body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p><strong>Which unit testing approach and WHY do you prefer?</strong></p> <p>Inheritance-driven-testing</p> <pre><code>public class GivenSynchronizedDataLink : TestBase { internal SynchronizedDataLink Subject { get; private set; } protected Mock&lt;IDataLink&gt; DataLinkFake { get; private set; } protected Mock&lt;IAutoReaderWriterLock&gt; ReaderWriterFake { get; private set; } private Fixture fixture; protected override void Setup() { fixture = new Fixture(); ReaderWriterFake = new Mock&lt;IAutoReaderWriterLock&gt;(); DataLinkFake = new Mock&lt;IDataLink&gt;(); } protected override void Given() { Subject = new SynchronizedDataLink(DataLinkFake.Object, () =&gt; ReaderWriterFake.Object); } protected T Any&lt;T&gt;() { return fixture.Create&lt;T&gt;(); } } [TestClass] public class WhenDisposeCalled : GivenSynchronizedDataLink { [TestMethod] public void ThenAquiresWriteLock() { ReaderWriterFake.Verify(x =&gt; x.Dispose(), Times.Once()); } protected override void When() { Subject.Dispose(); } } [TestClass] public class WhenDisposeCalledTwice : GivenSynchronizedDataLink { [TestMethod] public void ThenAquiresWriteLockOnlyOnce() { ReaderWriterFake.Verify(x =&gt; x.Dispose(), Times.Once()); } protected override void When() { Subject.Dispose(); Subject.Dispose(); } } [TestClass] public class WhenGetMinStampGreaterThanCalled : GivenSynchronizedDataLink { private Mock&lt;IDisposable&gt; lockRealeaserMock; private DateTime stamp; [TestMethod] public void ThenAquiresReadLock() { ReaderWriterFake.Verify(x =&gt; x.AcquireReadLock(), Times.Once()); } [TestMethod] public void ThenInvokesDataLink() { DataLinkFake.Verify(x =&gt; x.GetMinStampGreaterThan(stamp), Times.Once()); } [TestMethod] public void ThenReleasesReadLock() { lockRealeaserMock.Verify(x =&gt; x.Dispose(), Times.Once()); } protected override void Setup() { base.Setup(); lockRealeaserMock = new Mock&lt;IDisposable&gt;(); ReaderWriterFake.Setup(x =&gt; x.AcquireReadLock()) .Returns(lockRealeaserMock.Object); } protected override void Given() { base.Given(); stamp = Any&lt;DateTime&gt;(); } protected override void When() { Subject.GetMinStampGreaterThan(stamp); } } [TestClass] public class WhenRemoveValuesWithArrayCalled : GivenSynchronizedDataLink { private Mock&lt;IDisposable&gt; lockRealeaserMock; private ERemoveOptions options; private DateTime[] stamps; [TestMethod] public void ThenAquiresWriteLock() { ReaderWriterFake.Verify(x =&gt; x.AcquireWriteLock(), Times.Once()); } [TestMethod] public void ThenInvokesDataLink() { DataLinkFake.Verify(x =&gt; x.RemoveValues(stamps, options), Times.Once()); } [TestMethod] public void ThenReleasesWriteLock() { lockRealeaserMock.Verify(x =&gt; x.Dispose(), Times.Once()); } protected override void Setup() { base.Setup(); lockRealeaserMock = new Mock&lt;IDisposable&gt;(); ReaderWriterFake.Setup(x =&gt; x.AcquireWriteLock()) .Returns(lockRealeaserMock.Object); } protected override void Given() { base.Given(); stamps = Any&lt;DateTime[]&gt;(); options = Any&lt;ERemoveOptions&gt;(); } protected override void When() { Subject.RemoveValues(stamps, options); } } [TestClass] public class WhenRemoveValuesWithIntervalCalled : GivenSynchronizedDataLink { private DateTime fromIncl; private Mock&lt;IDisposable&gt; lockRealeaserMock; private ERemoveOptions options; private DateTime tillIncl; [TestMethod] public void ThenAquiresWriteLock() { ReaderWriterFake.Verify(x =&gt; x.AcquireWriteLock(), Times.Once()); } [TestMethod] public void ThenInvokesDataLink() { DataLinkFake.Verify(x =&gt; x.RemoveValues(fromIncl, tillIncl, options), Times.Once()); } [TestMethod] public void ThenReleasesWriteLock() { lockRealeaserMock.Verify(x =&gt; x.Dispose(), Times.Once()); } protected override void Setup() { base.Setup(); lockRealeaserMock = new Mock&lt;IDisposable&gt;(); ReaderWriterFake.Setup(x =&gt; x.AcquireWriteLock()) .Returns(lockRealeaserMock.Object); } protected override void Given() { base.Given(); fromIncl = Any&lt;DateTime&gt;(); tillIncl = Any&lt;DateTime&gt;(); options = Any&lt;ERemoveOptions&gt;(); } protected override void When() { Subject.RemoveValues(fromIncl, tillIncl, options); } } [TestClass] public class WhenSaveValuesCalled : GivenSynchronizedDataLink { private Mock&lt;IDisposable&gt; lockRealeaserMock; private UniqueDescendingValueCollection values; [TestMethod] public void ThenAquiresWriteLock() { ReaderWriterFake.Verify(x =&gt; x.AcquireWriteLock(), Times.Once()); } [TestMethod] public void ThenInvokesDataLink() { DataLinkFake.Verify(x =&gt; x.SaveValues(values), Times.Once()); } [TestMethod] public void ThenReleasesWriteLock() { lockRealeaserMock.Verify(x =&gt; x.Dispose(), Times.Once()); } protected override void Setup() { base.Setup(); lockRealeaserMock = new Mock&lt;IDisposable&gt;(); ReaderWriterFake.Setup(x =&gt; x.AcquireWriteLock()) .Returns(lockRealeaserMock.Object); } protected override void When() { values = AnyValues(); Subject.SaveValues(values); } private UniqueDescendingValueCollection AnyValues() { return new UniqueDescendingValueCollection(new IValue[0]); } } </code></pre> <p>Single class</p> <pre><code>[TestClass] public class SynchronizedDataLinkTests { private readonly SynchronizedDataLink cut; private readonly Mock&lt;IDataLink&gt; dataLinkFake; private readonly Fixture fixture; private readonly Mock&lt;IAutoReaderWriterLock&gt; readerWriterFake; public SynchronizedDataLinkTests() { fixture = new Fixture(); readerWriterFake = new Mock&lt;IAutoReaderWriterLock&gt;(); dataLinkFake = new Mock&lt;IDataLink&gt;(); cut = new SynchronizedDataLink(dataLinkFake.Object, () =&gt; readerWriterFake.Object); } [TestMethod] public void Dispose_DisposesLock() { cut.Dispose(); readerWriterFake.Verify(x =&gt; x.Dispose(), Times.Once()); } [TestMethod] public void GetMinStampGreaterThan_AquiresReadLock() { ExecuteGetMinStampGreaterThan(); readerWriterFake.Verify(x =&gt; x.AcquireReadLock(), Times.Once()); } [TestMethod] public void GetMinStampGreaterThan_InvokesDataLink() { DateTime stamp = ExecuteGetMinStampGreaterThan(); dataLinkFake.Verify(x =&gt; x.GetMinStampGreaterThan(stamp), Times.Once()); } [TestMethod] public void GetMinStampGreaterThan_ReleasesReadLock() { var lockRealeaserMock = new Mock&lt;IDisposable&gt;(); readerWriterFake.Setup(x =&gt; x.AcquireReadLock()) .Returns(lockRealeaserMock.Object); ExecuteGetMinStampGreaterThan(); lockRealeaserMock.Verify(x =&gt; x.Dispose(), Times.Once()); } [TestMethod] public void RemoveValuesWithArray_AquiresWriteLock() { ExecuteRemoveValuesWithArray(); readerWriterFake.Verify(x =&gt; x.AcquireWriteLock(), Times.Once()); } [TestMethod] public void RemoveValuesWithArray_InvokesDataLink() { Tuple&lt;DateTime[], ERemoveOptions&gt; input = ExecuteRemoveValuesWithArray(); dataLinkFake.Verify(x =&gt; x.RemoveValues(input.Item1, input.Item2), Times.Once()); } [TestMethod] public void RemoveValuesWithArray_ReleasesWriteLock() { var lockRealeaserMock = new Mock&lt;IDisposable&gt;(); readerWriterFake.Setup(x =&gt; x.AcquireWriteLock()) .Returns(lockRealeaserMock.Object); ExecuteRemoveValuesWithArray(); lockRealeaserMock.Verify(x =&gt; x.Dispose(), Times.Once()); } [TestMethod] public void RemoveValuesWithInterval_AquiresWriteLock() { ExecuteRemoveValuesWithInterval(); readerWriterFake.Verify(x =&gt; x.AcquireWriteLock(), Times.Once()); } [TestMethod] public void RemoveValuesWithInterval_InvokesDataLink() { Tuple&lt;DateTime, DateTime, ERemoveOptions&gt; input = ExecuteRemoveValuesWithInterval(); dataLinkFake.Verify(x =&gt; x.RemoveValues(input.Item1, input.Item2, input.Item3), Times.Once()); } [TestMethod] public void RemoveValuesWithInterval_ReleasesWriteLock() { var lockRealeaserMock = new Mock&lt;IDisposable&gt;(); readerWriterFake.Setup(x =&gt; x.AcquireWriteLock()) .Returns(lockRealeaserMock.Object); ExecuteRemoveValuesWithInterval(); lockRealeaserMock.Verify(x =&gt; x.Dispose(), Times.Once()); } [TestMethod] public void SaveValues_AquiresWriteLock() { ExecuteSaveValues(); readerWriterFake.Verify(x =&gt; x.AcquireWriteLock(), Times.Once()); } [TestMethod] public void SaveValues_InvokesDataLink() { UniqueDescendingValueCollection values = ExecuteSaveValues(); dataLinkFake.Verify(x =&gt; x.SaveValues(values), Times.Once()); } [TestMethod] public void SaveValues_ReleasesWriteLock() { var lockRealeaserMock = new Mock&lt;IDisposable&gt;(); readerWriterFake.Setup(x =&gt; x.AcquireWriteLock()) .Returns(lockRealeaserMock.Object); ExecuteSaveValues(); lockRealeaserMock.Verify(x =&gt; x.Dispose(), Times.Once()); } private T Any&lt;T&gt;() { return fixture.Create&lt;T&gt;(); } private UniqueDescendingValueCollection AnyValues() { return new UniqueDescendingValueCollection(new IValue[0]); } private DateTime ExecuteGetMinStampGreaterThan() { var stamp = Any&lt;DateTime&gt;(); cut.GetMinStampGreaterThan(stamp); return stamp; } private Tuple&lt;DateTime[], ERemoveOptions&gt; ExecuteRemoveValuesWithArray() { var stamp = Any&lt;DateTime[]&gt;(); var options = Any&lt;ERemoveOptions&gt;(); cut.RemoveValues(stamp, options); return new Tuple&lt;DateTime[], ERemoveOptions&gt;(stamp, options); } private Tuple&lt;DateTime, DateTime, ERemoveOptions&gt; ExecuteRemoveValuesWithInterval() { var from = Any&lt;DateTime&gt;(); var till = Any&lt;DateTime&gt;(); var options = Any&lt;ERemoveOptions&gt;(); cut.RemoveValues(from, till, options); return new Tuple&lt;DateTime, DateTime, ERemoveOptions&gt;(from, till, options); } private UniqueDescendingValueCollection ExecuteSaveValues() { UniqueDescendingValueCollection values = AnyValues(); cut.SaveValues(values); return values; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:05:45.850", "Id": "78090", "Score": "0", "body": "Your question is asking for an opinion. Could you rephrase it to be less opinionated (is this a real word ) ? You could chose one of those approach and see the review of it. You could always make a second question for the second and see which one looks best, but it should not be in the same question IMO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:44:22.187", "Id": "78111", "Score": "1", "body": "I personally prefer the second, but perhaps with more `TestPropertyAttribute`s if you want to be able to find them quickly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T21:29:48.167", "Id": "78205", "Score": "0", "body": "I want to know which implementation is more readable and maintainable. Isn't it a part of test code review?" } ]
[ { "body": "<p>I'd favor the second one, it seems that the first one abusing inheritance (uses it for only code reuse) and I think it's harder to read because you have to go back and forth to the parent class.</p>\n\n<ul>\n<li><em>Effective Java, 2nd Edition</em>, <em>Item 16: Favor composition over inheritance</em></li>\n<li><a href=\"https://softwareengineering.stackexchange.com/a/12446/36726\">Code Smell: Inheritance Abuse</a></li>\n<li><a href=\"http://www.approxion.com/?p=120\" rel=\"nofollow noreferrer\">The Principle of Proximity</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T16:21:26.420", "Id": "44879", "ParentId": "44861", "Score": "2" } } ]
{ "AcceptedAnswerId": "44879", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T13:35:13.797", "Id": "44861", "Score": "2", "Tags": [ "c#", ".net", "unit-testing" ], "Title": "Unit testing - test class inheritance vs single test class" }
44861
<p>Is there a way to write this better or more Clojure way? Especially the last part with <code>with-open</code> and the <code>let</code>. Should I put the <code>-&gt;</code> form into a separate function? Is this function to overloaded (to much stuff) or is this still ok?</p> <pre><code> (defn scrape-book-cover [url image-filename] (let [out-stream (io/output-stream image-filename) image (-&gt; url (java.net.URL.) (html/html-resource) (html/select [:div.bookcoverXXL :&gt; :div :&gt; :img]) (first) (:attrs) (:src) (-&gt;&gt; (str "http:")) (http-client/get {:as :byte-array}) (:body))] (with-open [out out-stream] (.write out image)))) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T16:12:57.260", "Id": "78150", "Score": "2", "body": "You have many forms with single element you can ignore parens around them `java.net.URL. html/html-resource .... first :attrs :src` instead of `(java.net.URL.) (html/html-resource) .... (first) (:attrs) (:src)`. Why do you add `\"http:\"` at the beginning of src attribute of the img element?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T18:19:20.253", "Id": "78170", "Score": "0", "body": "Thanks for the hint with the parens around single argument functions. The `\"http:\"` needs to be added because the url begins with `\"//\"` and clj-http can't deal with that (`MalformedURLException`)" } ]
[ { "body": "<p>@abuzittingillifirca made a good point in that you can leave the parentheses off of the <code>-&gt;</code> forms that are just a single element. </p>\n\n<p><code>html/html-resource</code> is actually quite flexible; it can take a variety of different kinds of arguments, including strings, URLs, input streams, etc. Assuming the <code>url</code> argument to your function is a string, you can take out the <code>java.net.URL.</code> part and just feed <code>url</code> directly into <code>html/html-resource</code>. In fact, I would begin the <code>-&gt;</code> part like this:</p>\n\n<pre><code>(-&gt; (html/html-resource url)\n ...\n</code></pre>\n\n<p>So <code>(html/html-resource url)</code> is like the \"first step\" in the threading macro. Less steps makes your code appear simpler and easier to read, just as long as the steps aren't overly complicated.</p>\n\n<p>For the <code>(first) (:attrs) (:src)</code> part, you might consider using <a href=\"http://clojuredocs.org/clojure_core/1.2.0/clojure.core/get-in\" rel=\"nofollow\">get-in</a>. This function comes in handy for navigating nested associative structures like vectors and maps -- it's perfect for something like enlive. You could re-word this part of your code as:</p>\n\n<pre><code>(get-in [0 :attrs :src])\n</code></pre>\n\n<p>It isn't much shorter than the original, but I think it reads better, and it \"feels\" shorter because you're only calling one function.</p>\n\n<p>It's probably not very Clojurian to have a <code>-&gt;&gt;</code> macro among the steps to a <code>-&gt;</code> macro. If you have a situation like this, where one of the steps to the <code>-&gt;</code> requires you to put the argument last instead of second, you can do something like <code>(#(str \"http:\" %))</code> -- create an anonymous function literal with the <code>%</code> wherever you want the argument to go, and then call it by putting parentheses around it.</p>\n\n<p>So, here is how I would refactor your code:</p>\n\n<pre><code>(defn scrape-book-cover [url image-filename]\n (let [out-stream (io/output-stream image-filename)\n image (-&gt; (html/html-resource url)\n (html/select [:div.bookcoverXXL :&gt; :div :&gt; :img])\n (get-in [0 :attrs :src])\n (#(str \"http:\" %))\n (http-client/get {:as :byte-array})\n :body)]\n (with-open [out out-stream]\n (.write out image))))\n</code></pre>\n\n<p>EDIT: To answer your question: No, I don't think this function is overloaded. When you simplify like I did above, it doesn't seem too long or complicated.</p>\n\n<p>EDIT 2: Of course, there's nothing stopping you from pulling out the <code>-&gt;</code> part and making it a separate function. It might make your code easier to read. You could call the function something like <code>imgurl-&gt;bytes</code>.</p>\n\n<pre><code>(defn imgurl-&gt;bytes [url]\n (-&gt; (html/html-resource url)\n (html/select [:div.bookcoverXXL :&gt; :div :&gt; :img])\n (get-in [0 :attrs :src])\n (#(str \"http:\" %))\n (http-client/get {:as :byte-array})\n :body))\n\n(defn scrape-book-cover [url image-filename]\n (let [out-stream (io/output-stream image-filename)\n image (imgurl-&gt;bytes url)]\n (with-open [out out-stream]\n (.write out image))))\n</code></pre>\n\n<p>Come to think of it, I like this better. If you look at a lot of Clojure code on github, you will see a lot of things broken up into simple helper functions. I suppose it is generally idiomatic in Clojure to break things up in helper functions.</p>\n\n<p>EDIT 3 (5/16/14): Someone just upvoted my answer, which made me remember this code and have a quick re-visit. You could actually further refactor this version of the <code>scrape-book-cover</code> function by taking out the <code>let</code> statement:</p>\n\n<pre><code>(defn scrape-book-cover [url image-filename]\n (with-open [out (io/output-stream image-filename)]\n (.write out (imgurl-&gt;bytes url))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T19:27:41.247", "Id": "78182", "Score": "0", "body": "I have no knowledge in Clojure what so ever, but your answer are always well-presented and in a good format! Your advises seems always good! + 1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T19:34:30.523", "Id": "78183", "Score": "3", "body": "Thanks! :) I was surprised people weren't doing more reviews of Clojure code on here, so I figured I'd make some contributions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T21:24:48.743", "Id": "78203", "Score": "0", "body": "Thanks a *lot*! This helps me understand a lot of other things as well! One little thing I've come up with the replacement of the ugly `->>` form inside the `->` was the `as->` form: `(as-> u (str \"http:\" u))`. Is this more Clojure idiomatic?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T21:51:46.223", "Id": "78208", "Score": "0", "body": "I've never seen that before... is there documentation online somewhere? I think `(#(str \"http:\" %))` is plenty idiomatic. I've read a few books on Clojure and I remember seeing that syntax used somewhere, maybe in *The Joy of Clojure*. I always find it kind of awkward deciding which threading macro to use, because I have to stop and think, \"how many of these functions would I need to pass in the argument in the second position, and how many would I need to pass it in the last position?\" I usually just kind of guess and then use `(#(fn args %))` as needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T22:08:44.470", "Id": "78213", "Score": "0", "body": "@DaveYarwood: See here: http://clojure.github.io/clojure/clojure.core-api.html#clojure.core/as-> But you made a good point for using an plain old lambda for that. It is much more visible whats going on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T13:51:50.407", "Id": "78298", "Score": "0", "body": "Ah! Looks like `as->` is new as of Clojure 1.5. It looks kind of promising! From the description, it appears to work just like `->` or `->>`, except you explicitly show where the argument fits in by giving it a name. You would use it something like this: `(as-> x (html/html-resource x) (html/select x [:div.bookcoverXXL :> :div :> :img]) (get-in x [0 :attrs :src]) (str \"http:\" x) ...` etc. I like it! I'm glad you mentioned it, I had no idea this existed. It's kind of a nice solution for the `->` vs. `->>` problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T14:21:46.217", "Id": "78308", "Score": "0", "body": "Whoops, reading [the docs](https://github.com/clojure/clojure/blob/master/changes.md) more, it looks like I screwed that up slightly. It would be `(as-> (html/html-resource url) x (html/select x ...` etc. The example from the docs is like yours -- using it just for a single step within a `->` macro -- but it has support for multiple forms, like the example I gave in my last comment (just flip the first `x` and `(html/html-resource url)`. It looks handy either way!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T19:21:58.097", "Id": "44898", "ParentId": "44862", "Score": "9" } } ]
{ "AcceptedAnswerId": "44898", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T13:47:16.210", "Id": "44862", "Score": "11", "Tags": [ "clojure", "web-scraping" ], "Title": "Is this the Clojure way to web-scrape a book cover image?" }
44862
<p>I have the following two methods of completing the same task, however I'd like to know <strong><em>which is the preferred method and WHY?</em></strong> Or if there are any suggestions to complete the task in an even better, cleaner way.</p> <p><em><strong>The task</em></strong></p> <p>Find part 1 of <code>$string</code> in the example <code>$string = '1/2/3/4';</code> so the first part would be '1'. </p> <p>Match that value to the corresponding 'id' from entries in the database, then return the 'filename' that corresponds to the 'id'. </p> <p>Then loop again until each part of the initial string has a corresponding value. </p> <p>The 'filename' values are each then output to a string delimited by a '/'.</p> <p>EG. <code>filename1/filename2/filename3/filename4</code></p> <p><em><strong>Option 1</em></strong></p> <pre><code>$string = '1/2/3/4'; $change = str_replace('/',',',$string); $result = $connection-&gt;query("SELECT id, filename FROM pages WHERE id IN($change) ORDER BY FIELD($change)"); while($row = $result-&gt;fetch_assoc()) { $match[] = $row; } foreach ($match as $array) { echo $array['filename'].'/'; } </code></pre> <p><strong>UPDATE</strong> This works fine if there are more than one parts to the string eg. '1/2/3/4' but I get the following error if just '1' is used.</p> <p><code>Fatal error: Call to a member function fetch_assoc() on a non-object in C:\xampp\htdocs\admin\pages\test2.php on line 22</code></p> <p><strong>OR</strong></p> <p><em><strong>Option 2</em></strong></p> <pre><code>$string = '1/2/3/4'; $split = explode('/', $string); $split = array_flip($split); $result = $connection-&gt;query("SELECT id, filename FROM pages"); while ($row = $result-&gt;fetch_assoc()) { $new_array[$row['id']] = $row['filename']; } $matched = array_intersect_key($new_array, $split); $join = implode('/', $matched); // join $matched as string. echo $join; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:05:12.077", "Id": "78089", "Score": "0", "body": "is the string always guaranteed to be delimited by /" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:08:33.493", "Id": "78094", "Score": "0", "body": "Yes, unless there is only one value then it will just be the value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:16:03.040", "Id": "78100", "Score": "0", "body": "if $string is 6/10/33/44 - then we would be matching 6 into the DB - then lets say we get two files out of that then you want to echo the two file name (assuming file name is codereview and stackexchange) it would be codereview/stackexchange ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:27:50.007", "Id": "78104", "Score": "0", "body": "6 would correspond to one filename. eg. 'codereview', 10 would be another filename eg. 'stackexchange'. so 6/10 = codereview/stackexchange" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:29:14.867", "Id": "78106", "Score": "0", "body": "ahhh ok -gotcha." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:31:00.697", "Id": "78108", "Score": "0", "body": "essentially, each number is an index for the filename. each unique." } ]
[ { "body": "<pre><code>$string = '1/2/3/4';\n\n$change = str_replace('/',',',$string);\n\n$result = $connection-&gt;query(\"SELECT id, filename FROM pages WHERE id IN($change) ORDER BY FIELD(id,$change)\");\n\n$new_string = \"\";\nwhile($row = $result-&gt;fetch_assoc()) {\n $new_string .= $row['filename'].\"/\";\n}\n\n$new_string = substr($new_string,0,-1);\n\necho $new_string;\n</code></pre>\n\n<p>Less looping - the <code>match[] = $row</code> was unnecessary IMO because you want a string back only...so you concatenate the file name with a <code>/</code> delimiter and then the last slash is removed with <code>sub_str</code>.</p>\n\n<p><strong>Updated the fixes including single query match.</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:12:06.420", "Id": "78119", "Score": "0", "body": "Just tested and only pulls the last part of the string, ie. '4' in the example. also sub_str should be substr." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:28:29.780", "Id": "78124", "Score": "1", "body": "i apologize - fixed it - forgot the dot in $new_string .= $row" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:34:17.740", "Id": "78132", "Score": "0", "body": "i'll give it a test now" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:53:05.787", "Id": "78144", "Score": "0", "body": "this doesn't (as with my option 1) if there is only one part to the string, eg. '1' instead of '1/2/3' etc. I get... `Fatal error: Call to a member function fetch_assoc() on a non-object in C:\\xampp\\htdocs\\admin\\pages\\test2.php on line 22`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:56:00.890", "Id": "78145", "Score": "0", "body": "It will be due to `query(\"SELECT id, filename FROM pages WHERE id IN($change) ORDER BY FIELD($change)\")` expecting more than one value in the brackets." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T16:10:41.953", "Id": "78149", "Score": "0", "body": "check my edit. it should work for singular return now also." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:36:05.087", "Id": "44866", "ParentId": "44863", "Score": "3" } } ]
{ "AcceptedAnswerId": "44866", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T13:51:56.160", "Id": "44863", "Score": "2", "Tags": [ "php", "sql", "array" ], "Title": "Two script completing the same task, which is the best way?" }
44863
<p>I have a multidimensional array as a result from a webservice called from PHP. I cannot edit the webservice, but the result is as</p> <pre><code>array (size=5) 'id' =&gt; int 0 'name' =&gt; array (size=7) 'it' =&gt; string 'Tutti' (length=5) 'ca' =&gt; string 'Tots' (length=4) 'es' =&gt; string 'Todos' (length=5) 'de' =&gt; string 'Alle' (length=4) 'fr' =&gt; string 'Tous' (length=4) 'nl' =&gt; string 'Alle' (length=4) 'en' =&gt; string 'All' (length=3) 'tree' =&gt; array (size=0) empty 'languages' =&gt; array (size=7) 'subTypes' =&gt; array (size=4) 0 =&gt; array (size=5) 'id' =&gt; int 1 'name' =&gt; array (size=29) ... 'tree' =&gt; array (size=1) ... 'languages' =&gt; array (size=29) ... 'subTypes' =&gt; array (size=3) ... 1 =&gt; array (size=5) 'id' =&gt; int 2 'name' =&gt; array (size=29) ... 'tree' =&gt; array (size=1) ... 'languages' =&gt; array (size=29) ... 'subTypes' =&gt; array (size=6) ... </code></pre> <p>As you can see, you can interpret it as a multidimensional array of objects. Each objects can have child objects of same type.</p> <p>My goal is to get <strong>only</strong> the elements on a specific language, fe <code>en</code> (and thus rest is not taken). I thought to use a recursive function.</p> <pre><code>// filter array function getByKey($array, $search, $level, $valuesUsed) { echo '&lt;ul&gt;'; foreach($array as $key =&gt; $value) { if(is_array($array[$key])) { $valuesUsed = getByKey($array[$key], $search, $level + 1, $valuesUsed); } else if ($key === $search) { if(!in_array($value, $valuesUsed)) { echo "&lt;li&gt; $key = $value &lt;/li&gt;"; $valuesUsed[] = $value; } } } echo '&lt;/ul&gt;'; return $valuesUsed; } </code></pre> <p>Then I call the above function from my HTML template by</p> <pre><code>&lt;div id="foo"&gt; &lt;?php getByKey($routeTypes, 'en', 0, array()); ?&gt; &lt;/div&gt; </code></pre> <p><code>$routeTypes</code> is the array, obtained from the webservice. It works as expected, it results as the list here below, which I can wrap with a js library.</p> <pre><code>&lt;ul&gt; &lt;li&gt;this is level1&lt;/li&gt; &lt;li&gt;this is level1&lt;/li&gt; &lt;li&gt; &lt;ul&gt; &lt;li&gt;this is level 2&lt;/li&gt; &lt;li&gt;this is level 2&lt;/li&gt; &lt;li&gt; ... level++ &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Now, I'm questioning myself if this can be improved ? It doesn't take long to have a list from a large multidimensional array. (a simple <code>print_r</code> command resulted in 45000+ characters). </p> <p>Especially checking the <code>$valuesUsed</code> array, to prevent duplicates (yes the webservice has objects which contains child keys which is similar to level - 2 parent (or on other level ...... ))</p> <p>Each time I am running through the lower levels, I am looping through the <code>$valuesUsed</code> array. Is there not a better way to loop through the sublevels ? Maybe an <a href="http://be2.php.net/manual/en/function.array-walk.php" rel="nofollow"><code>array_walk()</code></a> or <a href="http://be2.php.net/manual/en/function.array-walk-recursive.php" rel="nofollow"><code>array_walk_recursive()</code></a> with a callback function ?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:03:05.650", "Id": "78086", "Score": "0", "body": "Is this complete code ? It's seems to be missing some part ? Does it work on it's own ? Are you here for a review or something else ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:09:31.977", "Id": "78095", "Score": "0", "body": "yes, i'm here for a review. Just asking if the recursive function can be improved. The above function will be called in the HTML template. (it displays the list of which i want on the webpage). Edited my post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:16:47.910", "Id": "78101", "Score": "0", "body": "I was asking to come up with a title. The title of your question should describe what your code do!" } ]
[ { "body": "<p>You can choose a (key => value) pair recursively with this function:</p>\n\n<pre><code>function array_value_recursive($key, array $arr){\n $val = array();\n array_walk_recursive($arr, function($v, $k) use($key, &amp;$val){\n if($k == $key) array_push($val, $v);\n });\n return count($val) &gt; 1 ? $val : array_pop($val);\n}\n</code></pre>\n\n<p>This function makes use of <a href=\"http://www.php.net/manual/en/function.array-walk-recursive.php\" rel=\"nofollow\" title=\"array_walk_recursive&#40;&#41;\">array_walk_recursive()</a> to push into a placeholder array whatever value is pointed to by whichever key matches our needle key. </p>\n\n<p>Proof code:</p>\n\n<pre><code>$array = array(\n 'id' =&gt; 0,\n 'name' =&gt; array(\n 'it' =&gt; 'Tutti',\n 'ca' =&gt; 'Tots',\n 'es' =&gt; 'Todos', \n 'de' =&gt; 'Alle' ,\n 'fr' =&gt; 'Tous',\n 'nl' =&gt; 'Alle',\n 'en' =&gt; 'All'\n ),\n 'languages' =&gt; array(\n \"d\" =&gt; 33\n ),\n 'subTypes' =&gt; array(\n 0 =&gt; array(\n 'id' =&gt; 1,\n 'name' =&gt; array(\n 'it' =&gt; 'Tutti',\n 'ca' =&gt; 'Tots',\n 'es' =&gt; 'Todos', \n 'de' =&gt; 'Alle' ,\n 'fr' =&gt; 'Tous',\n 'nl' =&gt; 'Alle',\n 'en' =&gt; 'All'\n )\n ),\n 1 =&gt; array(\n 'id' =&gt; 1,\n 'name' =&gt; array(\n 'it' =&gt; 'Tutti',\n 'ca' =&gt; 'Tots',\n 'es' =&gt; 'Todos', \n 'de' =&gt; 'Alle' ,\n 'fr' =&gt; 'Tous',\n 'nl' =&gt; 'Alle',\n 'en' =&gt; 'All'\n )\n ),\n 2 =&gt; array(\n 'id' =&gt; 1,\n 'name' =&gt; array(\n 'it' =&gt; 'Tutti',\n 'ca' =&gt; 'Tots',\n 'es' =&gt; 'Todos', \n 'de' =&gt; 'Alle' ,\n 'fr' =&gt; 'Tous',\n 'nl' =&gt; 'Alle',\n 'en' =&gt; 'All'\n )\n )\n )\n);\n\nprint_r(array_value_recursive(\"de\", $array));\n</code></pre>\n\n<p>The above test code, which seeks all \"de\" keys, will output: </p>\n\n<pre><code>Array ( \n [0] =&gt; Alle \n [1] =&gt; Alle \n [2] =&gt; Alle \n [3] =&gt; Alle\n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T08:03:30.610", "Id": "78708", "Score": "0", "body": "thanks for your suggestion, but yours code didn't kept the child level of the main array. The goal is to get a nested list (menu - submenu) as mentioned in my post." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T14:40:34.727", "Id": "44975", "ParentId": "44864", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T13:52:08.773", "Id": "44864", "Score": "5", "Tags": [ "php", "recursion" ], "Title": "recursive function : filtering large multidimensional array by key element to HTML list" }
44864
<p>I wrote a <code>cstring</code> parser. It has to work with a relatively wide amount of arguments (usually 3 or 4, but maybe in future with a different amount), which are separated by an <code>,</code> or <code>;</code>. My wish is to make at least Function 1 less static and save some code. However, I don't really want to use dynamic memory allocation (just if it not to avoid and would bring a benefit). The whole code should run on ATMega2560. This is why I cannot use higher library functions.</p> <p>Function 1:</p> <pre><code>float *Receiver::parse_pid_substr(char* buffer) { static float pids[8]; memset(pids, 0, 8*sizeof(float) ); char cI[32], cII[32], cIII[32], cIV[32], cV[32], cVI[32], cVII[32], cVIII[32]; size_t i = 0, c = 0, p = 0; for(; i &lt; strlen(buffer); i++) { if(buffer[i] == '\0') { break; } else if(buffer[i] != ',') { switch(p) { case 0: cI[c] = buffer[i]; cI[c+1] = '\0'; break; case 1: cII[c] = buffer[i]; cII[c+1] = '\0'; break; case 2: cIII[c] = buffer[i]; cIII[c+1] = '\0'; break; case 3: cIV[c] = buffer[i]; cIV[c+1] = '\0'; break; case 4: cV[c] = buffer[i]; cV[c+1] = '\0'; break; case 5: cVI[c] = buffer[i]; cVI[c+1] = '\0'; break; case 6: cVII[c] = buffer[i]; cVII[c+1] = '\0'; break; case 7: cVIII[c] = buffer[i]; cVIII[c+1] = '\0'; break; } c++; } else { p++; c = 0; continue; } } pids[0] = atof(cI); pids[1] = atof(cII); pids[2] = atof(cIII); pids[3] = atof(cIV); pids[4] = atof(cV); pids[5] = atof(cVI); pids[6] = atof(cVII); pids[7] = atof(cVIII); return pids; } </code></pre> <p>Function 2:</p> <pre><code>bool Receiver::parse_pid_conf(char* buffer) { if(m_pHalBoard == NULL) { return false; } else if(m_rgChannelsRC[2] &gt; RC_THR_MIN) { // If motors run: Do nothing! return false; } // process cmd bool bRet = false; char *str = strtok(buffer, "*"); // str = roll, pit, thr, yaw char *chk = strtok(NULL, "*"); // chk = chksum if(verf_chksum(str, chk) ) { // if chksum OK char *cstr; for(uint_fast8_t i = 0; i &lt; PID_ARGS; i++) { if(i == 0) cstr = strtok (buffer, ";"); else cstr = strtok (NULL, ";"); float *pids = parse_pid_substr(cstr); switch(i) { case 0: m_pHalBoard-&gt;m_rgPIDS[PID_PIT_RATE].kP(pids[0]); m_pHalBoard-&gt;m_rgPIDS[PID_PIT_RATE].kI(pids[1]); m_pHalBoard-&gt;m_rgPIDS[PID_PIT_RATE].imax(pids[2]); break; case 1: m_pHalBoard-&gt;m_rgPIDS[PID_ROL_RATE].kP(pids[0]); m_pHalBoard-&gt;m_rgPIDS[PID_ROL_RATE].kI(pids[1]); m_pHalBoard-&gt;m_rgPIDS[PID_ROL_RATE].imax(pids[2]); break; case 2: m_pHalBoard-&gt;m_rgPIDS[PID_YAW_RATE].kP(pids[0]); m_pHalBoard-&gt;m_rgPIDS[PID_YAW_RATE].kI(pids[1]); m_pHalBoard-&gt;m_rgPIDS[PID_YAW_RATE].imax(pids[2]); break; case 3: m_pHalBoard-&gt;m_rgPIDS[PID_THR_ACCL].kP(pids[0]); m_pHalBoard-&gt;m_rgPIDS[PID_THR_ACCL].kI(pids[1]); m_pHalBoard-&gt;m_rgPIDS[PID_THR_ACCL].imax(pids[2]); break; case 4: m_pHalBoard-&gt;m_rgPIDS[PID_PIT_STAB].kP(pids[0]); m_pHalBoard-&gt;m_rgPIDS[PID_ROL_STAB].kP(pids[1]); m_pHalBoard-&gt;m_rgPIDS[PID_YAW_STAB].kP(pids[2]); m_pHalBoard-&gt;m_rgPIDS[PID_THR_STAB].kP(pids[3]); bRet = true; break; } } } return bRet; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T19:19:19.667", "Id": "78353", "Score": "0", "body": "Should really open this up to C developers. Nothing C++ about it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T04:39:38.650", "Id": "78468", "Score": "0", "body": "@LokiAstari It may be idiomatically closer to C than C++, but the method signature makes it definitely C++, as the `::` makes it fail to parse as C." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T06:36:37.037", "Id": "78477", "Score": "0", "body": "@200_success: True. But that will not help the OP. What he rely need is C help not C++ help. The function signatures are just 3 lines and play no significant part in the code. Thus you are preventing qualified C people from spotting it and helping by applying the C++ tag and not the C tag." } ]
[ { "body": "<h1>Two-dimesional array</h1>\n\n<p>Your first function can be aggressively reduced by replacing <code>cI</code> and friends by a 2D array:</p>\n\n<pre><code>float *Receiver::parse_pid_substr(char* buffer) {\n static float pids[8];\n memset(pids, 0, 8*sizeof(float) );\n\n char rgcPIDS[8][32];\n size_t i = 0, c = 0, p = 0;\n for(; i &lt; strlen(buffer); i++) {\n if(buffer[i] == '\\0') {\n break;\n }\n else if(buffer[i] != ',') {\n rgcPIDS[p][c] = buffer[i];\n rgcPIDS[p][c+1] = '\\0';\n c++;\n } else {\n p++;\n c = 0;\n continue;\n }\n }\n\n for (int j = 0 ; j &lt; 8 ; ++j) {\n pids[j] = atof(chars[j]);\n }\n\n return pids;\n}\n</code></pre>\n\n<h1><code>continue</code></h1>\n\n<p>In the following piece of code:</p>\n\n<pre><code>} else {\n p++;\n c = 0;\n continue;\n}\n</code></pre>\n\n<p>The <code>else</code> clause is the last of your loop, and <code>continue</code> is the last instruction of that clause. You can remove <code>continue</code>: even without it, your function will still work and behave the same way as before.</p>\n\n<h1>Zero-initialization</h1>\n\n<p>Instead of using <code>memset</code> to zero-initialize your arrays, you can use the language zero-initialization for arrays whose bound is known at compile-time:</p>\n\n<pre><code>char rgcPIDS[8][32] = { 0 };\n</code></pre>\n\n<h1>Names</h1>\n\n<p>The names you use are all but explicit. While <code>i</code> is good as a loop iterator, <code>c</code> and <code>p</code> should have more explicit names.</p>\n\n<p><strong>NOTE:</strong> Hadn't it been for the <code>Receiver::</code>, I would have thought that your code was written in plain old C, and not in C++. Is it intentional?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:03:47.573", "Id": "78115", "Score": "0", "body": "Could you please adjust the position of the braces at the last for loop to be consistent with the rest of the code? It is really bothering me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:17:23.887", "Id": "78121", "Score": "0", "body": "@AJMansfield Of course. It's true that I didn't pay any attention to it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:47:17.990", "Id": "78139", "Score": "0", "body": "Yeah in this case it is desired to use C instead of C++ for string handling." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:54:31.543", "Id": "44870", "ParentId": "44867", "Score": "8" } }, { "body": "<p>At the top, you are declaring eight 32-character arrays, which later you use a switch with to decide which array to use. Instead, you should declare an array of arrays, the Morwenn did it, or you can use just one 256-character array. You can then just add a multiple of the <code>p</code> to the index in the first big switch block, reducing it to only one case:</p>\n\n<pre><code>cArrays[p&lt;&lt;5 + c] = buffer[i];\ncArrays[p&lt;&lt;5 + c+1] = '\\0';\n</code></pre>\n\n<p>There are a number of this type of optimization that you can do in your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:00:59.110", "Id": "44871", "ParentId": "44867", "Score": "5" } }, { "body": "<p>Without going into too much detail about your concrete code (I agree with the others that an array makes a lot more sense), I'd like to point out that many parser generators (flex, bison, re2c) generate essentially standalone code and don't need runtime library support. You may need to move some of the tables they generate from RAM to PROGMEM (i.e. flash), but other than that, such parsers should work fine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:08:06.597", "Id": "44872", "ParentId": "44867", "Score": "2" } } ]
{ "AcceptedAnswerId": "44870", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:46:01.103", "Id": "44867", "Score": "11", "Tags": [ "c", "strings", "parsing", "floating-point", "embedded" ], "Title": "Parsing comma-separated floats and semicolon-delimited commands" }
44867
<p>In <a href="https://codereview.stackexchange.com/questions/44821/print-out-table-with-start-end-temperatures-and-step-size/44829#comment78006_44829">this comment</a> the OP wrote,</p> <blockquote> <p>I am a newbie so i would like to know how would i parse the negetive numbers/arguments ?</p> </blockquote> <p>In <a href="https://codereview.stackexchange.com/q/44836/34757">this answer</a> @200_success showed an implementation using the strtod function.</p> <p>The following is my implementation of <a href="http://www.cplusplus.com/reference/cstdlib/strtod/" rel="nofollow noreferrer">the strtod function</a>:</p> <blockquote> <p>A valid floating point number for strtod using the "C" locale is formed by an optional sign character (+ or -), followed by a sequence of digits, optionally containing a decimal-point character (.), optionally followed by an exponent part (an e or E character followed by an optional sign and a sequence of digits).</p> </blockquote> <p>I'm not using a modern compiler so I didn't implement this portion of the spec.:</p> <blockquote> <p>If the correct value is out of the range of representable values for the type, a positive or negative HUGE_VAL is returned, and errno is set to ERANGE.</p> <p>If the correct value would cause underflow, the function returns a value whose magnitude is no greater than the smallest normalized positive number and sets errno to ERANGE.</p> </blockquote> <ul> <li>Is my implementation correct (does it return correct output for all input)?</li> <li>Is it easy to read even without comments?</li> <li>Is the set of test cases sufficiently complete?</li> <li>Any other suggestions for improvement?<sup>1</sup></li> </ul> <p><sup>1</sup><sub>(except comments on where I put <code>{ }</code> braces, and whether I use them around single-line control statements</sub></p> <pre><code>double strtod(const char* str, char** endptr) { double result = 0.0; char signedResult = '\0'; char signedExponent = '\0'; int decimals = 0; bool isExponent = false; bool hasExponent = false; bool hasResult = false; // exponent is logically int but is coded as double so that its eventual // overflow detection can be the same as for double result double exponent = 0; char c; for (; '\0' != (c = *str); ++str) { if ((c &gt;= '0') &amp;&amp; (c &lt;= '9')) { int digit = c - '0'; if (isExponent) { exponent = (10 * exponent) + digit; hasExponent = true; } else if (decimals == 0) { result = (10 * result) + digit; hasResult = true; } else { result += (double)digit / decimals; decimals *= 10; } continue; } if (c == '.') { if (!hasResult) { // don't allow leading '.' break; } if (isExponent) { // don't allow decimal places in exponent break; } if (decimals != 0) { // this is the 2nd time we've found a '.' break; } decimals = 10; continue; } if ((c == '-') || (c == '+')) { if (isExponent) { if (signedExponent || (exponent != 0)) break; else signedExponent = c; } else { if (signedResult || (result != 0)) break; else signedResult = c; } continue; } if (c == 'E') { if (!hasResult) { // don't allow leading 'E' break; } if (isExponent) break; else isExponent = true; continue; } // else unexpected character break; } if (isExponent &amp;&amp; !hasExponent) { while (*str != 'E') --str; } if (!hasResult &amp;&amp; signedResult) --str; if (endptr) *endptr = const_cast&lt;char*&gt;(str); for (; exponent != 0; --exponent) { if (signedExponent == '-') result /= 10; else result *= 10; } if (signedResult == '-') { if (result != 0) result = -result; // else I'm not used to working with double-precision numbers so I // was surprised to find my assert for "-0" failing, saying -0 != +0. } return result; } // This header is only needed for assert, not for strtod implementation #include &lt;cstring&gt; void assert(const char* s, double d, const char* remainder) { char* endptr; double result = strtod(s, &amp;endptr); if ((result!=d) || strcmp(endptr, remainder)) throw "failed"; } int main() { assert("0", 0, ""); assert("-0", 0, ""); assert("12", 12, ""); assert("23.5", 23.5, ""); assert("-14", -14, ""); assert("-", 0, "-"); assert("-2-a", -2, "-a"); assert("-2a", -2, "a"); assert("0.036", 0.036, ""); assert("12.5E2", 12.5E2, ""); assert("12.5E-3", 12.5E-3, ""); assert("12.5E0", 12.5E0, ""); assert("12.5E", 12.5, "E"); assert("12.5E-", 12.5, "E-"); assert("", 0, ""); assert("a", 0, "a"); assert("E10", 0, "E10"); assert("-E10", 0, "-E10"); assert("-0E10", 0, ""); assert(".3", 0, ".3"); assert("-.3", 0, "-.3"); strtod("42C", 0); // tests endptr == null assert("+12", 12, ""); assert("+-12", 0, "+-12"); assert("12.5E+3", 12.5E+3, ""); assert("12.5E+-3", 12.5, "E+-3"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:05:04.657", "Id": "78116", "Score": "1", "body": "What does using a 'modern compiler' have to do with implementing the out-of-range value part of the spec?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:07:01.673", "Id": "78118", "Score": "0", "body": "@AJMansfield I couldn't work out how to test for infinity given the headers I have; and I don't know the syntax/behaviour of `double` well enough to do that comparison without a helpful header." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:36:19.323", "Id": "78135", "Score": "1", "body": "The libraries you have available is actually pretty much unrelated to the compiler you are using, although the two do frequently get bundled together." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:23:41.190", "Id": "78374", "Score": "0", "body": "Fails to parse things like \"0-0\" and \"0+0\" correctly because of test `if (signedResult || (result != 0))` assuming that if `result` is zero, no input has been read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:47:23.177", "Id": "78388", "Score": "0", "body": "@WilliamMorris The original code was just `if (signedResult) result = - result;` The problem was that failed my assert that \"-0\" ought to return `0.0`. Instead it returned `-0.0` and I didn't know/understand why `0.0 != -0.0` ... therefore I added the `&& (result != 0)` to the implementation, and didn't negate if result is 0." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:04:23.603", "Id": "78763", "Score": "0", "body": "@ChrisW `-0.0` _is_ different from `0.0`, as they signify different floating-point values. The double-precision bit pattern for `0.0` is just `0x0000000000000000`, while `-0.0` is instead `0x8000000000000000`, as specified in IEEE 754. However, IEEE 754 also specifies that `-0.0` compares equal to `0.0`; that is, `-0.0 == 0.0` will evaluate to `true`, even though their string representations are different." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:11:11.087", "Id": "78767", "Score": "0", "body": "Wikipedia has some good information about the [IEEE floating point](http://en.wikipedia.org/wiki/IEEE_floating_point) explaining how all the special floating point values work, including signed zeroes, signed infinity, and `NaN`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:33:08.103", "Id": "78777", "Score": "0", "body": "@AJMansfield That's why I was surprised that this assert failed: `assert(\"-0\", 0, \"\");`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:52:14.523", "Id": "78780", "Score": "0", "body": "@ChrisW The assertion fails because of a different problem with the code. Try splitting the asserted conditions so that it throws something indicating _how_ it failed, where `if (result!=d) throw \"wrong value\";` but `if (!strcmp(endptr, remainder)) throw \"wrong string\";` instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T16:04:54.717", "Id": "78785", "Score": "0", "body": "@AJMansfield Ah you're right and I was wrong: it doesn't throw at all. So I don't need `if (result != 0)` before `result = -result;`. Sorry for that mistake." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T16:06:24.540", "Id": "78786", "Score": "0", "body": "@ChrisW no, it's all good. I've made similar mistakes myself, no big deal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-26T22:50:30.617", "Id": "278748", "Score": "0", "body": "This test is failing for me: assert(\"789E-2\", 789E-2, \"\"); I am using MSVC 2015 if it matters. I also wrote a bit different implementation where above test is passing but this one is failing: assert(\"23423.2342\", 23423.2342, \"\"); I just can't get an algorithm that will pass both these tests." } ]
[ { "body": "<p>After reading the specification of the input ...</p>\n\n<ul>\n<li>Optional sign</li>\n<li>One or more digits</li>\n<li>Optional decimal with one or more digits</li>\n<li>Optional exponent with\n<ul>\n<li>Optional sign</li>\n<li>one or more digits</li>\n</ul></li>\n</ul>\n\n<p>... instead of a single for loop, it might have been clearer (easier to see the mapping from requirements to implementation) to have a succession of 3 <code>for</code> loops.</p>\n\n<hr>\n\n<p>It's not completely clear from the specification what the behaviour of \"12.\" should be. \"12.\" is accepted as a valid number by the C++ compiler in source code. This assert succeeds:</p>\n\n<pre><code>assert(\"12.\", 12., \"\");\n</code></pre>\n\n<p>... but is missing from the set of test cases in the OP.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:22:07.487", "Id": "44873", "ParentId": "44869", "Score": "5" } }, { "body": "<p>One of the biggest obstacles to comprehension in my mind is the inconsistent bracing. \nAs long as you use the same style everywhere, it doesn't matter that much, but please do use the same thing everywhere.</p>\n\n<p>With all the bracing and stuff modified to be consistant, the code is much more readable, if not completely so:</p>\n\n<pre><code>double strtod(const char* str, char** endptr){\n double result = 0.0;\n char signedResult = '\\0';\n char signedExponent = '\\0';\n int decimals = 0;\n bool isExponent = false;\n bool hasExponent = false;\n bool hasResult = false;\n // exponent is logically int but is coded as double so that its eventual\n // overflow detection can be the same as for double result\n double exponent = 0;\n char c;\n\n for (; '\\0' != (c = *str); ++str) {\n if ((c &gt;= '0') &amp;&amp; (c &lt;= '9')) {\n int digit = c - '0';\n if (isExponent) {\n exponent = (10 * exponent) + digit;\n hasExponent = true;\n } else if (decimals == 0) {\n result = (10 * result) + digit;\n hasResult = true;\n } else {\n result += (double)digit / decimals;\n decimals *= 10;\n }\n continue;\n }\n\n if (c == '.') {\n if (!hasResult) break; // don't allow leading '.'\n if (isExponent) break; // don't allow decimal places in exponent\n if (decimals != 0) break; // this is the 2nd time we've found a '.'\n\n decimals = 10;\n continue;\n }\n\n if ((c == '-') || (c == '+')) {\n if (isExponent) {\n if (signedExponent || (exponent != 0)) break;\n else signedExponent = c;\n } else {\n if (signedResult || (result != 0)) break;\n else signedResult = c;\n }\n continue;\n }\n\n if (c == 'E') {\n if (!hasResult) break; // don't allow leading 'E'\n if (isExponent) break;\n else isExponent = true;\n continue;\n }\n\n break; // unexpected character\n }\n\n if (isExponent &amp;&amp; !hasExponent) {\n while (*str != 'E')\n --str;\n }\n\n if (!hasResult &amp;&amp; signedResult) --str;\n\n if (endptr) *endptr = const_cast&lt;char*&gt;(str);\n\n for (; exponent != 0; --exponent) {\n if (signedExponent == '-') result /= 10;\n else result *= 10;\n }\n\n if (signedResult == '-' &amp;&amp; result != 0) result = -result;\n\n return result;\n}\n</code></pre>\n\n<p>As far as correctness goes, there is only one flaw I have spotted, but there <em>are</em> structural problems that you might want to fix. (The error I found is that you only allow a capital \"E\" to signify the exponent, while the standard allows use of either a capital \"E\" or lowercase \"e\".)</p>\n\n<p>Structurally, you should consider refactoring out different parts of the function. You should, for instance refactor out a function processing a string of digits into an integral type into a separate method. And you should see if you can separate the big for loop into different loops for processing the different parts of the string.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:59:29.297", "Id": "78146", "Score": "0", "body": "Having this all one one line `if (!hasResult) break; // don't allow leading '.'` is IMO compact and readable; but, it's so bold! Because it contradicts various style guides [like this one](http://www.webkit.org/coding/coding-style.html#linebreaking-multiple-statements)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T16:04:01.627", "Id": "78148", "Score": "0", "body": "@ChrisW And yet there are many other style guides that _recommend_ single statements in braceless if statements be placed on the same line. The important thing though is consistency and readability, not following any particular style guide." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T18:01:22.463", "Id": "78166", "Score": "0", "body": "To \"refactor out a function processing a string of digits\" I get I would need, `int strtoi(const char* str, char** endptr)`. And if it returns an int, then the caller needs to convert e.g. \"123\" to \"0.123\" if it's after the decimal point." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T15:32:19.540", "Id": "44874", "ParentId": "44869", "Score": "5" } }, { "body": "<p>Incorrect functionality preventing creation of <code>-0.0</code>.</p>\n\n<p><code>-0.0</code> is a legitimate result of <code>strtod()</code>. Although <code>-0.0</code> and <code>+0.0</code> have the same arithmetic <em>value</em>, <code>+0.0 == -0.0</code>, they differ in sign.</p>\n\n<pre><code>// if (signedResult == '-' &amp;&amp; result != 0) result = -result;\nif (signedResult == '-') result = -result;\n</code></pre>\n\n<p>If you would like a test to assert if the result is <code>+0.0</code> or <code>-0.0</code>, consider <code>memcmp()</code> or <a href=\"https://stackoverflow.com/questions/25332133/what-operations-and-functions-on-0-0-and-0-0-give-different-arithmetic-results\">What operations and functions on +0.0 and -0.0 give different arithmetic results?</a></p>\n\n<pre><code>double pz = 0.0;\ndouble nz = -0.0;\nassert(memcmp(&amp;test_result, &amp;pz, sizeof pz) == 0); // test if canonically the same as +0.0\nassert(memcmp(&amp;test_result, &amp;nz, sizeof nz) == 0); // test if canonically the same as -0.0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-30T21:27:58.937", "Id": "117634", "Score": "0", "body": "So I guess that also implies that this assert is wrong: `assert(\"-0\", 0, \"\");` ... with your change, maybe the assert would need to be `assert(\"-0\", -0.0, \"\");`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-30T21:29:43.963", "Id": "117635", "Score": "1", "body": "See update for testing +0.0, -0.0. Show in your asserts which if the test value and and which is the result of the computation. Your `assert()` function differs from what I expect `assert(something that evalutes true or false)`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-30T21:22:46.787", "Id": "64317", "ParentId": "44869", "Score": "2" } } ]
{ "AcceptedAnswerId": "44874", "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:53:59.027", "Id": "44869", "Score": "5", "Tags": [ "c++", "c", "unit-testing", "reinventing-the-wheel", "floating-point" ], "Title": "Implement strtod parsing" }
44869
Questions under this tag regroup common code issues that are often encountered in code that is posted for review. Use this tag for Community Wiki questions that aim at providing general-purpose, one-size-fits-all answers to these common issues, so that reviewers can link to them when reviewing real code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T16:57:31.647", "Id": "44883", "Score": "0", "Tags": null, "Title": null }
44883
<p>I use SonarQube to help me try and become a better programmer to program along with 'best-practice' standards.</p> <p>There are business rules when a user is submitting data they enter in a datagridview that I encompass in a <code>Try Catch</code> block. I think the comments in the code describe fairly well what should be happening.</p> <p>The problem: When I submit my project to SonarQube, it says "Exit Statements should not be used." I do not know what to use in lieu of the <code>Exit</code> statements, when they do exactly what I need. Can anyone point me in the right direction?</p> <p>A visual representation of the Data Grid View:</p> <pre><code>Must be between 0-85 Must total to 100 +------------------+-------------+-----------------+--------------+ | Bonus Percentage | Fund Option | Fund Percentage | Election Date| +------------------+-------------+-----------------+--------------+ | 85 | 2 | 50 | 3/20/2014 | +------------------+-------------+-----------------+--------------+ | 85 | 5 | 50 | 3/20/2014 | +------------------+-------------+-----------------+--------------+ </code></pre> <p>Code:</p> <pre><code>tot = CInt(BonusDGV.Rows(0).Cells(0).Value) 'Business Rules Try/Catch block Try 'Ensure, for all rows, Fund amount totals 100 and Bonus Percentage is between 0-85%. For i As Integer = 0 To BonusDGV.Rows.Count - 1 'don't count rows that contain no data If BonusDGV.Rows(i).Cells(0).Value = Nothing Then Exit For End If fundTot = fundTot + CInt(BonusDGV.Rows(i).Cells(2).Value) If tot &lt;&gt; CInt(BonusDGV.Rows(i).Cells(0).Value) Then MessageBox.Show("Percentage Must Be Between 0-85%.", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Error) 'Stop looping, there has been a violation in user entry (Bonus Percentage) Exit Try End If Next 'Bonus Percentage must be between 0-85% // \\ Double check If tot &gt; 85 Or tot &lt; 0 Then MessageBox.Show("Percentage Must Be Between 0-85%.", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Error) Exit Try 'Total of fun amounts must = 100 ElseIf fundTot &lt;&gt; 100 Then MessageBox.Show("Fund Total Must Add to 100%.", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Error) Exit Try 'Met all the business requirements, proceed to insert record Else For i As Integer = 0 To BonusDGV.Rows.Count - 1 'Make sure there is actually data in the row If BonusDGV.Rows(i).Cells(0).Value = Nothing Then Exit For End If cmd.Parameters("@BonusPct").Value = BonusDGV.Rows(i).Cells(0).Value cmd.Parameters("@FundID").Value = CInt(BonusDGV.Rows(i).Cells(1).Value) cmd.Parameters("@DefPct").Value = BonusDGV.Rows(i).Cells(2).Value cmd.Parameters("@ElectDT").Value = BonusDGV.Rows(i).Cells(3).Value 'nonquery because we don't expect a return value cmd.ExecuteNonQuery() Next End If Catch ex As Exception MessageBox.Show("Invalid Entry. Make sure Bonus Percentage is between 0-85% and Fund Percentage total = 100.", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try 'dispose of the connection conn.Close() </code></pre>
[]
[ { "body": "<p>All of your <code>Exit Try</code> statements follow an error condition. So why not throw an exception with the message and display it in the <code>Catch</code> block instead? That's the purpose of the <code>Try..Catch</code>. </p>\n\n<p>Also, to get rid of the <code>Exit For</code>, just reverse the conditional. As it is, those two statements will end the loop completely on the first empty row, not just skip it.</p>\n\n<p>(Ideally, you'd want to create a custom Exception class and throw it instead of a generic <code>Exception</code>, but this is just to give you an idea.)</p>\n\n<p>So you end up with something like this</p>\n\n<pre><code>tot = CInt(BonusDGV.Rows(0).Cells(0).Value)\n\n'Business Rules Try/Catch block\nTry\n 'Ensure, for all rows, Fund amount totals 100 and Bonus Percentage is between 0-85%.\n For i As Integer = 0 To BonusDGV.Rows.Count - 1\n 'don't count rows that contain no data\n If BonusDGV.Rows(i).Cells(0).Value IsNot Nothing Then\n fundTot = fundTot + CInt(BonusDGV.Rows(i).Cells(2).Value)\n If tot &lt;&gt; CInt(BonusDGV.Rows(i).Cells(0).Value) Then\n Throw New Exception(\"Percentage Must Be Between 0-85%.\")\n End If\n End If\n Next\n 'Bonus Percentage must be between 0-85% // \\\\ Double check\n If tot &gt; 85 Or tot &lt; 0 Then\n Throw New Exception(\"Percentage Must Be Between 0-85%.\")\n ElseIf fundTot &lt;&gt; 100 Then\n Throw New Exception(\"Fund Total Must Add to 100%.\")\n 'Met all the business requirements, proceed to insert record\n Else\n For i As Integer = 0 To BonusDGV.Rows.Count - 1\n 'Make sure there is actually data in the row\n If BonusDGV.Rows(i).Cells(0).Value IsNot Nothing Then\n cmd.Parameters(\"@BonusPct\").Value = BonusDGV.Rows(i).Cells(0).Value\n cmd.Parameters(\"@FundID\").Value = CInt(BonusDGV.Rows(i).Cells(1).Value)\n cmd.Parameters(\"@DefPct\").Value = BonusDGV.Rows(i).Cells(2).Value\n cmd.Parameters(\"@ElectDT\").Value = BonusDGV.Rows(i).Cells(3).Value\n 'nonquery because we don't expect a return value\n cmd.ExecuteNonQuery()\n End If\n Next\n End If\nCatch ex As Exception\n MessageBox.Show(ex.Message, \"Invalid Entry\", MessageBoxButtons.OK, MessageBoxIcon.Error)\nEnd Try\n'dispose of the connection\nconn.Close()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T18:31:39.963", "Id": "78172", "Score": "0", "body": "I thought about doing the `IsNot Nothing`, which I should have known better. I'll have to do more research on `Throw New Exception`, I'm not too familiar with that. I'm assuming it skips the rest of the code once entered and goes immediately to the Catch block. Thanks! I Appreciate it. I would love to hear more about the `Exception` class I should be using in lieu of these Exceptions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T18:59:05.833", "Id": "78177", "Score": "0", "body": "@MarkLaREZZA `Throw` is a way of manually creating an exception. You're correct that it will transfer control to the `Catch` block, just as if any other error in the code threw an exception. What I was referring to by custom exception is making your own class that inherits from `Exception` and using it. Then you have the ability to respond differently if you catch an exception of the custom class versus an unexpected exception generated elsewhere in the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T19:12:17.833", "Id": "78180", "Score": "0", "body": "Got it. I looked at the MSDN documentation, but it's somewhat over my head and kind of lacking in my opinion. I'll have to search for a better resource. Thanks again!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T18:20:36.977", "Id": "44890", "ParentId": "44887", "Score": "3" } }, { "body": "<p>I would seperate the error checking from the database connection.</p>\n\n<pre><code>Enum ErrorType\n Success\n NotBetween\n NotAdding\nEnd Enum\n\nFunction IsThereAnError() As ErrorType\n\n tot = CInt(BonusDGV.Rows(0).Cells(0).Value)\n\n 'Ensure, for all rows, Fund amount totals 100 and Bonus Percentage is between 0-85%.\n For i As Integer = 0 To BonusDGV.Rows.Count - 1\n 'don't count rows that contain no data\n If BonusDGV.Rows(i).Cells(0).Value = Nothing Then\n Exit For\n End If\n fundTot = fundTot + CInt(BonusDGV.Rows(i).Cells(2).Value)\n If tot &lt;&gt; CInt(BonusDGV.Rows(i).Cells(0).Value) Then\n Return ErrorType.NotBetween\n 'Stop looping, there has been a violation in user entry (Bonus Percentage)\n End If\n Next\n 'Bonus Percentage must be between 0-85% // \\\\ Double check\n If tot &gt; 85 Or tot &lt; 0 Then\n Return ErrorType.NotBetween\n 'Total of fun amounts must = 100\n ElseIf fundTot &lt;&gt; 100 Then\n Return ErrorType.NotAdding\n 'Met all the business requirements, proceed to insert record\n End If\n\n Return ErrorType.Success\nEnd Function\n\nPublic Sub Save()\n\n ' OPEN DATABASE CONNECTION\n\n For i As Integer = 0 To BonusDGV.Rows.Count - 1\n 'Make sure there is actually data in the row\n If BonusDGV.Rows(i).Cells(0).Value = Nothing Then\n Exit For\n End If\n cmd.Parameters(\"@BonusPct\").Value = BonusDGV.Rows(i).Cells(0).Value\n cmd.Parameters(\"@FundID\").Value = CInt(BonusDGV.Rows(i).Cells(1).Value)\n cmd.Parameters(\"@DefPct\").Value = BonusDGV.Rows(i).Cells(2).Value\n cmd.Parameters(\"@ElectDT\").Value = BonusDGV.Rows(i).Cells(3).Value\n 'nonquery because we don't expect a return value\n cmd.ExecuteNonQuery()\n Next\n\n ' CLOSE DATABASE CONNECTION\n\nEnd Sub\n\nSub DoSomething()\n\n Select Case IsThereAnError()\n Case ErrorType.Success\n Save()\n Case ErrorType.NotBetween\n MessageBox.Show(\"Percentage Must Be Between 0-85%.\", \"Invalid Entry\", MessageBoxButtons.OK, MessageBoxIcon.Error)\n Case ErrorType.NotAdding\n MessageBox.Show(\"Fund Total Must Add to 100%.\", \"Invalid Entry\", MessageBoxButtons.OK, MessageBoxIcon.Error)\n End Select\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T16:03:30.487", "Id": "45631", "ParentId": "44887", "Score": "0" } } ]
{ "AcceptedAnswerId": "44890", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T18:00:22.533", "Id": "44887", "Score": "3", "Tags": [ "vb.net", "exception-handling" ], "Title": "How to reformat this code so I don't use 'Exit Try' and 'Exit For'?" }
44887
<p>Can anyone recommend improvements to the compress() method? </p> <pre><code>public class ArrayList&lt;E&gt; { private Object[] array; public static final int DEFAULT_SIZE = 20; private int size = 0; public ArrayList(){ this(DEFAULT_SIZE); } public ArrayList(int size){ array = new Object[size]; } public void add(E element){ ensureCapacity(); array[size++] = element; } public E remove(int index){ if(index&gt;=size || index &lt; 0 ){throw new RuntimeException("Invalid index");} E element = (E) array[index]; array[index] = null; --size; compress(); return element; } public E get(int index){ if(index &gt; size){throw new RuntimeException("Invalid index");} E element = (E) array[index]; return element; } public int size(){ return this.size; } private void ensureCapacity(){ if(size &lt; array.length){ return;} resize(); } private void resize(){ Object[] temp = new Object[array.length*2]; copy(array,temp); array = temp; } private void copy(Object[] src, Object[] dest){ if(dest.length&lt; src.length){throw new RuntimeException(src+ " cannot be copied into "+dest);} for(int i=0;i&lt;src.length; i++){ dest[i] = src[i]; } } private void compress(){ int skipCount =0; for(int i=0;i &lt; size &amp;&amp; i&lt;array.length; i++){ if(array[i]==null){ ++skipCount; } array[i]=array[i+skipCount]; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T18:17:17.700", "Id": "78169", "Score": "6", "body": "Can you explain more about what you are actually doing? Are you, knowingly that `ArrayList` exists, making your own implementation for fun? Why does it not implement the `List<E>` interface?" } ]
[ { "body": "<h2>General</h2>\n\n<p>There are a few things in here....</p>\n\n<ul>\n<li><p>You allow users to add a null value in the <code>add()</code> method, but you will then 'compress' it later if you remove something.</p></li>\n<li><p>you have an off-by-one error on the <code>get()</code> (but not <code>remove()</code> ) methods... it should be <code>&gt;= size</code>, and not <code>&gt; size</code>.</p></li>\n<li><p><code>compress()</code> is only called from <code>remove()</code>. I would recommend removing the compress() method and making remove just compress 1 value:</p>\n\n<pre><code>public E remove(int index){\n if(index&gt;=size || index &lt; 0 ){throw new RuntimeException(\"Invalid index\");}\n E element = (E) array[index];\n --size;\n System.arraycopy(array, index + 1, array, index, size - index);\n array[size] = null;\n return element;\n}\n</code></pre>\n\n<p>Alternatively, pass in an int value to the compress method.</p>\n\n<p>If you do the above you will correctly support null values.</p></li>\n<li><p>Although it is tempting, don't call your class ArrayList.... it competes with the standard class name, and will produce problems. Use something like 'MyArrayList'.</p></li>\n</ul>\n\n<h2>Generics</h2>\n\n<p>What you have right now is fine with respect to the Generics.</p>\n\n<p>If you want to be a bit more correct, you can use a Class-type initializer, and use that to create correctly typed arrays, and avoud the generic <code>(T)array[index]</code> casting later.... but that is a pain, and requires passing <code>Class&lt;T&gt; clazz</code> in as the constructor.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T18:24:27.837", "Id": "44892", "ParentId": "44889", "Score": "4" } }, { "body": "<ol>\n<li><p>I agree with <em>@rolfl</em>, that <code>System.arraycopy</code> is better but about the following code:</p>\n\n<blockquote>\n<pre><code>private void copy(Object[] src, Object[] dest){\n if(dest.length&lt; src.length){throw new RuntimeException(src+ \" cannot be copied into \"+dest);}\n for(int i=0;i&lt;src.length; i++){\n dest[i] = src[i];\n } \n}\n</code></pre>\n</blockquote>\n\n<p>If <code>dest.length</code> bigger than <code>src.length</code> you get an exception with the following message:</p>\n\n<pre><code>java.lang.RuntimeException: [Ljava.lang.Object;@1318e59 cannot be copied into [Ljava.lang.Object;@787ee7\n</code></pre>\n\n<p>It's not very useful, I'd rather put the size of the arrays to the message.</p></li>\n<li><blockquote>\n<pre><code>for (int i = 0; i &lt; size &amp;&amp; i &lt; array.length; i++) {\n</code></pre>\n</blockquote>\n\n<p>I think the following would be a little bit easier to read:</p>\n\n<pre><code>for (int i = 0; i &lt; Math.min(size, array.length); i++) {\n</code></pre></li>\n<li><blockquote>\n<pre><code>private Object[] array;\n</code></pre>\n</blockquote>\n\n<p>I'd rename array to <code>data</code> to reflect its purpose.</p></li>\n<li><p><code>remove</code> check negative indexes:</p>\n\n<pre><code>if (index &gt;= size || index &lt; 0) {\n throw new RuntimeException(\"Invalid index\");\n}\n</code></pre>\n\n<p><code>get</code> doesn't:</p>\n\n<pre><code>if (index &gt; size) {\n throw new RuntimeException(\"Invalid index\");\n}\n</code></pre>\n\n<p>It would be more user-friendly to check that in both method. You could create a common <code>checkIndex()</code> method to remove the duplication. Furthermore, putting the invalid index into the exception message would be useful.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T19:02:49.907", "Id": "44894", "ParentId": "44889", "Score": "3" } } ]
{ "AcceptedAnswerId": "44892", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T18:11:55.120", "Id": "44889", "Score": "7", "Tags": [ "java", "generics" ], "Title": "Generic ArrayList" }
44889
<p>I'm new to jQuery and trying to learn how to refactor my bloated code to make it nicer and better maintainable.</p> <p>I have a tabbed navigation which I'm using jQuery to hide and show pages depending on the selector that is clicked.</p> <pre><code> $('#search_distributors').on 'click', (e) =&gt; e.preventDefault() $('#distributor_location_search_filter_form').show() $('#distributor_location_search_container').show() $('#international_distributors_location_container').hide() $('#all_distributors_location_container').hide() $('li.search_locations').addClass('active') $('li.international').removeClass('active') $('li.all_distributors').removeClass('active') $('#international_distributors').on 'click', (e) =&gt; e.preventDefault() $('#international_distributors_location_container').show() $('#distributor_location_search_container, #distributor_location_search_filter_form, #all_distributors_location_container').hide() $('li.search_locations').removeClass('active') $('li.all_distributors').removeClass('active') $('li.international').addClass('active') $('#all_distributors').on 'click', (e) =&gt; e.preventDefault() $('#all_distributors_location_container').show() $('#international_distributors_location_container, #distributor_location_search_container, #distributor_location_search_filter_form, ').hide() $('li.search_locations').removeClass('active') $('li.international').removeClass('active') $('li.all_distributors').addClass('active') </code></pre> <p>I'm familiar with using functions and stuff but unsure how to DRY this up. If anyone can shed some light on this and help me learn that would be wonderful.</p>
[]
[ { "body": "<p>It's hard to give an exact answer without knowing your HTML structure, but if we assume that:</p>\n\n<ol>\n<li>Your tab headers (apparently li-elements with classes like <code>.search_locations</code> and ids like <code>#search_distributors</code>) have some common class, such as <code>.tabheader</code>.</li>\n<li>Each of your tabs is wrapped in an element with a common class, such as <code>.tab</code>.</li>\n<li>You can add a <a href=\"http://ejohn.org/blog/html-5-data-attributes/\">HTML5 data- attribute</a> on your tab headers to designate the tab whiches header it is.</li>\n</ol>\n\n<p>Assumptions 1. and 2. are necessary so that you can use a common function for all the tabs without writing what is essentially the same code thrice.</p>\n\n<p>Number 3. could be implemented like this:</p>\n\n<pre><code>&lt;li class=\"tabheader search_locations\" id=\"search_distributors\" data-tab-id=\"search_distributors_tab\"&gt;Search locations&lt;/li&gt;\n</code></pre>\n\n<p>Then you can reduce your CoffeeScript to</p>\n\n<pre><code>$('.tabheader').on 'click', (e) =&gt;\n e.preventDefault()\n tabId = $(e.currentTarget).data('tabId')\n $('.tab').hide()\n $('#' + tabId).show()\n $('.tabheader').removeClass('active')\n $(e.currentTarget).addClass('active')\n</code></pre>\n\n<p>See <a href=\"http://jsfiddle.net/zWht6/3/\">my jsFiddle</a>.</p>\n\n<p>If you, some strange reason, would not be able to alter your HTML in any way, your code would still be easier to maintain if you wrote a common function for displaying a tab, then called it for each of the click events:</p>\n\n<pre><code>showTab = (e, tab, header) -&gt;\n e.preventDefault()\n allTabs = [\n '#distributor_location_search_filter_form', \n '#distributor_location_search_container', \n '#international_distributors_location_container', \n '#all_distributors_location_container'\n ]\n $(allTabs.join(',')).hide()\n if tab instanceof Array\n tab = tab.join(',')\n $(tab).show()\n allHeaders = [\n 'li.search_locations',\n 'li.international',\n 'li.all_distributors'\n ]\n $(allHeaders.join(',')).removeClass('active')\n $(header).addClass('active')\n\n$('#search_distributors').on 'click', (e) =&gt;\n showTab(e, ['#distributor_location_search_filter_form', '#distributor_location_search_container'], 'li.search_locations')\n\n$('#international_distributors').on 'click', (e) =&gt;\n showTab(e, '#international_distributors_location_container', 'li.international')\n\n$('#all_distributors').on 'click', (e) =&gt;\n showTab(e, '#all_distributors_location_container', 'li.all_distributors')\n</code></pre>\n\n<p>See <a href=\"http://jsfiddle.net/jR7u7/3/\">my other jsFiddle</a>.</p>\n\n<p>Note that there are also multiple jQuery plugins for tab behavior, such as one in <a href=\"http://getbootstrap.com/javascript/#tabs\">Bootstrap</a> and <a href=\"http://jqueryui.com/tabs/\">jQuery UI</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T23:02:02.180", "Id": "78219", "Score": "1", "body": "I cant upvote cause my rep isnt high enough on here yet but thank you for the response... I Did something similar to what you suggested in the first option. Where I grab the id...i knew my code was too bloated thank you for the tips!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T21:28:03.400", "Id": "44904", "ParentId": "44893", "Score": "10" } } ]
{ "AcceptedAnswerId": "44904", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T18:42:20.057", "Id": "44893", "Score": "10", "Tags": [ "javascript", "jquery", "beginner", "coffeescript" ], "Title": "Tabbed navigation to hide and show pages" }
44893
<p>I've written a small library of objects for parsing of Valve Map Files (VMF). These files are always generated and exported from either the Hammer World Editor, or a Source engine built in map making program like the PTI in Portal 2. So I can trust them to always look roughly like the following, except of course that these are just bits of what is usually a much more massive file.</p> <h2>in.vmf</h2> <pre><code>visgroups { visgroup { "name" "Tree_1" "visgroupid" "5" "color" "65 45 0" } visgroup { "name" "Tree_2" "visgroupid" "1" "color" "60 35 0" visgroup { "name" "Branch_1" "visgroupid" "2" "color" "0 192 0" } visgroup { "name" "Branch_2" "visgroupid" "3" "color" "0 255 0" visgroup { "name" "Leaf" "visgroupid" "4" "color" "255 0 0" } } } } viewsettings { "bSnapToGrid" "1" "bShowGrid" "1" "bShowLogicalGrid" "0" "nGridSpacing" "64" "bShow3DGrid" "0" } side { "id" "6" "plane" "(512 -512 -512) (-512 -512 -512) (-512 -512 512)" "material" "BRICK/BRICKFLOOR001A" "uaxis" "[1 0 0 0] 0.25" "vaxis" "[0 0 -1 0] 0.25" "rotation" "0" "lightmapscale" "16" "smoothing_groups" "0" dispinfo { } } </code></pre> <p>I'm looking for feedback on anything relating to structure of my tree, or how I programmed it. If you have any tips, or see some place where I've taken a longer route than necessary, I'd like to know.</p> <p>I'm not looking for criticism on how my if-else chains look, or how I only include brackets when necessary instead of all the time to maintain consistency. I am more interested in functionality feedback.</p> <p>One thing I can point out right now, which I believe is inefficient is that when a block is being created, it is looped over just to be collected and passed into another block constructor. This means if you have a block nested 10 blocks deep that block is iterated over 10 times, and only processed the last time. I could remedy this by creating new properties and blocks as I go, the deeper I go. Using a recursive approach, and that might work faster. However as far as I've seen blocks are never nested 10 deep, they may get as deep as 5. Anyway here is the code.</p> <h2>IVNode</h2> <pre><code>public interface IVNode { string Name { get; } } </code></pre> <h2>VProperty</h2> <pre><code>public class VProperty : IVNode { public string Name { get; private set; } public string Value { get; set; } public VProperty(string name, string value = "") { Name = name; Value = value; } public VProperty(string text) { var texts = text.Trim().Split(new char[] { ' ', '\t' }, 2); Name = texts[0].Trim('\"'); Value = texts[1].Trim('\"'); } public string ToVMFString() { return string.Format("\"{0}\" \"{1}\"", Name, Value); } public override string ToString() { return base.ToString() + " (" + Name + ")"; } } </code></pre> <h2>VBlock</h2> <pre><code>public class VBlock : IVNode { public string Name { get; private set; } public IList&lt;IVNode&gt; Body { get; private set; } public VBlock(string name, IList&lt;IVNode&gt; body = null) { Name = name; if (body == null) body = new List&lt;IVNode&gt;(); } public VBlock(string[] text) { Name = text[0].Trim(); Body = Utils.ParseToBody(text.SubArray(2, text.Length - 3)); } public string[] ToVMFStrings(bool useTabs = true) { var text = Utils.BodyToString(Body); if (useTabs) text = text.Select(t =&gt; t.Insert(0, "\t")).ToList(); text.Insert(0, Name); text.Insert(1, "{"); text.Add("}"); return text.ToArray(); } public override string ToString() { return base.ToString() + " (" + Name + ")"; } } </code></pre> <h2>VMF</h2> <pre><code>public class VMF { public IList&lt;IVNode&gt; Body { get; private set; } public VMF(string[] text) { Body = Utils.ParseToBody(text); } public string[] ToVMFStrings() { return Utils.BodyToString(Body).ToArray(); } } </code></pre> <h2>Extensions</h2> <pre><code>static class Extensions { public static T[] SubArray&lt;T&gt;(this T[] data, int index, int length) { T[] result = new T[length]; Array.Copy(data, index, result, 0, length); return result; } } </code></pre> <h2>Utils</h2> <pre><code>internal static class Utils { internal static Type GetNodeType(string line) { return line.Trim().StartsWith("\"") ? typeof(VProperty) : typeof(VBlock); } internal static IList&lt;IVNode&gt; ParseToBody(string[] body) { IList&lt;IVNode&gt; nBody = new List&lt;IVNode&gt;(); int depth = 0; var wasDeep = false; IList&lt;string&gt; nextBlock = null; for (int i = 0; i &lt; body.Length; i++) { var line = body[i].Trim(); if (string.IsNullOrWhiteSpace(line) || line.StartsWith("//")) continue; var readable = line.FirstOrDefault() != default(char); if (readable &amp;&amp; line.First() == '{') depth++; if (depth == 0) if (Utils.GetNodeType(line) == typeof(VProperty)) nBody.Add(new VProperty(line)); else { nextBlock = new List&lt;string&gt;(); nextBlock.Add(line); } else nextBlock.Add(line); wasDeep = depth &gt; 0; if (readable &amp;&amp; line.First() == '}') depth--; if (wasDeep &amp;&amp; depth == 0) { nBody.Add(new VBlock(nextBlock.ToArray())); nextBlock = null; } } return nBody; } internal static IList&lt;string&gt; BodyToString(IList&lt;IVNode&gt; body) { IList&lt;string&gt; text = new List&lt;string&gt;(); foreach (var node in body) if (node.GetType() == typeof(VProperty)) text.Add(((VProperty)node).ToVMFString()); else foreach (string s in ((VBlock)node).ToVMFStrings()) text.Add(s); return text; } } </code></pre> <p>If you want to actually run this program, here is the very simple code that it takes to load up a vmf and write it back.</p> <h2>Main</h2> <pre><code>static void Main() { string fileName = "in.vmf"; VMF vmf = new VMF(File.ReadAllLines(fileName)); // Manipulate the vmf as you desire File.WriteAllLines("out.vmf", vmf.ToVMFStrings()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T23:19:15.543", "Id": "78224", "Score": "0", "body": "Isn't there a format specification for the language? Just to make sure that you covered every possible edge case correctly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T00:13:23.640", "Id": "78228", "Score": "0", "body": "not as far as I've seen, and as long as it works with hammer and the compiler, it doesn't matter... it doesn't really throw curveballs" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T00:53:30.327", "Id": "78231", "Score": "0", "body": "@svick There is a wiki page on this, however some examples have invalid syntax to save space\nhttps://developer.valvesoftware.com/wiki/Valve_Map_Format\nlike anywhere you have a block name followed by empty {}" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T01:24:03.637", "Id": "78236", "Score": "0", "body": "That's the problem when you don't have a formal spec: is that actually invalid syntax, or are the newlines that I think you are expecting there optional?" } ]
[ { "body": "<p>Instead of writing your own parser by hand, I think you should use a <a href=\"https://en.wikipedia.org/wiki/Parser_generator\">parser generator</a>. If you've never used anything like that before, it requires some learning, but it's not actually that hard and the grammar is actually pretty understandable and readable.</p>\n\n<p>I don't personally have much experience with parser generators, so I took this as an excuse to try out <a href=\"https://github.com/sharwell/antlr4cs\">ANTLR</a>, mostly following <a href=\"http://programming-pages.com/2013/12/14/antlr-4-with-c-and-visual-studio-2012/\">this tutorial</a>. With that, you would have a grammar that looks something like this:</p>\n\n<pre><code>grammar VMF;\n\n/*\n * Parser Rules\n */\n\nfile : node+;\n\nnode : block\n | property;\n\nblock : NAME '{' node* '}';\n\nproperty : STRING STRING;\n\n/*\n * Lexer Rules\n */\n\nNAME : [a-zA-Z_]+;\n\nSTRING : '\"' (~[\"\\r\\n])* '\"';\n\nWS : [ \\r\\n] -&gt; channel(HIDDEN);\n</code></pre>\n\n<p>And then write some simple code to map from the generated ANTLR classes to your classes:</p>\n\n<pre><code>class VMFFileVisitor : VMFBaseVisitor&lt;VMF&gt;\n{\n public override VMF VisitFile(VMFParser.FileContext context)\n {\n var nodeVisitor = new VMFNodeVisitor();\n\n return new VMF(context.node().Select(n =&gt; n.Accept(nodeVisitor)).ToList());\n }\n}\n\nclass VMFNodeVisitor : VMFBaseVisitor&lt;IVNode&gt;\n{\n public override IVNode VisitBlock(VMFParser.BlockContext context)\n {\n return new VBlock(\n context.NAME().GetText(),\n context.node().Select(n =&gt; Visit(n)).ToList());\n }\n\n public override IVNode VisitProperty(VMFParser.PropertyContext context)\n {\n return new VProperty(\n context.STRING(0).GetText().Trim('\"'),\n context.STRING(1).GetText().Trim('\"'));\n }\n}\n</code></pre>\n\n<p>And finally use it like this:</p>\n\n<pre><code>var input = new AntlrInputStream(text);\nvar lexer = new VMFLexer(input);\nvar tokens = new CommonTokenStream(lexer);\nvar parser = new VMFParser(tokens);\nvar visitor = new VMFFileVisitor();\nVMF result = visitor.Visit(parser.file());\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T01:02:14.023", "Id": "44923", "ParentId": "44895", "Score": "5" } }, { "body": "<pre><code>public VProperty(string name, string value = \"\")\npublic VProperty(string text)\n</code></pre>\n\n<p>This means that the default value will never be used. If you write <code>new VProperty(\"propertyName\")</code>, it will call the <code>text</code> overload.</p>\n\n<p>To avoid the confusion, consider using some way of differentiate parsing from normal constructor, like using a static factory method (e.g. <code>public static VProperty Parse(string text)</code>), or even have the parsing and possibly also <code>ToVMFString()</code> in a separate class.</p>\n\n<hr>\n\n<pre><code>'\\\"'\n</code></pre>\n\n<p>You don't need the backslash there, <code>'\"'</code> works fine.</p>\n\n<hr>\n\n<pre><code>public VBlock(string name, IList&lt;IVNode&gt; body = null)\n{\n Name = name;\n if (body == null)\n body = new List&lt;IVNode&gt;();\n}\n</code></pre>\n\n<p>This constructor won't work, you never actually assign to <code>Body</code>.</p>\n\n<hr>\n\n<p>You can make members of internal classes public, instead of internal. It will work exactly the same, but it will make it much simpler to make the class public, if you ever decide to do that.</p>\n\n<hr>\n\n<pre><code>IList&lt;IVNode&gt; nBody = new List&lt;IVNode&gt;();\nint depth = 0;\nvar wasDeep = false;\n</code></pre>\n\n<p>The name <code>nBody</code> is not very good. What does the <code>n</code> mean? You shouldn't use abbreviations like that to make your code clearer.</p>\n\n<p>Also, there is no need to specify the type for <code>nBody</code>, you could use <code>var</code> here. On the other hand, I would be explicit with <code>wasDeep</code>, I think saving that one character is not worth it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T13:02:01.873", "Id": "78287", "Score": "0", "body": "Thank you, I hadn't actually tested the manual creation of Properties and Blocks yet as it takes a lot more effort than loading up a file. `nBody` meant `newBody`, but I see your point. I didn't use var because that would evaluate `nBody` to be a `List<T>` vs an `IList<T>` while this probably would be fine here, I'm just in the habit of using `IList<T>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T16:14:27.027", "Id": "78320", "Score": "0", "body": "Using interfaces makes sense for public parts of your code (like method parameters and return values). But for local variables, there is no need to do that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T01:20:03.640", "Id": "44924", "ParentId": "44895", "Score": "8" } } ]
{ "AcceptedAnswerId": "44924", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T19:12:58.230", "Id": "44895", "Score": "11", "Tags": [ "c#", ".net", "parsing" ], "Title": "Parsing Valve Map Files (VMF) into a tree like structure" }
44895
<p>I wrote a lockless queue for sending small objects from a single thread to a random worker thread.</p> <p>Assumptions:</p> <ul> <li>x86/x86_64 compiled with GCC</li> <li>one thread may Write(), multiple threads may Read()</li> <li>notifying a thread that data is available is done elsewhere</li> <li>T is copy assignable and sizeof(T) is small</li> <li>N is a power of two</li> </ul> <p>Any suggestions welcome.</p> <pre><code>//RnW1FifoFixed.h #pragma once #include &lt;memory&gt; //multiple reader single writer first in first out fixed length ring buffer queue //compatible with x86/x86_64 GCC template&lt;typename T,uint32_t N&gt; class RnW1FifoFixed { private: const uint32_t MASK = 2*N-1; public: RnW1FifoFixed() :m_array(new T[N]),m_read(0),m_write(0) { static_assert(std::is_default_constructible&lt;T&gt;::value,"T does not have a default constructor."); static_assert(std::is_copy_assignable&lt;T&gt;::value,"T does not support copy assignment."); static_assert(N!=0,"N is too small."); static_assert(N!=0x80000000,"N is too large."); static_assert((N&amp;(N-1))==0,"N is not a power of two."); } //one thread bool Write(T t) { //full if(m_write-m_read==N) return false; m_array[m_write&amp;MASK] = t; //CPU does not reorder writes //prevent compiler from reordering writes asm volatile("":::"memory"); m_write++; return true; } //multiple threads bool Read(T&amp; t) { while(true) { //use a constant m_read each loop uint32_t read = m_read; //empty if(read==m_write) return false; t = m_array[read&amp;MASK]; if(__sync_bool_compare_and_swap(&amp;m_read,read,read+1)) return true; } } private: std::unique_ptr&lt;T[]&gt; m_array; uint32_t m_read; uint32_t m_write; }; </code></pre>
[]
[ { "body": "<p>This line seems really strange to me:</p>\n\n<pre><code>static_assert(N!=0x80000000,\"N is too large.\");\n</code></pre>\n\n<p>Technically, it is rather odd to just compare for equality with one big number where there could be numbers even bigger. Didn't you mean:</p>\n\n<pre><code>static_assert(N &gt;= 0x80000000, \"N is too large.\");\n</code></pre>\n\n<hr>\n\n<pre><code>const uint32_t MASK = 2*N-1;\n</code></pre>\n\n<p>Since all the values in this line are known at compile time and <code>MASK</code> is apparently not meant to be changed, you should consider making it both <code>static</code> and <code>constexpr</code>:</p>\n\n<pre><code>static constexpr uin32_t MASK = 2*N-1;\n</code></pre>\n\n<hr>\n\n<p>That's kind of trivial, but you can also use curly braces instead of parenthesis in your constructor initialization list:</p>\n\n<pre><code>RnW1FifoFixed():\n m_array{new T[N]},\n m_read{0},\n m_write{0}\n{\n // ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T18:13:54.950", "Id": "78344", "Score": "1", "body": "I chose N!=0x80000000 because it is the largest power of two that can fit in a uint32. Larger values will fail the power of two test. I agree though that N>=0x80000000 is much more clear. Thanks for the suggestions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T18:22:16.963", "Id": "78345", "Score": "0", "body": "@Bob65536 But now you say it, it makes sense. And it's true that you already check for a power of `2` :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T14:05:00.007", "Id": "44971", "ParentId": "44896", "Score": "4" } }, { "body": "<p>Two comments. First you can move the assignment down a bit to save some work.</p>\n<pre><code>while(true)\n{\n //use a constant m_read each loop\n uint32_t read = m_read;\n //empty\n if(read==m_write)\n return false;\n if(__sync_bool_compare_and_swap(&amp;m_read,read,read+1)) \n {\n t = m_array[read&amp;MASK]; \n return true;\n }\n}\n</code></pre>\n<p>Second, if you declare m_read as volatile, or std::atomic, the first read in the while loop</p>\n<pre><code>uint32_t read = m_read;\n</code></pre>\n<p>would not be optimized with cached value, before the barrier in the CAS.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-17T13:49:54.117", "Id": "249498", "ParentId": "44896", "Score": "2" } } ]
{ "AcceptedAnswerId": "44971", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T19:14:04.613", "Id": "44896", "Score": "8", "Tags": [ "c++", "multithreading", "c++11", "queue", "lock-free" ], "Title": "Lockless Queue Multiple-Reader Singler-Writer in C++" }
44896
<p>I have a large import task that runs as a cronjob and I want to split that task in smaller subtasks. Each subtask should be handled by an own class.</p> <p>At the cronjob entry point I prepare the import-file and want to pass it to sub-functions e.g. </p> <pre><code>$category = new categoryImport($param1, $param2); $category-&gt;importCategories() $articles = new articlesImport($param1, $param2); $articles-&gt;importArticles(); </code></pre> <p>But it feels wrong to instantiate a class to run a single method and after that the instance isn't necessary anymore.</p> <p>My second thought was to use a static method.</p> <pre><code>categoryImport::importCategories($param1, $param2); articlesImport::importArticles($param1, $param2); </code></pre> <p>But inside the class (e.g. categoryImport) a few more methods are needed to split the task in smaller tasks. And some basic information are needed in many of them.</p> <p>In the normal class context I would use member variables and use $this->$var in every method that needs this information but with static methods this is not working.</p> <p>I could pass all informations as parameters to all methods that need them but that feels wrong too. (Yes I know dependency injection).</p> <p>Now I am unsure what is the 'right' solution for this task and I look forward to your feedback.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T20:01:19.450", "Id": "78189", "Score": "0", "body": "If you want local storage in a static implementation then use static variables. Created by `public static $var = array();` and accessed with the scope resolution operator internally by `self::$var` externally by `ClassName::$var`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T20:28:45.790", "Id": "78191", "Score": "0", "body": "You are right that would work. Would you say this is a legitimate solution for this task or is it bad style?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T20:37:22.423", "Id": "78193", "Score": "0", "body": "If ```$params1``` and ```$params2``` are the same for category and articles, you could wrap them in a parent (dependency injection would be good here) and call something like ```$fullDocument->build()```. I would need to know more about the parameters themselves to know where to go with this though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T20:55:11.600", "Id": "78198", "Score": "0", "body": "No they are not the same. I use \"simplexml_load_string\" to convert the xml import file into an object. importCategories get the category relevant part. importArticles the article relevant part. That's no problem. It's about information that are generated in the classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T00:20:24.110", "Id": "78229", "Score": "0", "body": "It would be interesting to see more context here. I worry that, if you have all your data in simpleXML object, that you are not working with that object effectively. Seeing more context good give us areas to provide more feedback on how to work with that object best." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T01:41:42.053", "Id": "78240", "Score": "0", "body": "@Manuel I believe any real working solution can be considered legitimate. It's my professional opinion that as long as your implementation follows some standard design ([SOLID](http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)) perhaps?), is properly documented and is _easily_ maintainable is a proper legitimate solution. Without seeing your entire classes code it's impossible to make that deduction. However, unless you are having performance issues then there is no harm in having a class instantiated for a single purpose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T11:05:56.367", "Id": "78260", "Score": "0", "body": "It's a amount of Code and my Import-Plugin is embeded in a shop software called \"Shopware\" and make use of shopware internal methods etc. Is it sufficient to provide only my relevant code parts?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T19:17:59.643", "Id": "44897", "Score": "1", "Tags": [ "php", "php5", "dependency-injection", "subroutine" ], "Title": "Split large import task into smaller subtasks" }
44897
<p>This is code I need to maintain. I'm trying to make this as an example for code gone bad, for C programmers going to C++.</p> <p>Please provide any comment you can. The original code is about 40 pages long, so I just gave this "small example".</p> <pre><code>void Algo::compute( Image* pInImg, Image* pImg, Image* deBugImg) { int ind_r, ind_c, ind_app_r, ind_app_c , ind_g_r, ind_g_c; int Gv_approx[7][7], Gh_approx[7][7], Bv_approx[5][5], Bh_approx[5][5], Rv_approx[5][5], Rh_approx[5][5]; int Gv_clip_approx[7][7], Gh_clip_approx[7][7]; int HH_h, HH_v; int Yv_approx[5][3], Yh_approx[3][5], Uv_approx[5][3], Uh_approx[3][5], Vv_approx[5][3], Vh_approx[3][5] ; int R_ahd[5][5], G_ahd[5][5], B_ahd[5][5]; int Y_ahd[5][5], U_ahd[5][5], V_ahd[5][5]; int w_v_q, w_h_q; int avg_gr_q=0, avg_gb_q=0, avg_G_q, avg_G3_q, G_std_q, G3_std_q, Gr_std_q, Gb_std_q, AvgG_std_q; int avg_G3_q_rm1, avg_G3_q_rp1, avg_G3_q_cm1, avg_G3_q_cp1, G3_std_q_rm1, G3_std_q_rp1, G3_std_q_cm1, G3_std_q_cp1;// Research checkers FCC int std_prec = (1&lt;&lt;HWP_MSB_STD)-1; int HL_h, HL_v,HW_h, HW_v, HW_h2, HW_v2; int HL_hq, HL_vq,HH_hq, HH_vq, wh_quant; int correction_coef_q; int avg_Uv, avg_Uh, avg_Vv, avg_Vh, avg_Cvq, avg_Chq; int coring_shift; int* ByerrBufferInLine; int* ByerrBufferInLine_min1; int* ByerrBufferInLine_min2; int* ByerrBufferInLine_pls1; int* ByerrBufferInLine_pls2; int margin_h = 5, margin_v = 0,buf_r; int MaxPxlVal = (1&lt;&lt;HWP_PXL_BIT)-1; int valinlog, MSB, MSB2; int OLD_VERSION = 0; /// DBG std::array&lt;int, 1&gt; x_vect = {2310}; std::array&lt;int, 1&gt; y_vect = {1723}; FILE *fp_log=fopen(m_OutputFileName.c_str(),"wt"); int w_clp_array[7], w_clp_array_even[7], w_clp_array_odd[7]; // define config units Prepare_Config_Unit_DIAG1(); Prepare_config_Unit_DIAG2(); Prepare_config_Unit_HF(); Prepare_config_Unit_DIAGSAT(); // produce corinng threshold calculation outside main loop int Corin_TH_array[4096]; for(int ii = 0; ii&lt;4096; ii++) { if(ii&gt;1) { MSB = (int)(log((float)ii)/log(2.0)); valinlog= ii - (1&lt;&lt;MSB); if(valinlog&gt;0) { MSB2 =(int)(log((float)valinlog)/log(2.0)); Corin_TH_array[ii] = MSB + (MSB2 == (MSB-1)); } else { Corin_TH_array[ii] = MSB; } } else { Corin_TH_array[ii] = 0; } } for( int row=0 + margin_v; row &lt; m_Height - margin_v; row++){ // define rellevant lines' pointers. Our restriction that inout buffert have full quads only =&gt; even number of lines buf_r = min( max(row-2,abs((row-2)&amp; 1)) , m_Height - 2 + abs((row-2)&amp; 1) ); int* ByerrBufferLine_min2 = pInImg-&gt;m_R[buf_r]; buf_r = min( max(row-1,abs((row-1)&amp; 1)) , m_Height - 2 + abs((row-1)&amp; 1) ); int* ByerrBufferLine_min1 = pInImg-&gt;m_R[buf_r]; buf_r = min( max(row,abs((row)&amp; 1)) , m_Height - 2 + abs((row)&amp; 1) ); int* ByerrBufferLine = pInImg-&gt;m_R[buf_r]; buf_r = min( max(row+1,abs((row+1)&amp; 1)) , m_Height - 2 + abs((row+1)&amp; 1) ); int* ByerrBufferLine_pls1 = pInImg-&gt;m_R[buf_r]; buf_r = min( max(row+2,abs((row+2)&amp; 1)) , m_Height - 2 + abs((row+2)&amp; 1) ); int* ByerrBufferLine_pls2 = pInImg-&gt;m_R[buf_r]; //// DBG buf_r = min( max(row+3,abs((row+3)&amp; 1)) , m_Height - 3 + abs((row+3)&amp; 1) ); int* ByerrBufferLine_pls3 = pInImg-&gt;m_R[buf_r]; buf_r = min( max(row+4,abs((row+4)&amp; 1)) , m_Height - 4 + abs((row+4)&amp; 1) ); int* ByerrBufferLine_pls4 = pInImg-&gt;m_R[buf_r]; buf_r = min( max(row-3,abs((row-3)&amp; 1)) , m_Height - 3 + abs((row-3)&amp; 1) ); int* ByerrBufferLine_min3 = pInImg-&gt;m_R[buf_r]; buf_r = min( max(row-4,abs((row-4)&amp; 1)) , m_Height - 4 + abs((row-4)&amp; 1) ); int* ByerrBufferLine_min4 = pInImg-&gt;m_R[buf_r]; for( int col=0 + margin_h; col &lt; m_Width - margin_h; col++){ ////////////// DBG //if(DEBUG_MODE) //{ int log_this_pix=0; for(int dbg_indx = 0; dbg_indx &lt; x_vect.size(); dbg_indx ++) { if((fp_log != NULL) &amp;&amp; (((col == x_vect[dbg_indx] &amp;&amp; (row == y_vect[dbg_indx]) )))) { log_this_pix = 1; break; } } if(log_this_pix) { fprintf(fp_log,"org_pix %d x- %d y- %d",ByerrBufferLine[col], col, row); if(FC(row,col)== Green) { if(FC(row,col-1)== Red) { fprintf(fp_log,"\tpixel GREEN RED\n"); } else { fprintf(fp_log,"\tpixel GREEN BLUE\n"); } } else if(FC(row,col)== Red) { fprintf(fp_log,"\tpixel RED\n"); } else { fprintf(fp_log,"\tpixel BLUE\n"); } for(int dbg_x_shft = col-4; dbg_x_shft&lt;col+4; dbg_x_shft++) { fprintf(fp_log,"%d\t", ByerrBufferLine_min4[dbg_x_shft]); } fprintf(fp_log,"\n"); for(int dbg_x_shft = col-4; dbg_x_shft&lt;col+4; dbg_x_shft++) { fprintf(fp_log,"%d\t", ByerrBufferLine_min3[dbg_x_shft]); } fprintf(fp_log,"\n"); for(int dbg_x_shft = col-4; dbg_x_shft&lt;col+4; dbg_x_shft++) { fprintf(fp_log,"%d\t", ByerrBufferLine_min2[dbg_x_shft]); } fprintf(fp_log,"\n"); for(int dbg_x_shft = col-4; dbg_x_shft&lt;col+4; dbg_x_shft++) { fprintf(fp_log,"%d\t", ByerrBufferLine_min1[dbg_x_shft]); } fprintf(fp_log,"\n"); for(int dbg_x_shft = col-4; dbg_x_shft&lt;col+4; dbg_x_shft++) { fprintf(fp_log,"%d\t", ByerrBufferLine[dbg_x_shft]); } fprintf(fp_log,"\n"); for(int dbg_x_shft = col-4; dbg_x_shft&lt;col+4; dbg_x_shft++) { fprintf(fp_log,"%d\t", ByerrBufferLine_pls1[dbg_x_shft]); } fprintf(fp_log,"\n"); for(int dbg_x_shft = col-4; dbg_x_shft&lt;col+4; dbg_x_shft++) { fprintf(fp_log,"%d\t", ByerrBufferLine_pls2[dbg_x_shft]); } fprintf(fp_log,"\n"); for(int dbg_x_shft = col-4; dbg_x_shft&lt;col+4; dbg_x_shft++) { fprintf(fp_log,"%d\t", ByerrBufferLine_pls3[dbg_x_shft]); } fprintf(fp_log,"\n"); for(int dbg_x_shft = col-4; dbg_x_shft&lt;col+4; dbg_x_shft++) { fprintf(fp_log,"%d\t", ByerrBufferLine_pls4[dbg_x_shft]); } fprintf(fp_log,"\n"); } //} /////////////////////////////// // Patch statistics calculation. ////////////////////// // Calculate statistics if(FC(row,col)== Green) { if(FC(row, col-1)== Red) { avg_gr_q = (455*(int)(ByerrBufferLine_min2 [col-2] + ByerrBufferLine_min2 [col] + ByerrBufferLine_min2 [col+2] +ByerrBufferLine[col-2] + ByerrBufferLine[col] + ByerrBufferLine[col+2] +ByerrBufferLine_pls2[col-2] + ByerrBufferLine_pls2[col] + ByerrBufferLine_pls2[col+2]))&gt;&gt;12; avg_gr_q = CLIP_VAL(avg_gr_q, 0, MaxPxlVal); avg_gb_q = ((int)((ByerrBufferLine_min1[col-1] + ByerrBufferLine_min1[col+1] + ByerrBufferLine_pls1[col-1] + ByerrBufferLine_pls1[col+1] + 2)&gt;&gt;2)); avg_gb_q = CLIP_VAL(avg_gb_q, 0, MaxPxlVal); } else { avg_gr_q = (int)((ByerrBufferLine_min1[col-1] + ByerrBufferLine_min1[col+1] + ByerrBufferLine_pls1[col-1] + ByerrBufferLine_pls1[col+1] + 2)&gt;&gt;2); avg_gr_q = CLIP_VAL(avg_gr_q, 0, MaxPxlVal); avg_gb_q = (455*(int)(ByerrBufferLine_min2[col-2] + ByerrBufferLine_min2[col] + ByerrBufferLine_min2[col+2] + ByerrBufferLine[col-2] + ByerrBufferLine[col] + ByerrBufferLine[col+2] + ByerrBufferLine_pls2[col-2] + ByerrBufferLine_pls2[col] + ByerrBufferLine_pls2[col+2])&gt;&gt;12); avg_gb_q = CLIP_VAL(avg_gb_q, 0, MaxPxlVal); } avg_G3_q = 819*(int)(ByerrBufferLine_min1[col-1] + ByerrBufferLine_min1[col+1] + ByerrBufferLine[col] + ByerrBufferLine_pls1[col-1] + ByerrBufferLine_pls1[col+1])&gt;&gt;12; avg_G3_q = CLIP_VAL(avg_G3_q, 0, MaxPxlVal); // Research FCC checker removal avg_G3_q_rm1 = (int)(ByerrBufferLine_min2[col] + ByerrBufferLine_min1[col-1] + ByerrBufferLine_min1[col+1] + ByerrBufferLine[col] + 2) &gt;&gt; 2; avg_G3_q_rm1 = CLIP_VAL(avg_G3_q_rm1, 0, MaxPxlVal); avg_G3_q_rp1 = (int)(ByerrBufferLine[col] + ByerrBufferLine_pls1[col-1] + ByerrBufferLine_pls1[col+1] + ByerrBufferLine_pls2[col] + 2) &gt;&gt; 2; avg_G3_q_rp1 = CLIP_VAL(avg_G3_q_rp1, 0, MaxPxlVal); avg_G3_q_cm1 = (int)(ByerrBufferLine[col-2] + ByerrBufferLine_min1[col-1] + ByerrBufferLine[col] + ByerrBufferLine_pls1[col-1] + 2) &gt;&gt; 2; avg_G3_q_cm1 = CLIP_VAL(avg_G3_q_cm1, 0, MaxPxlVal); avg_G3_q_cp1 = (int)(ByerrBufferLine[col] + ByerrBufferLine_min1[col+1] + ByerrBufferLine[col+2] + ByerrBufferLine_pls1[col+1] + 2) &gt;&gt; 2; avg_G3_q_cp1 = CLIP_VAL(avg_G3_q_cp1, 0, MaxPxlVal); } else { if(FC(row,col)== Red) { avg_gr_q = (682*(int)(ByerrBufferLine_min2[col-1] + ByerrBufferLine_min2[col+1] +ByerrBufferLine[col-1] + ByerrBufferLine[col+1] +ByerrBufferLine_pls2[col-1] + ByerrBufferLine_pls2[col+1])&gt;&gt;12); avg_gr_q = CLIP_VAL(avg_gr_q, 0, MaxPxlVal); avg_gb_q = (682*(int)(ByerrBufferLine_min1[col-2] + ByerrBufferLine_min1[col] + ByerrBufferLine_min1[col+2] +ByerrBufferLine_pls1[col-2] + ByerrBufferLine_pls1[col] + ByerrBufferLine_pls1[col+2])&gt;&gt;12); avg_gb_q = CLIP_VAL(avg_gb_q, 0, MaxPxlVal); } else { avg_gr_q = (682*(int)(ByerrBufferLine_min1[col-2] + ByerrBufferLine_min1[col] + ByerrBufferLine_min1[col+2] +ByerrBufferLine_pls1[col-2] + ByerrBufferLine_pls1[col] + ByerrBufferLine_pls1[col+2])&gt;&gt;12); avg_gr_q = CLIP_VAL(avg_gr_q, 0, MaxPxlVal); avg_gb_q = (682*(int)(ByerrBufferLine_min2[col-1] + ByerrBufferLine_min2[col+1] +ByerrBufferLine[col-1] + ByerrBufferLine[col+1] +ByerrBufferLine_pls2[col-1] + ByerrBufferLine_pls2[col+1])&gt;&gt;12); avg_gb_q = CLIP_VAL(avg_gb_q, 0, MaxPxlVal); } avg_G3_q = (int)(ByerrBufferLine_min1[col] + ByerrBufferLine[col-1] + ByerrBufferLine[col+1] + ByerrBufferLine_pls1[col] + 2) &gt;&gt; 2; avg_G3_q = CLIP_VAL(avg_G3_q, 0, MaxPxlVal); /// Research FCC, checker removal avg_G3_q_rm1 = 819*(int)(ByerrBufferLine_min2[col-1] + ByerrBufferLine_min2[col+1] + ByerrBufferLine_min1[col] + ByerrBufferLine[col-1] + ByerrBufferLine[col+1])&gt;&gt;12; avg_G3_q_rm1 = CLIP_VAL(avg_G3_q_rm1, 0, MaxPxlVal); avg_G3_q_rp1 = 819*(int)(ByerrBufferLine[col-1] + ByerrBufferLine[col+1] + ByerrBufferLine_pls1[col] + ByerrBufferLine_pls2[col-1] + ByerrBufferLine_pls2[col+1])&gt;&gt;12; avg_G3_q_rp1 = CLIP_VAL(avg_G3_q_rp1, 0, MaxPxlVal); avg_G3_q_cm1 =819*(int)(ByerrBufferLine_min1[col-2] + ByerrBufferLine_min1[col] + ByerrBufferLine[col-1] + ByerrBufferLine_pls1[col-2] + ByerrBufferLine_pls1[col+2])&gt;&gt;12; avg_G3_q_cm1 = CLIP_VAL(avg_G3_q_cm1, 0, MaxPxlVal); avg_G3_q_cp1 = 819*(int)(ByerrBufferLine_min1[col] + ByerrBufferLine_min1[col+2] + ByerrBufferLine[col+1] + ByerrBufferLine_pls1[col] + ByerrBufferLine_pls1[col+2])&gt;&gt;12; avg_G3_q_cp1 = CLIP_VAL(avg_G3_q_cp1, 0, MaxPxlVal); } avg_G_q = (avg_gr_q + avg_gb_q + 1)&gt;&gt;1; // calc std if(FC(row,col)== Green){ if(FC(row,col-1)== Red) { Gr_std_q = (455*(int)(min(abs(ByerrBufferLine_min2[col-2] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine_min2[col] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine_min2[col+2] - avg_gr_q) , std_prec ) +min(abs(ByerrBufferLine[col-2] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine[col] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine[col+2] - avg_gr_q) , std_prec ) +min(abs(ByerrBufferLine_pls2[col-2] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine_pls2[col] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine_pls2[col+2] - avg_gr_q) , std_prec )))&gt;&gt;12; Gb_std_q = (min(abs(ByerrBufferLine_min1[col-1] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine_min1[col+1] - avg_gb_q) , std_prec ) +min(abs(ByerrBufferLine_pls1[col-1] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col+1] - avg_gb_q) , std_prec ) + 2)&gt;&gt;2; } else { Gr_std_q = (min(abs(ByerrBufferLine_min1[col-1] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine_min1[col+1] - avg_gr_q) , std_prec ) +min(abs(ByerrBufferLine_pls1[col-1] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col+1] - avg_gr_q) , std_prec ) + 2)&gt;&gt;2; Gb_std_q = (455*(int)(min(abs(ByerrBufferLine_min2[col-2] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine_min2[col] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine_min2[col+2] - avg_gb_q) , std_prec ) +min(abs(ByerrBufferLine[col-2] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine[col] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine[col+2] - avg_gb_q) , std_prec ) +min(abs(ByerrBufferLine_pls2[col-2] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine_pls2[col] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine_pls2[col+2] - avg_gb_q) , std_prec )))&gt;&gt;12; } G3_std_q = (819*(int)(min(abs(ByerrBufferLine_min1[col-1] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_min1[col+1] - avg_G3_q) , std_prec ) +min(abs(ByerrBufferLine[col] - avg_G3_q) , std_prec ) +min(abs(ByerrBufferLine_pls1[col-1] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col+1] - avg_G3_q) , std_prec )))&gt;&gt;12; G_std_q = (315*(int)(min(abs(ByerrBufferLine_min2[col-2] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine_min2[col] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine_min2[col+2] - avg_G_q) , std_prec ) +min(abs(ByerrBufferLine_min1[col-1] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine_min1[col+1] - avg_G_q) , std_prec ) +min(abs(ByerrBufferLine[col-2] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine[col] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine[col+2] - avg_G_q) , std_prec ) +min(abs(ByerrBufferLine_pls1[col-1] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col+1] - avg_G_q) , std_prec ) +min(abs(ByerrBufferLine_pls2[col-2] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine_pls2[col] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine_pls2[col+2] - avg_G_q) , std_prec )))&gt;&gt;12; /// Research FCC, checker removal G3_std_q_rm1 = (int)( min(abs(ByerrBufferLine_min2[col] - avg_G3_q_rm1) , std_prec ) + min(abs(ByerrBufferLine_min1[col-1] - avg_G3_q_rm1) , std_prec ) + min(abs(ByerrBufferLine_min1[col+1] - avg_G3_q_rm1) , std_prec ) + min(abs(ByerrBufferLine[col] - avg_G3_q_rm1) , std_prec ) + 2)&gt;&gt;2; G3_std_q_rp1 = (int)( min(abs(ByerrBufferLine[col] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col-1] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col+1] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_pls2[col] - avg_G3_q) , std_prec ) + 2)&gt;&gt;2; G3_std_q_cm1 = (int)( min(abs(ByerrBufferLine_min1[col-1] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine[col-2] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine[col] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col-1] - avg_G3_q) , std_prec ) + 2)&gt;&gt;2; G3_std_q_cp1 = (int)( min(abs(ByerrBufferLine_min1[col+1] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine[col] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine[col+2] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col+1] - avg_G3_q) , std_prec ) + 2)&gt;&gt;2; } else{ if(FC(row,col)== Red){ Gr_std_q = (682*(int)(min(abs(ByerrBufferLine_min2[col-1] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine_min2[col+1] - avg_gr_q) , std_prec ) +min(abs(ByerrBufferLine[col-1] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine[col+1] - avg_gr_q) , std_prec ) +min(abs(ByerrBufferLine_pls2[col-1] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine_pls2[col+1] - avg_gr_q) , std_prec )))&gt;&gt;12; Gb_std_q = (682*(int)(min(abs(ByerrBufferLine_min1[col-2] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine_min1[col] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine_min1[col+2] - avg_gb_q) , std_prec ) +min(abs(ByerrBufferLine_pls1[col-2] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col+2] - avg_gb_q) , std_prec )))&gt;&gt;12; } else{ Gr_std_q = (682*(int)(min(abs(ByerrBufferLine_min1[col-2] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine_min1[col] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine_min1[col+2] - avg_gr_q) , std_prec ) +min(abs(ByerrBufferLine_pls1[col-2] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col] - avg_gr_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col+2] - avg_gr_q) , std_prec )))&gt;&gt;12; Gb_std_q = (682*(int)(min(abs(ByerrBufferLine_min2[col-1] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine_min2[col+1] - avg_gb_q) , std_prec ) +min(abs(ByerrBufferLine[col-1] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine[col+1] - avg_gb_q) , std_prec ) +min(abs(ByerrBufferLine_pls2[col-1] - avg_gb_q) , std_prec ) + min(abs(ByerrBufferLine_pls2[col+1] - avg_gb_q) , std_prec )))&gt;&gt;12; } G3_std_q = (int)( min(abs(ByerrBufferLine_min1[col] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine[col-1] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine[col+1] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col] - avg_G3_q) , std_prec ) + 2)&gt;&gt;2; G_std_q = (341*(int)(min(abs(ByerrBufferLine_min2[col-1] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine_min2[col+1] - avg_G_q) , std_prec ) +min(abs(ByerrBufferLine_min1[col-2] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine_min1[col] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine_min1[col+2] - avg_G_q) , std_prec ) +min(abs(ByerrBufferLine[col-1] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine[col+1] - avg_G_q) , std_prec ) +min(abs(ByerrBufferLine_pls1[col-2] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col+2] - avg_G_q) , std_prec ) +min(abs(ByerrBufferLine_pls2[col-1] - avg_G_q) , std_prec ) + min(abs(ByerrBufferLine_pls2[col+1] - avg_G_q) , std_prec )))&gt;&gt;12; /// Research FCC, checker removal G3_std_q_rm1 = (819*(int)(min(abs(ByerrBufferLine_min2[col-1] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_min2[col+1] - avg_G3_q) , std_prec ) +min(abs(ByerrBufferLine_min1[col] - avg_G3_q) , std_prec ) +min(abs(ByerrBufferLine[col-1] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine[col+1] - avg_G3_q) , std_prec )))&gt;&gt;12; G3_std_q_rp1 = (819*(int)(min(abs(ByerrBufferLine[col-1] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine[col+1] - avg_G3_q) , std_prec ) +min(abs(ByerrBufferLine_pls1[col] - avg_G3_q) , std_prec ) +min(abs(ByerrBufferLine_pls2[col-1] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_pls2[col+1] - avg_G3_q) , std_prec )))&gt;&gt;12; G3_std_q_cm1 = (819*(int)(min(abs(ByerrBufferLine_min1[col-2] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_min1[col] - avg_G3_q) , std_prec ) +min(abs(ByerrBufferLine[col-1] - avg_G3_q) , std_prec ) +min(abs(ByerrBufferLine_pls1[col-2] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col] - avg_G3_q) , std_prec )))&gt;&gt;12; G3_std_q_cp1 = (819*(int)(min(abs(ByerrBufferLine_min1[col] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_min1[col+2] - avg_G3_q) , std_prec ) +min(abs(ByerrBufferLine[col+1] - avg_G3_q) , std_prec ) +min(abs(ByerrBufferLine_pls1[col] - avg_G3_q) , std_prec ) + min(abs(ByerrBufferLine_pls1[col+2] - avg_G3_q) , std_prec )))&gt;&gt;12; } AvgG_std_q = (Gr_std_q + Gb_std_q + 1)&gt;&gt;1; //// Diagonal int metric_diag, metric_overshrpn2; int Y_est[3][3]; int G1, G2, G3, G4; int cu_diag1_out, cu_diag2_out, cu_diag3_out; int ClpdW; ////////////////// STEP 1 /////////////////// ///////////////////////////////////////////////// ////// Green clip weigh (Wgclp) calculation ////// calculated only in even rows like avg between even and odd rows ///////////////////////////////////////////////// int G_std_q_array[7]; // calculate w_gclp for each column independently based on central row and store it in array for (int gl_shift_c = - 3 ; gl_shift_c &lt;= 3 ; ++gl_shift_c ) { int col_w = col+gl_shift_c; for(int shift_r = - 1 ; shift_r &lt;= 1 ; ++shift_r ) { for(int shift_c = - 1 ; shift_c &lt;= 1 ; ++shift_c ) { int row_ind = max(min(row+shift_r,m_Height-2+abs(row+shift_r)&amp; 1),abs(row+shift_r)&amp; 1); int col_ind = col + (shift_c+gl_shift_c); // buf_r = min( max(row+1,abs((row+1)&amp; 1)) , m_Height - 2 + abs((row+1)&amp; 1) );buf_r = min( max(row-1,abs((row-1)&amp; 1)) , m_Height - 2 + abs((row-1)&amp; 1) ); Y_est[shift_r+1][shift_c+1] = ( pInImg-&gt;m_R[max(row_ind-1,abs(row_ind-1)&amp;1)][col_ind-1] + pInImg-&gt;m_R[max(row_ind-1,abs(row_ind-1)&amp;1)][col_ind]*2 + pInImg-&gt;m_R[max(row_ind-1,abs(row_ind-1)&amp;1)][col_ind+1] + pInImg-&gt;m_R[row_ind][col_ind-1]*2 + pInImg-&gt;m_R[row_ind][col_ind]*4 + pInImg-&gt;m_R[row_ind][col_ind+1]*2 + pInImg-&gt;m_R[min(row_ind+1,m_Height-2+abs(row_ind+1)&amp;1)][col_ind-1] + pInImg-&gt;m_R[min(row_ind+1,m_Height-2+abs(row_ind+1)&amp;1)][col_ind]*2 + pInImg-&gt;m_R[min(row_ind+1,m_Height-2+abs(row_ind+1)&amp;1)][col_ind+1] + 8)&gt;&gt;4; } } metric_diag = min((abs(Y_est[0][0]-Y_est[1][1]) + abs(Y_est[1][1]-Y_est[2][2]) + abs(Y_est[0][1]-Y_est[1][2]) + abs(Y_est[1][0]-Y_est[2][1]) +2 )&gt;&gt;2, (abs(Y_est[0][2]-Y_est[1][1]) + abs(Y_est[1][1]-Y_est[2][0]) + abs(Y_est[0][1]-Y_est[1][0]) + abs(Y_est[1][2]-Y_est[2][1]) +2 )&gt;&gt;2 ); metric_diag = min(metric_diag,(1&lt;&lt;HWP_DIAG_METR)-1); // calculate metric_diag2 G1 = MAX( (abs(pInImg-&gt;m_R[max(row-2,abs(row-2)&amp;1)][col_w-2] - pInImg-&gt;m_R[row][col_w]) + abs(pInImg-&gt;m_R[row][col_w - 2] - pInImg-&gt;m_R[min(row + 2,m_Height-2+(row + 2)%1)][col_w]) + abs(pInImg-&gt;m_R[row][col_w] - pInImg-&gt;m_R[min(row + 2,m_Height-2+(row + 2)%1)][col_w + 2]) + abs(pInImg-&gt;m_R[max(row - 2,abs(row-2)&amp;1)][col_w] - pInImg-&gt;m_R[row][col_w + 2]) + (1&lt;&lt;(HWP_SH_DOWN+1)))&gt;&gt;(2+HWP_SH_DOWN) , (abs(pInImg-&gt;m_R[max(row-2,abs(row-2)&amp;1)][col_w] - pInImg-&gt;m_R[row][col_w - 2]) + abs(pInImg-&gt;m_R[max(row - 2,abs(row-2)&amp;1)][col_w + 2] - pInImg-&gt;m_R[row][col_w])+ abs( pInImg-&gt;m_R[row][col_w]-pInImg-&gt;m_R[min(row + 2,m_Height-2+(row + 2)%1)][col_w-2]) + abs(pInImg-&gt;m_R[row][col_w+2]-pInImg-&gt;m_R[min(row+2,m_Height-2+(row + 2)%1)][col_w]) + (1&lt;&lt;(HWP_SH_DOWN+1)))&gt;&gt;(2+HWP_SH_DOWN)); G2 = MAX( (abs(pInImg-&gt;m_R[max(row-1,abs(row-1)&amp;1)][col_w-1] - pInImg-&gt;m_R[min(row + 1,m_Height-2+(row + 1)%1)][col_w+1]) + (1&lt;&lt;(HWP_SH_DOWN-1)))&gt;&gt;HWP_SH_DOWN, (abs(pInImg-&gt;m_R[max(row-1,abs(row-1)&amp;1)][col_w+1] - pInImg-&gt;m_R[min(row + 1,m_Height-2+(row + 1)%1)][col_w-1]) + (1&lt;&lt;(HWP_SH_DOWN-1)))&gt;&gt;HWP_SH_DOWN); G3 = MAX( (abs(pInImg-&gt;m_R[max(row-2,abs(row-2)&amp;1)][col_w-1] - pInImg-&gt;m_R[row][col_w+1]) + abs(pInImg-&gt;m_R[row][col_w-1]-pInImg-&gt;m_R[min(row + 2,m_Height-1)][col_w+1]) + (1&lt;&lt;HWP_SH_DOWN) )&gt;&gt; .... </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T20:06:14.093", "Id": "78190", "Score": "1", "body": "Get yourself familiarized with OOPS Design Patterns, if you haven't already." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T20:31:37.550", "Id": "78644", "Score": "0", "body": "Please do not remove the original code as the answers rely on them. You may post the updated version below the original." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T20:34:31.957", "Id": "78645", "Score": "0", "body": "sure was about to update" } ]
[ { "body": "<p>Given that a good rule of thumb is to keep functions small enough to fit on a page, I want the kind of screen these coders have...<br><br>\nSeriously, function calls are cheap on modern hardware, and compilers can do the inlining for you today. I'd bet the code can gain some performance simply by chopping it into smaller functions.<br><br>\nYou might get away with giving a variable a name like <code>HH_h</code> if there were &lt;10 variables in the function, but for this monstrosity you'd need to have a more descriptive name than that, and also a comment for every variable, describing exactly what it represents.<br>\nSpeaking of comments, if you can't be bothered to put stuff in functions, at least write a comment explaining what each loop is doing.<br> Finally, I know C isn't an object-oriented language at heart, but it does support <strong>structs</strong>. Use them to group related values together.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T23:57:17.403", "Id": "78226", "Score": "0", "body": "It looks like C code, but it's actually C++11 code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T08:45:31.127", "Id": "78255", "Score": "0", "body": "@Morwenn: I don't see why this should be turned into a language war, nobody sane would say this is acceptable for C code. The suggestions I've made work for both C and C++." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T09:12:11.180", "Id": "78257", "Score": "0", "body": "It is because you said \"I know C isn't an object-oriented language at heart\". But this is C++, which is actually an OO language; my point was that you could strengthen this sentence. I never intended to turn this into a language war." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T16:04:38.093", "Id": "78318", "Score": "0", "body": "@Morwenn: Well, it seems to me like the whole question is meant to be used to beat C-programmers over the head saying: \"Behold what C hath wrought!\", when really it's not a matter of language, but of good programming practices older than dirt. Practically, if I were asked to convert this code into C++, I'd either do a full rewrite, or first turn it into usable C. If you go and design a few nice `struct`s for the code, the only thing you need to do to turn them into `class`es is turning the functions that work on them into methods." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T22:54:50.360", "Id": "44914", "ParentId": "44900", "Score": "6" } }, { "body": "<p>It's <strike>difficult</strike> impossible to review for correctness (\"Does it implement required functionality?\") without knowing (or being able to recognize from past experience of image processing algorithms) what the required functionality is. Ideally there should be one or more comments which reference (perhaps with a hyperlink) the algorithms that are being implemented.</p>\n\n<blockquote>\n<pre><code> void Algo::compute\n</code></pre>\n</blockquote>\n\n<p>Not a good class name <code>Algo</code>.</p>\n\n<blockquote>\n<pre><code> int ind_r, ind_c, ind_app_r, ind_app_c , ind_g_r, ind_g_c;\n</code></pre>\n</blockquote>\n\n<p>Variables declared before they're initialized. Badly named. It's even more important to be told what data is supposed to be in a variable, than to be told what the code is doing (because you can read code to see what it's doing).</p>\n\n<p>That might be the first change I'd make if I were trying to refactor it. For example, <code>MSB</code>, <code>MSB2</code> and <code>valinlog</code> are declared at the top of the function. On inspection they're used within a single <code>for</code> loop later on: that (inside the for loop) is where they should be declared. Otherwise it's difficult to tell:</p>\n\n<ul>\n<li>What they're used for (what they mean)</li>\n<li>Whether they're initialized before they're used</li>\n<li>Whether they're used again much later in the procedure (whereas if they're defined inside a small scope like a <code>for</code> loop, you know they're not re-used after they have gone out of scope)</li>\n</ul>\n\n<p>Having so many at the top of the long procedure is akin to having global variables: it's difficult to tell where they're referenced.</p>\n\n<blockquote>\n<pre><code>int Gv_approx[7][7]\n</code></pre>\n</blockquote>\n\n<p>Magic numbers: <code>7</code> etc. (also <code>455</code>, <code>819</code>, etc.)</p>\n\n<blockquote>\n<pre><code>FILE *fp_log=fopen(m_OutputFileName.c_str(),\"wt\");\n</code></pre>\n</blockquote>\n\n<p>No immediate guarantee this file will be closed again.</p>\n\n<blockquote>\n<pre><code>Prepare_Config_Unit_DIAG1();\n</code></pre>\n</blockquote>\n\n<p>Maybe this and similar should be constructors of some class.</p>\n\n<blockquote>\n<pre><code>// produce corinng threshold calculation outside main loop\n</code></pre>\n</blockquote>\n\n<p>Woot: a comment! Too bad it's meaningless to me. Is <code>corinng</code> an identifier, or a typo?</p>\n\n<blockquote>\n<pre><code>// define rellevant lines' pointers.\n</code></pre>\n</blockquote>\n\n<p>Non-standard indentation (8 spaces instead of 4).</p>\n\n<blockquote>\n<pre><code>pInImg-&gt;m_R[min(row_ind+1,m_Height-2+abs(row_ind+1)&amp;1)][col_ind-1] + pInImg-m_R[min(row_ind+1,m_Height-2+abs(row_ind+1)&amp;1)][col_ind]*2 + pInImg-m_R[min(row_ind+1,m_Height-2+abs(row_ind+1)&amp;1)][col_ind+1] + 8)&gt;&gt;4;\n</code></pre>\n</blockquote>\n\n<p>A nice long line; not designed to be read by a human.</p>\n\n<blockquote>\n<pre><code> //if(DEBUG_MODE)\n //{\n</code></pre>\n</blockquote>\n\n<p>Doesn't inspire confidence. If it's debug mode why are subsequent lines of code unconditionally enabled?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T07:32:52.080", "Id": "44943", "ParentId": "44900", "Score": "4" } } ]
{ "AcceptedAnswerId": "44943", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T19:53:55.920", "Id": "44900", "Score": "6", "Tags": [ "c++", "algorithm", "c++11", "image" ], "Title": "Image processing algorithm" }
44900
<p>I would like review on the following dynamic memory allocation process and suggestions on whether there are any memory leaks. Following code is not real code in use, but I'm trying to understand concepts of memory allocations and de-allocation in different ways.</p> <pre><code>class ObjMapData { private: //Header Info fields to describe each object actual data type, total elements of actual data type, and lot more describing the object common fields int itsDataTypeID; // 1 to 20+, each represent one type of data being used int itsDataType; // 1 to 8, which could be UINT8, INT8, UINT16, INT16, UINT32, INT32 int itsDataSize; // 1 or 2 or 4 bytes int itsTotalElements; // original data type elements, but not the total bytes of the binary file //...... other common header information // body data, (actual data could be UINT8, INT8, UINT16, INT16, UINT32, INT32 type) char* itsMapData; // size = itsTotalElements*itsDataSize; type cast to various actual data types later to access/populate the data ........ public: ObjMapData(); ObjMapData&amp; operator = (const ObjMapData&amp; objMyMap); ObjMapData(const ObjMapData&amp; objMyMap); ~ObjMapData(){if(itsMapData!= NULL) delete[] itsMapData;} //Following two functions are used to allocate/free memory within the scope of the object so that it can be re-used again for a different data type object ClearMemory() {if(itsMapData!= NULL) {delete[] itsMapData; itsMapData= NULL}} void AllocateMemory( unsigned long nSizeInBytes = 0) { if(itsMapData!= NULL) {delete[] itsMapData; itsMapData= NULL;} itsMapData= new (std::nothrow) INT8[nSizeInBytes]; } ....... void SetMapData(char* ptrData) { itsMapData = ptrData;} // or should I use char*&amp;ptrData?? char* GetMapData() const { return itsMapData;} } </code></pre> <p>Now can I do the following without any memory leaks?</p> <pre><code>//There are 30+ functions like Function1() to populate the map data of different type of maps using different sources of input data or algorithms bool Function1(ObjMapData&amp; objMyMap) { //populate the ptrData with some data values using many different ways int* ptrData = new int[1000]; // usually a variable from binary file header ...................... objMyMap.SetMapData((char*)ptrData); //don't want to delete the memory yet as this map will be used along with map objects to create a new mapdata return true; } bool Function2(ObjMapData&amp; objMyMap) { int* ptrData = (int*) objMyMap.GetMapData(); //do some work such as writing updated data and then write into a binary file } bool Function3(ObjMapData&amp; objMyMap) { //populate the data using different method for different map data types //there could be 30+ other functions like Function1() to populate the map data bool bStatus = Function1(objMyMap); int* ptrData = (int*)objMyMap.GetMapData(); //update the map data by modifying ptrData variable .......... objMyMap.SetMapData((char*)ptrData); // Do I need to set again or member pointer get updated automatically? bStatus = Function2(objMyMap); // write data to a binary file objMyMap.ClearMemory(); // not real code in use, but for understanding the concept bStatus = Function1(objMyMap); // re-allocate memory and assign a new Map Data short* ptrData2 = (short*) objMyMap.GetMapData(); //update the map data using ptrData variable objMyMap.SetMapData((char*)ptrData2); // Do I need to set again or member pointer get updated automatically? return true } int main() { ObjMapData objMyMap; bool bStatus = Function3(objMyMap); short* ptrData = (short*)objMyMap.GetMapData(); //do something with ptrData //default destructor of objMyMap can take care of the allocated memory cleanup return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T22:04:42.993", "Id": "78410", "Score": "0", "body": "Your code is broken (undefined behavior abounds). See my answer below. You should never use C style casts in your code." } ]
[ { "body": "<p>Short Answer: Yes</p>\n\n<p>Longer Answer:\nAs far as I see, your code works without any memory leaks.\nA program which helps you detect memleaks would be valgrind.</p>\n\n<p>With this code you have to be very careful. I recommend checking the pointer before assigning it in <code>SetMapData(int* ptrData)</code>. Something like:</p>\n\n<pre><code>void SetMapData(int* ptrData) // or should I use int*&amp;ptrData?? -&gt; no\n{\n if (itsMapData != NULL &amp;&amp; itsMapData != ptrData)\n {\n delete[] itsMapData;\n } \n itsMapData = ptrData;\n} \n</code></pre>\n\n<p>If you add these lines you don't have to manually call <code>ClearMemory()</code> before assigning new <code>MapData</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T21:36:32.287", "Id": "44905", "ParentId": "44901", "Score": "5" } }, { "body": "<p>SetMapData will not leak on first invocation, it will leak on ayny consecutive invocation. Its a tricky one to get right in multi-threaded settings b.t.w, lots of non-obvious ways to introduce TOCTOU issues. Setter based resource injection is tricky in C++ for numerous reasons. I would suggest you'll try to avoid using this idiom and use good old constructor injected RAII instead whenever possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T06:45:51.467", "Id": "78247", "Score": "0", "body": "Yes, first there is nothing in the interface of ObjMapData to suggest this is mandatory. You could, as Tom sugest add this ClearMemory functionality to SetMapData, but in a multi threading setting that won't fully fix it either. And worse, valgrind will likely not catch it either. Concider what hapens if two threads call SetMapData at the same time. Thread 1 checks and deletes the old one and sets the pointer to NULL, now thread 1 is ready to assign a new value to the pointer, at that point thread 2 checks,sees the value is NULL and feels its also ready to assign a new value to the pointer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T22:02:24.843", "Id": "44910", "ParentId": "44901", "Score": "2" } }, { "body": "<p>Although your client code has no memory leaks, there are a few design problems with your class.</p>\n\n<p>As other answers mention, the interface of the class allows you to use it incorrectly and create memory leaks.</p>\n\n<p>Code:</p>\n\n<pre><code>ObjMapData objMyMap;\nobjMyMap.SetMapData(new char[20]); // leaked when executing next statement\nobjMyMap.SetMapData(new char[20]);\n</code></pre>\n\n<p>The implementation makes bad assumptions how the class will be used. </p>\n\n<pre><code>ObjMapData objMyMap;\nobjMyMap.SetMapData(new char{'a'}); // UB: will be deleted using delete[]\n</code></pre>\n\n<p>You use C-style casts for casting the data. Don't do that - it's unsafe code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T15:25:20.463", "Id": "44982", "ParentId": "44901", "Score": "2" } }, { "body": "<p>Don't do your own memory management. Use the tools provided for you unless you have good reason to do otherwise.</p>\n\n<p>This:</p>\n\n<pre><code>objMyMap.SetMapData((char*)ptrData);\n</code></pre>\n\n<p>causes undefined behavior. This is because when <code>objMyMap</code> is deleted you delete the pointer as a char pointer (it was created as an int pointer). Thus the runtime memory management will probably get the size of the block wrong.</p>\n\n<p>If you ever use a C-Cast then you are probably doing something wrong. Always use C++ style casts. Then it is easy to spot when you are doing things wrong.</p>\n\n<pre><code>const_cast&lt;&gt;() // Bad if you casting away constness.\nreinterpret_cast&lt;&gt;() // Bad unless used to interact with C libraries.\nstatic_cast&lt;&gt;() // Bad if used to cast pointers around\ndynamic_cast&lt;&gt;() // Safe but slow as it is a runtime cast.\n // Note: Only useful for casting down class hierarchy\n // But it is also a sign of bad design.\n</code></pre>\n\n<p>Looking at the class.</p>\n\n<pre><code>class ObjMapData\n{\n</code></pre>\n\n<p>There is no reason do your own memory management.</p>\n\n<pre><code>private:\nchar* itsMapData;\n</code></pre>\n\n<p>This should probably be a <code>std::vector&lt;char&gt;</code>. Once you do that the rest becomes irelavant and all memory management issues are solved.</p>\n\n<pre><code>........\npublic:\nObjMapData();\n</code></pre>\n\n<p>Don't bother to test for NULL. Just delete.</p>\n\n<pre><code>~ObjMapData(){if(itsMapData!= NULL) delete[] itsMapData;}\nClearMemory() {if(itsMapData!= NULL) {delete[] itsMapData; itsMapData= NULL}}\n.......\n</code></pre>\n\n<p>This obviously leaks the memory that you had before.</p>\n\n<pre><code>void SetMapData(char* ptrData) { itsMapData = ptrData;} // or should I use int*&amp;ptrData??\n</code></pre>\n\n<p>Sure. But only if you need to expose that data.\nI would rather encapsolate the manipulation of the data inside the class so you don't need to expose it.</p>\n\n<pre><code>char* GetMapData() const { return itsMapData;}\n}\n</code></pre>\n\n<p>You don't show it so I have to assume you are not following the \"Rule of Three\" (look it up).</p>\n\n<p>I would have done this:</p>\n\n<pre><code>class ObjMapData\n{\n private:\n std::vector&lt;char&gt; itsMapData;\n\n public:\n clearMemory() // lower case first letter of non type.\n {\n itsMapData.swap(std::vector&lt;char&gt;());\n }\n void setMapData(std::vector&lt;char&gt;&amp; ptrData)\n {\n itsMapData.swap(ptrData);\n }\n char* getMapData() const { return &amp;itsMapData[0];}\n};\n</code></pre>\n\n<h3>Addition based on comment:</h3>\n\n<blockquote>\n <p>(could be INT8, UINT8, INT16, UINT16, UINT32, INT32)</p>\n</blockquote>\n\n<pre><code>// Note the above data is not correctly aligned on all systems.\n\n// INT8 INT8 INT16 INT16\n\n01234567 01234567 0123456701234567 0123456701234567 Not a 32 Bit Boundary\n| | | | | | |\n8/16/32 Boundary 8/16 Boundary 8/16/32 Boundary 8/16 Boundary\n 8 Boundary 8 Boundary 8 Boundary\n</code></pre>\n\n<p>But lets assume you just made a typo and you know what you are doing.</p>\n\n<pre><code>// Need room for\n// INT 8 | INT 8 | INT 16 | INT 32 | INT 32\nstd::vector&lt;char&gt; data(96);\n::read(fd, &amp;data[0], 96); // Wow look at that fits neatly.\n\nINT8 d1 = *reinterpret_cast&lt;INT8 *&gt;(&amp;data[ 0]); // The reinterpret cast is required\nINT8 d2 = *reinterpret_cast&lt;INT8 *&gt;(&amp;data[ 8]); // It also shows its really dangerious\nINT16 d3 = *reinterpret_cast&lt;INT16*&gt;(&amp;data[16]);\nINT32 d4 = *reinterpret_cast&lt;INT16*&gt;(&amp;data[32]);\nINT32 d5 = *reinterpret_cast&lt;INT32*&gt;(&amp;data[64]);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:07:55.907", "Id": "78434", "Score": "0", "body": "I am a big fan of 1D, 2D, and 3D vectors and use 80% of the time in my code.. Am using pointers for a specific reason:\nConsider you know the number of data elements and data type of each element along with bunch of other header information before reading the body data. (could be INT8, UINT8, INT16, UINT16, UINT32, INT32)\nSame thing applies when populating and writing binary files of various data types.\n\nI use basic type of char* data and then cast it to various data types based on the header information. \nOnly one class definition with char* handles all 8 types of data objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:17:27.510", "Id": "78436", "Score": "0", "body": "Will it be safe, if I use the dynamic_cast<>() as follows:\nINT16* ptrDataType3 = dynamic_cast<INT16*> (ptrBaseCharDataType);\nINT8* ptrBaseCharDataType = dynamic_cast<INT8*> (ptrDataType3);\nPlease note that I already know that original data type is short and total number elements to fread/fwrite exact number of bytes as TotalElements*EachDataTypeSize;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T06:03:19.547", "Id": "78472", "Score": "1", "body": "@user3442509: No. Added more information about `dynamic_cast<>()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T06:04:25.590", "Id": "78473", "Score": "0", "body": "@user3442509: I would still use `std::vector<char>` in all the above situations (to handle all memory management). See new addition above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T06:22:28.730", "Id": "78474", "Score": "0", "body": "@user3442509: You can convert `std::vector<char>` to `char*` very easily. So still no reason to use `char*`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T17:00:33.217", "Id": "78534", "Score": "0", "body": "Thanks a lot Loki for your insights. I think we are bit off topic. I don't mix and match various data types within itsMapData. So don't need to apply casting on each element. itsMapData is an intermediate char pointer pointing to a block of memory (easy to read/write as a single block and same code is used for multiple data types). It is type casted from original data type before writing to binary file. And while reading, it get type casted back to the original data type again.\nI would appreciate, if you can answer:\nDo I need to set again or member pointer get updated automatically?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T21:50:57.553", "Id": "45031", "ParentId": "44901", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T20:06:44.010", "Id": "44901", "Score": "7", "Tags": [ "c++", "memory-management", "pointers" ], "Title": "Pass pointer data across multiple functions" }
44901
<p>I have a controller with just a few actions, not the whole 7 RESTful actions situation. Here's what I have so far for routing:</p> <pre><code>Snip::Application.routes.draw do get "appointment_reminder_responses/confirmation_thanks", to: "appointment_reminder_responses#confirmation_thanks" get "appointment_reminder_responses/declination_thanks", to: "appointment_reminder_responses#declination_thanks" get "appointment_reminder_responses/:hash", to: "appointment_reminder_responses#create", as: :create_appointment_reminder_response end </code></pre> <p>I think there certainly has to be a way to express this in a more DRY way, but but I'm not sure how that might go.</p>
[]
[ { "body": "<p>Not a lot to review,</p>\n\n<p>obviously the most repeated part of your code is <code>appointment_reminder_responses</code>, if you create a variable called <code>root</code> and then built your routes with concatenations like <br>\n<code>root + \"/confirmation_thanks\"</code> then that would be a good start.</p>\n\n<p>Furthermore you create a function that takes a string and modifies so that <br>\n<code>\"xxx/zzzz/yyyy\"</code> becomes <code>\"xxx/zzz#yyyy\"</code> and use that function for the first 2 routes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T01:32:05.217", "Id": "44925", "ParentId": "44902", "Score": "3" } }, { "body": "<p>Since I don't have your code or your requirements, you can take this with a grain of salt.</p>\n\n<p>Even if there are certainly cases where REST cannot be applied, it seems that you have some sort of entity: <code>AppointmentReminderResponse</code> that you need to create with user information and then you need to give some sort of feedback to the user.</p>\n\n<p>First of all, if you're modifying the state of a model, it's better to use <code>post</code> for the <code>#create</code> action. If you are not, you'd better use the action name <code>#new</code> (or something else) to avoid possible confusions, because of Rails conventions.</p>\n\n<p>Another thing is, if you have an entity that you need to input some information (<code>new</code>), and based on that you will create a document or not (<code>create</code>), and finally you'll give the user some feedback, you could use a RESTful controller and routes for it (even if you don't need the 7 actions).</p>\n\n<p>Having <code>:hash</code> as the key to get the Response should not be a problem.</p>\n\n<p>I think you could write something like this:</p>\n\n<pre><code>resources appointment_reminder_responses, only: [:new, :create] do\n get :confirmation_thanks, to: :confirmation_thanks\n get :declination_thanks, to: :declination_thanks\nend\n</code></pre>\n\n<p>Are you planning to show information from the <code>AppointmentReminderResponse</code> to the <code>confirmation_thanks</code> action? If so, you could go a bit further and consider that action like the <code>show</code> action for that <code>AppointmentReminderResponse</code>, and you'd have:</p>\n\n<pre><code>resources appointment_reminder_responses, only: [:new, :create, :show] do\n get :declination_thanks, to: :declination_thanks\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T12:59:28.857", "Id": "44966", "ParentId": "44902", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T20:09:31.850", "Id": "44902", "Score": "4", "Tags": [ "ruby", "ruby-on-rails", "url-routing" ], "Title": "Routes for reminders" }
44902
<p>I have a JavaScript function that takes in a user number (total amount placed on a betting table in denominations of 50) and returns an Array of the optimum chips (lowest # required) to form each stack.</p> <p>My function works, the correct array for each value tested is output - but since this should be running on the client browser with a fast response time for smooth UI I feel like the code is not optimised. </p> <p>Is there a better, more efficient (+ mathematically solid) way of computing the same output?</p> <p>Any suggestions would be appreciated.</p> <pre><code>//number will be validated before running through function to make sure it has a factor of 50. function chipStack(number) { var k = 0; //1k chip var f = 0; //500 chip var t = 0; //300 chip var o = 0; //100 chip var fi = 0; // 50 chip k = Math.floor(number / 1000); var number2 = number % 1000 if (number2 === 0) { return [k, f, t, o, fi]; } else { f = Math.floor(number2 / 500) var number3 = number2 % 500 } if (number3 === 0) { return [k, f, t, o, fi]; } else { t = Math.floor(number3 / 300) var number4 = number3 % 300 } if (number4 === 0) { return [k, f, t, o, fi]; } else { o = Math.floor(number4 / 100) var number5 = number4 % 100 } if (number5 === 0) { return [k, f, t, o, fi]; } else { fi = Math.floor(number5 / 50) var number6 = number5 % 50 } if (number6 === 0) { return [k, f, t, o, fi]; } else { return "Something isn't right " + number6; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T17:31:47.700", "Id": "78209", "Score": "0", "body": "I guess you could write the code to *look* more compact, but inlined as it is here should execute fast." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T17:33:37.177", "Id": "78210", "Score": "0", "body": "There won't be performance problems, but there are several poor programming practices in that code (`else` after `return`, `var` inside conditional code, etc)." } ]
[ { "body": "<p>You could compress the code as follows. It doesn't check for early exit conditions, but since it's running on the front-end anyway, i.e. not at high volumes, the performance won't be noticeably degraded.</p>\n\n<pre><code>function chipStack(n){\n var chipValues = [1000,500,300,100,50];\n var stack = [];\n chipValues.forEach(function(e,i){\n stack.push(Math.floor(n / e));\n n -= (stack[stack.length-1] * e);\n })\n return stack;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T17:58:40.613", "Id": "44907", "ParentId": "44906", "Score": "2" } }, { "body": "<p>Since you asked for mathematical background…</p>\n\n<p>In general, the <a href=\"http://en.wikipedia.org/wiki/Change-making_problem\" rel=\"nofollow noreferrer\">Change-making problem</a> is a knapsack problem, which is NP-hard. However, <a href=\"https://stackoverflow.com/q/13557979/1157100\">for sane sets of currency denominations, a simple greedy algorithm works</a>.</p>\n\n<p>For your set of denominations, { 1000, 500, 300, 100, 50 }, the greedy algorithm applies. (There is, however, an amount with two optimal solutions: 600 = 500 + 100 = 300 + 300.) Therefore, your greedy algorithm and @MartVandeVen's simplified implementation of it will work.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T22:56:25.777", "Id": "44915", "ParentId": "44906", "Score": "1" } } ]
{ "AcceptedAnswerId": "44907", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T17:23:55.330", "Id": "44906", "Score": "3", "Tags": [ "javascript", "optimization" ], "Title": "Number Division Theory" }
44906
<p>I'm using <code>NSInvocation</code> as a choke point in my app to help manage threading and reduce the amount of redundant code. The purpose of this class is to pass arguments from the view controllers to the API project on a background thread and return success/error on the main thread. I also have a log callback that logs API events in the background. </p> <p>Here's my implementation file: (setArguments isn't being used and probably will be removed)</p> <pre><code>@implementation NSInvocation (Worker) +(NSInvocation*)invocationWithSelector:(SEL)selector { return [NSInvocation invocationWithTarget:[WAAPI class] selector:selector arguments:nil]; } +(NSInvocation*)invocationWithTarget:(id)target selector:(SEL)selector arguments:(NSArray*)arguments { NSMethodSignature *sig = [target methodSignatureForSelector:selector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; [invocation retainArguments]; [invocation setTarget:target]; [invocation setSelector:selector]; if(arguments) { [invocation setArguments:arguments]; } return invocation; } //SET ARGUMENTS //=================================================================================================== -(void)setArguments:(NSArray*)arguments { //An integer (i in the below code) specifying the index of the argument. Indices 0 and 1 indicate the hidden arguments self and _cmd, respectively; //you should set these values directly with the setTarget: and setSelector: methods. Use indices 2 and greater for the arguments normally passed in a message. #warning screwed up for blocks and probably primitive types for(int i = 0; i &lt; arguments.count; i++) { id argument = [arguments objectAtIndex:i+2]; if([argument isKindOfClass:NSClassFromString(@"NSBlock")]) { [self setBlockArgument:argument index:i]; } else { [self setArgument:&amp;argument atIndex:i]; } } } -(void)setBlockArgument:(id)blockArgument index:(NSInteger)index { } -(void)setAsWeakArgument:(id)argument index:(NSInteger)index { __weak id weakArg = argument; [self setArgument:&amp;weakArg atIndex:index]; } //MAKE THE CALL //=================================================================================================== -(NSOperation*)invokeAPICall { @autoreleasepool { [WAWorker background:^{ [self invoke]; }]; return [self apiReturnValue]; } } //RETURN VALUE //=================================================================================================== -(NSOperation*)apiReturnValue { __unsafe_unretained NSOperation *result; [self getReturnValue:&amp;result]; return result; } //SUCCESS //=================================================================================================== -(void)setSuccess:(void(^)(id))success index:(NSInteger)index { [self setSuccess:success title:nil message:nil index:index]; } -(void)setSuccess:(void(^)(id))success title:(NSString*)title message:(NSString*)message index:(NSInteger)index { void(^successBlock)(id) = ^(id s){ [WAWorker main:^{ if(title &amp;&amp; message) { [WANotificationManager showSuccessWithTitle:title message:message]; } if(success) success(s); }]; }; [self setArgument:&amp;successBlock atIndex:index]; } //PROGRESS //=================================================================================================== -(void)setProgress:(void(^)(double))progress index:(NSInteger)index { void(^progressBlock)(double) = ^(double p){ [WAWorker main:^{ if(progress) progress(p); }]; }; [self setArgument:&amp;progressBlock atIndex:index]; } //ERROR //=================================================================================================== -(void)setError:(void(^)(NSError*))error index:(NSInteger)index { [self setError:error message:nil index:index]; } -(void)setError:(void(^)(NSError*))error message:(NSString*)message index:(NSInteger)index { void(^errorBlock)(NSError*) = ^(NSError *e){ [WAWorker main:^{ if(message) { [WAErrorHandler processError:e defaultText:message additionalText:[NSString stringWithFormat:@"%s",sel_getName(self.selector)]]; } if (error) error(e); }]; }; [self setArgument:&amp;errorBlock atIndex:index]; } //LOG //=================================================================================================== -(void)setLogIndex:(NSInteger)index { void(^logBlock)(NSString*, LogType) = ^(NSString *log, LogType logType){ [WAConsoleManager log:log type:logType]; }; [self setArgument:&amp;logBlock atIndex:index]; } @end </code></pre> <p>Here's a couple examples using it:</p> <pre><code>-(void)updateProfileWithSuccess:(void(^)(void))success error:(void(^)(NSError*))error { NSInvocation *invocation = [NSInvocation invocationWithSelector:@selector(profileUpdate:deleted:success:error:log:)]; void(^successBlock)(id) = ^(WAContact *s) { self.dataContact = s; [WAWorker main:^{ [WANotificationManager showSuccessWithTitle:@"Success" message:@"Your information has been updated"]; if(success) success(); }]; }; WAContact *contact = self.dataContact; NSArray *deleted = self.dataDeleted; [invocation setArgument:&amp;contact atIndex:2]; [invocation setArgument:&amp;deleted atIndex:3]; [invocation setArgument:&amp;successBlock atIndex:4]; [invocation setError:error message:@"Failed to update your information" index:5]; [invocation setLogIndex:6]; [invocation invokeAPICall]; } -(void)messageDetails:(NSString*)messageID success:(void (^)(void))success error:(void (^)(NSError*))error { NSInvocation *invocation = [NSInvocation invocationWithSelector:@selector(messageDetails:success:error:log:)]; void(^successBlock)(id) = ^(id s) { self.dataMessage = s; [WAWorker main:^{ if(success) success(); }]; }; [invocation setArgument:&amp;messageID atIndex:2]; [invocation setArgument:&amp;successBlock atIndex:3]; [invocation setError:error index:4]; [invocation setLogIndex:5]; [invocation invokeAPICall]; } </code></pre> <p>Questions:</p> <ol> <li><p>Am I creating retain loops by passing <code>self</code> in any of the blocks?</p></li> <li><p>Is this possible without using <code>retainArguments:</code> in the <code>NSInvocation</code> category?</p></li> <li><p>Are there any other issues with this implementation?</p></li> </ol>
[]
[ { "body": "<p>This is one of my weakspots, but if you are ever concerned about a retain loop in a block, create a weak variable:</p>\n\n<pre><code>__weak typeof(self) weakSelf = self;\n</code></pre>\n\n<p>Now just use <code>weakSelf</code> anywhere you'd use <code>self</code> in that block, and there's no chance that the block will create a retain cycle.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T11:29:22.437", "Id": "46901", "ParentId": "44908", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T21:57:24.657", "Id": "44908", "Score": "9", "Tags": [ "multithreading", "objective-c", "memory-management", "ios", "category" ], "Title": "NSInvocation Implementation" }
44908
<p>I've just completed this binary search kata - which has some weird requirements - and I spent a little while "cleaning" up my code and making it more compact. I would appreciate some feedback on the readability of the <code>BinarySearch</code> class. I've packed a lot of logic into some of the lines and I'd like to know if that makes it more or less readable.</p> <p>A Ruby Kata for Binary Search of Arrays:</p> <pre><code>Binary Search Kata Create a binary search class that is initialized with an array of integers - detail: Do not use built in array functions - detail: The initial array is [1,3] - detail: return the index of the search value if found - example: searching for 3 returns 1 completed (Y|n): Successfully deal with values that are not in the data set - example: searching for 5 indicates to the caller the value is not found completed (Y|n): Binary Search handles an odd number of elements in the data set - detail: Allows the data set to be redefined with [1,3,5,7,9] - example: Searching for 5 returns 2 - example: Searching for 7 returns 3 completed (Y|n): Handles more than trivial sized data set - detail: consider a data set of the first 10000 integers - example: Searching for 899 returns 898 completed (Y|n): Supports duplicate elements in the data set - detail: Use [1,3,5,5,7,9] as the data set - example: Searching for 3 returns 1 - example: Searching for 5 returns 2 completed (Y|n): Handles expired call for duplicate elements - detail: Use [1,3,5,5,7,9] as the data set - example: Third call to search for 5 is handled like missing element completed (Y|n): Supports sorted array of strings - detail: Use ["a", "b", "c", "d"] as the data set - example: Searching for "c" returns 2 completed (Y|n): Supports duplicate strings - detail: Use ["a", "b", "c", "c", "d"] as the data set - example: First search for "c" returns 2 - example: Second search for "c" returns 3 completed (Y|n): Handles expired call for duplicate string elements - detail: Use ["a", "b", "c", "c", "d"] as the data set - example: Third call to search for "c" is handled like missing element completed (Y|n): ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┓ ┃ Requirement ┃ Time ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Create a binary search class that is initialized with an array of integers ┃ 00:04:02 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Successfully deal with values that are not in the data set ┃ 00:04:09 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Binary Search handles an odd number of elements in the data set ┃ 00:10:49 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Handles more than trivial sized data set ┃ 00:02:28 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Supports duplicate elements in the data set ┃ 00:05:17 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Handles expired call for duplicate elements ┃ 00:10:35 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Supports sorted array of strings ┃ 00:02:27 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Supports duplicate strings ┃ 00:02:35 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫ ┃ Handles expired call for duplicate string elements ┃ 00:00:57 ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━┛ Questions: - What about supporting duplicate data changed your solution? - Did your approach get better or worse after dealing with duplicates? - What was the hardest part about adding support for strings? - Can you think of a different technique for building the kata? - What can you say about the relative merits of the various techniques you chose? - Which is the most likely to make it into production code? - Which was the most fun to write? - Which requirement was the hardest to get working? - For all of the above, ask yourself why? </code></pre> <p>My Specs:</p> <pre><code> 1 require 'spec_helper' 2 require 'binary_search' 3 require 'its' 4 5 describe BinarySearch do 6 subject(:binary_search) { BinarySearch.new(data) } 7 let(:data) { [1,3] } 8 9 describe "#initialize" do 10 it "instantiates" do 11 expect { binary_search }.to_not raise_exception 12 end 13 end 14 15 describe '.find' do 16 its(:find, 3) { should eq(1) } 17 its(:find, 5) { should be_nil } 18 19 context 'odd numbers of elements in data set' do 20 let(:data) { [1,3,5,7,9] } 21 its(:find, 0) { should be_nil } 22 its(:find, 1) { should eq(0) } 23 its(:find, 2) { should be_nil } 24 its(:find, 3) { should eq(1) } 25 its(:find, 4) { should be_nil } 26 its(:find, 5) { should eq(2) } 27 its(:find, 6) { should be_nil } 28 its(:find, 7) { should eq(3) } 29 its(:find, 8) { should be_nil } 30 its(:find, 9) { should eq(4) } 31 its(:find, 10) { should be_nil } 32 end 33 34 context 'non trivial data sets' do 35 let(:data) { [] } 36 before { for i in 1..10000 do data &lt;&lt; i end } 37 its(:find, 899) { should eq(898) } 38 end 39 40 context 'duplicate data elements' do 41 let(:data) { [1,3,5,5,7,9] } 42 its(:find, 3) { should eq(1) } 43 its(:find, 5) { should eq(2) } 44 it 'handles expired calls for duplicate elements' do 45 2.times do binary_search.find(5) end 46 binary_search.find(5).should be_nil 47 end 48 end 49 50 context 'sorted array of strings' do 51 let(:data) { ['a','b','c','d'] } 52 its(:find, 'a') { should eq(0) } 53 its(:find, 'b') { should eq(1) } 54 its(:find, 'c') { should eq(2) } 55 its(:find, 'd') { should eq(3) } 56 its(:find, 'x') { should be_nil } 57 end 58 59 context 'duplicate strings' do 60 let(:data) { ['a', 'b', 'c', 'c', 'd'] } 61 its(:find, 'c') { should eq(2) } 62 it 'handles multiple searches' do 63 binary_search.find('c') 64 binary_search.find('c').should eq(3) 65 end 66 it 'handles expired calls for strings' do 67 2.times do binary_search.find('c') end 68 binary_search.find('c').should be_nil 69 end 70 end 71 end 72 end </code></pre> <p>And, the <code>BinarySearch</code> Class:</p> <pre><code> 1 class BinarySearch 2 def initialize(data) 3 @data = data 4 @search_hash = Hash.new 5 end 6 7 def find(target) 8 return @search_hash[target] = first_find(target) unless @search_hash[target] 9 return @data[@search_hash[target] + 1] == target ? @search_hash[target] += 1 : nil 10 end 11 12 private 13 14 def first_find(target) 15 return nil unless pivot = bsearch(target, @data) 16 pivot -= 1 while @data[pivot - 1] == target 17 return pivot 18 end 19 20 def bsearch(target, data) 21 pivot = data.length / 2 22 23 return pivot if data[pivot] == target 24 return nil if pivot == 0 25 26 if data[pivot] &gt; target 27 return bsearch(target, data[0..pivot - 1]) 28 else 29 offset = bsearch(target, data[pivot..-1]) 30 return offset ? pivot + offset : nil 31 end 32 end 33 end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T16:27:59.333", "Id": "78321", "Score": "1", "body": "please, don't include line numbers in the code or you're forcing people to remove them... can you edit it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T01:59:40.427", "Id": "78432", "Score": "0", "body": "Sorry about that. Line numbers are super easy to remove in vim so I never realized they were a pain for others. I'll edit the question when I'm back at my desk. Or, you can edit it for sweet smelling karma. Jamal follows me around deleting all of my \"pleases\" and \"thank yous\" to get those points. You could actually improve the question for your karma ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:44:44.437", "Id": "78442", "Score": "0", "body": "What rspec extension, or what version of rspec, is providing the special syntax for `its`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T17:49:59.867", "Id": "78536", "Score": "0", "body": "That's the \"its\" gem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T13:20:48.940", "Id": "78605", "Score": "0", "body": "This is a good question. Would you consider replacing the section named \"A Ruby Kata for Binary Search of Arrays\" with a link to the Kata? That section didn't help me to understand the exercise, so it can probably go. A link to the kata, however, would be valuable." } ]
[ { "body": "<p>This is pretty good code. It <em>is</em> a little compact, but that only hurts readability in a few places. I will make some\nsuggestions that fluff it out just a bit, and might make it more\nunderstandable for some readers. Most of what I bring up here is\nquite minor. The important stuff is at the end, where I suggest\nreorganizing #find, and describe a bug.</p>\n\n<h1>Prefer {...} for single-line blocks</h1>\n\n<p><code>{...}</code> is preferred for single-line blocks; <code>begin...end</code> for\nmulti-line. So, instead of this:</p>\n\n<pre><code>2.times do binary_search.find('c') end\n</code></pre>\n\n<p>this:</p>\n\n<pre><code>2.times { binary_search.find(5) }\n</code></pre>\n\n<h1>Implicit vs. explicit <em>return</em></h1>\n\n<p>The value of the last executed expression in a method becomes the\nreturn value of the method; this allows you to omit many instances of\n<code>return</code>. So, instead of this:</p>\n\n<pre><code> ...\n return pivot\nend\n</code></pre>\n\n<p>you can do this:</p>\n\n<pre><code> ...\n pivot\nend\n</code></pre>\n\n<p>The value of an \"if\" expression is the value of the last expression it\nexecuted, so instead of this:</p>\n\n<pre><code>if data[pivot] &gt; target\n return bsearch(target, data[0..pivot - 1])\nelse\n offset = bsearch(target, data[pivot..-1])\n return offset ? pivot + offset : nil\nend\n</code></pre>\n\n<p>you can do this:</p>\n\n<pre><code>if data[pivot] &gt; target\n bsearch(target, data[0..pivot - 1])\nelse\n offset = bsearch(target, data[pivot..-1])\n offset ? pivot + offset : nil\nend\n</code></pre>\n\n<h1>Typo in a \"describe\" description</h1>\n\n<p>I think this is just a typo. Since <em>find</em> is an instance method,\nthis:</p>\n\n<pre><code>describe '.find' do\n</code></pre>\n\n<p>should instead be:</p>\n\n<pre><code>describe '#find' do\n</code></pre>\n\n<h1>Testing that the constructor does not die</h1>\n\n<p>Since every one of the specs implicitly tests that the constructor\ndoes not die, and because that is the normal expectation for a\nconstructor, there is no need to implicitly test that the constructor\ndoes not raise an exception. This can safely be removed from the\nspec:</p>\n\n<pre><code>describe \"#initialize\" do\n it \"instantiates\" do\n expect { binary_search }.to_not raise_exception\n end\nend\n</code></pre>\n\n<h1>Names</h1>\n\n<ul>\n<li><p>In class <em>BinarySearch</em>, the instance variable <code>@search_hash</code> needs\na better name. This one is a bit tough (naming is hard!), but until\na truly good name is found, I suggest <code>@found_indices</code> as a name\nthat gives the reader a better clue about what the hash is being\nused for.</p></li>\n<li><p>A better name for <code>BinarySearch#find</code> might be <em>index</em>. This is\nconsistent with the built-in <code>Array#index</code>, and so less surprising.</p></li>\n<li><p>Similarly, consider renaming <code>BinarySearch#first_find</code> to\n<code>first_index</code>.</p></li>\n</ul>\n\n<h1>Creating a hash</h1>\n\n<p>It is more usual, when creating an empty hash, to do this:</p>\n\n<pre><code>@found_indices = {}\n</code></pre>\n\n<p>rather than this:</p>\n\n<pre><code>@found_indices = Hash.new\n</code></pre>\n\n<h1>Use &amp;&amp; to eliminate a use of the trinary operator</h1>\n\n<p>This:</p>\n\n<pre><code>offset ? pivot + offset : nil\n</code></pre>\n\n<p>may be more succinctly stated as:</p>\n\n<pre><code>offset &amp;&amp; pivot + offset\n</code></pre>\n\n<h1>Expanding BinarySearch#find</h1>\n\n<p>I had trouble following the flow of control here:</p>\n\n<pre><code>def find(target)\n return @search_hash[target] = first_find(target) unless @search_hash[target]\n return @data[@search_hash[target] + 1] == target ? @search_hash[target] += 1 : nil\nend\n</code></pre>\n\n<p>We can make it easier to follow, and solve another problem: It isn't\nobvious at first that this binary search handles duplicate values by\nreturn successive indices. Let's draw it in crayon:</p>\n\n<pre><code>def find(target)\n unless @found_indices[target]\n find_first(target)\n else\n find_next(target)\n end\nend\n\nprivate\n\ndef find_first(target)\n @found_indices[target] = first_index(target)\nend\n\ndef find_next(target)\n next_index = @found_indices[target] + 1\n return nil unless @data[next_index] == target\n @found_indices[target] = next_index\n next_index\nend\n</code></pre>\n\n<p>The result of <code>@found_indices[target] = next_index</code> is <code>next_index</code>, so the last line that explicitly returns <code>next_index</code> is, strictly speaking, unnecessary. However, it does make the code more clear.</p>\n\n<h1>A bug with repeating values</h1>\n\n<p>If the array has only one distinct value, whether repeated or not,\nthen there's a bug. This spec exposes it:</p>\n\n<pre><code>context 'array of identical values' do\n let(:data) { [1, 1] }\n specify do\n binary_search.find(1).should eq 0 # =&gt; Expected 0; got -2\n binary_search.find(1).should eq 1\n binary_search.find(1).should be_nil\n end\nend\n</code></pre>\n\n<p>The problem is here:</p>\n\n<pre><code>def first_index(target)\n return nil unless pivot = bsearch(target, @data)\n pivot -= 1 while @data[pivot - 1] == target # The bug is here\n pivot\nend\n</code></pre>\n\n<p>When pivot is 0, the expression <code>@data[pivot - 1]</code> becomes\n<code>@data[-1]</code>, which gets the <em>last value in @data</em>. The code ends up\nwrappting from the beginning to the end of the array. The fix is to\ncheck that pivot is greater than 0 before decrementing it:</p>\n\n<pre><code> pivot -= 1 while pivot &gt; 0 &amp;&amp; @data[pivot - 1] == target\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T13:41:45.947", "Id": "45143", "ParentId": "44912", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T22:06:41.087", "Id": "44912", "Score": "5", "Tags": [ "ruby", "binary-search", "rspec" ], "Title": "BinarySearch Kata in Ruby" }
44912
<p>I'm doing a programming practice problem and was wondering if someone can suggest a better to create/setup the call back for the comparison function. I have the following classes:</p> <pre><code>public class myTreeItem&lt;T&gt; { private T item; private myTreeItem&lt;T&gt; left; private myTreeItem&lt;T&gt; right; private myTreeItem&lt;T&gt; parent; } </code></pre> <p>I have the usual get/set functions. This item go into a tree, whose definition is:</p> <pre><code>public class myTree&lt;T&gt; { myTreeItem&lt;T&gt; root; protected comparableCallBack&lt;T&gt; callback; // call back function for comparisons, to be provided by the creator of the tree public interface comparableCallBack&lt;T&gt; { int onCompare(myTreeItem&lt;T&gt; item1, myTreeItem&lt;T&gt; item2); } } </code></pre> <p>I omitted all the other functions to help with readability. I am creating the tree in the following way:</p> <pre><code> // create a regular tree myTree&lt;Integer&gt; tree1 = new myTree&lt;Integer&gt;(); tree1.setCallback(new comparableCallBack&lt;Integer&gt;() { public int onCompare(myTreeItem&lt;Integer&gt; item1, myTreeItem&lt;Integer&gt; item2) { // Do the actual comparison here. if (item1.getItem().intValue() &lt; item2.getItem().intValue()) return -1; else if (item1.getItem().intValue() == item2.getItem().intValue()) return 0; else return 1; } }); </code></pre> <p>Are there any other options/ideas for the call back?</p>
[]
[ { "body": "<h2>Comparator</h2>\n\n<p>There is no need for your interface.... <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html\" rel=\"nofollow\">what's wrong with <code>Comparator</code></a>? Why do you need to have your own?</p>\n\n<p>The reason you appear to have it is because you need to compare the <code>myTreeItem</code> against another <code>myTreeItem</code> and the generic type is not right for you, but you can solve it easily with wrapping the Comparator in your myTree class when you need to....</p>\n\n<p>So, your code has:</p>\n\n<blockquote>\n<pre><code>tree1.setCallback(new comparableCallBack&lt;Integer&gt;() {\n public int onCompare(myTreeItem&lt;Integer&gt; item1,\n myTreeItem&lt;Integer&gt; item2) {\n .......\n }\n });\n</code></pre>\n</blockquote>\n\n<p>but it should instead have:</p>\n\n<pre><code>tree1.setCallback(new Comparator&lt;Integer&gt;() {\n public int compare(Integer item1, Integer item2) {\n .......\n }\n });\n</code></pre>\n\n<p>and then, your library should have it's own private Comparator that looks something like:</p>\n\n<pre><code>class TreeComparator &lt;T&gt; implements Comparator&lt;myTreeItem&lt;T&gt;&gt; {\n\n private final Comparator&lt;T&gt; delegate;\n TreeComparator(Comparator&lt;T&gt; delegate) {\n this.delegate = delegate;\n }\n public int compare(myTreeItem&lt;T&gt; a, myTreeItem&lt;T&gt; b) {\n return delegate.compare(a.getItem(), b.getItem());\n }\n}\n</code></pre>\n\n<h2>Code Style</h2>\n\n<p>Read the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html\" rel=\"nofollow\">Java Code-style guidelines</a>.</p>\n\n<p>Java class names should start with a capital letter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:37:10.213", "Id": "78329", "Score": "0", "body": "Yes I was trying to create a comparator for the tree item. The suggestions make sense... I wasn't sure how to use the Comparator to create my own (guess I am more rusty than I thought). Agree on the guidelines too... I was trying to quickly put something together to post here I didn't follow all the guidelines." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T00:25:15.587", "Id": "44919", "ParentId": "44913", "Score": "3" } }, { "body": "<p>I agree with <em>@rolfl</em> that <code>Comparator</code> should be used here, +1, and some other notes:</p>\n\n<ol>\n<li><p>If doesn't make sense to create a tree without a comparator it should be a required constructor parameter. It would reduce the possible number of misuses (as well as bugs and <code>NullPointerException</code>s).</p></li>\n<li><p>Just a sidenote: it's good to know that most Java types implements <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html\" rel=\"nofollow noreferrer\"><code>Comparable</code></a>:</p>\n\n<pre><code>public interface Comparable&lt;T&gt; {\n public int compareTo(T o);\n}\n</code></pre>\n\n<p>You could use that it the type definition:</p>\n\n<pre><code>public class myTree&lt;T extends Comparable&lt;T&gt;&gt; {\n</code></pre>\n\n<p>Although, it's probably too strict. Not all types implements this interface and sometimes it's required to create a tree based on another comparison (for example, to build reversed tree).</p></li>\n<li><p>The <code>comparableCallBack</code> interface could be <code>static</code>. See: <em>Effective Java 2nd Edition</em>, <em>Item 22: Favor static member classes over nonstatic</em></p></li>\n<li><blockquote>\n<pre><code>public int onCompare(myTreeItem&lt;Integer&gt; item1,\n myTreeItem&lt;Integer&gt; item2) {\n // Do the actual comparison here.\n if (item1.getItem().intValue() &lt; item2.getItem().intValue())\n return -1;\n else if (item1.getItem().intValue() == item2.getItem().intValue())\n return 0;\n else\n return 1;\n }\n</code></pre>\n</blockquote>\n\n<p>You could extract out two local variables here to remove some duplication:</p>\n\n<pre><code>int value1 = item1.getItem().intValue();\nint value2 = item2.getItem().intValue();\n</code></pre>\n\n<p>(It looks like that the closing brace closes the if statement. It should be one level outer.)</p></li>\n<li><p>If you don't have a good reason to not to do that, make the fields <code>private</code>:</p>\n\n<blockquote>\n<pre><code>myTreeItem&lt;T&gt; root;\nprotected comparableCallBack&lt;T&gt; callback; // call back function for comparisons, to be provided by the creator of the tree\n</code></pre>\n</blockquote>\n\n<p>(<a href=\"https://stackoverflow.com/q/5484845/843804\">Should I always use the private access modifier for class fields?</a>; <em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.)</p></li>\n<li><p>Comments like this are rather noise:</p>\n\n<pre><code>// Do the actual comparison here.\n</code></pre>\n\n<p>The code is obvious here, so I'd remove the comment. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T04:21:07.680", "Id": "44932", "ParentId": "44913", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T22:40:38.367", "Id": "44913", "Score": "6", "Tags": [ "java", "tree", "callback" ], "Title": "Alternate way for comparison call back function?" }
44913
<p>I just got into <code>struct</code>s and I decided to create a list using them:</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; int main(void) { char counter; struct list { int x; struct list *pointer1; }; struct list test; struct list *pointer2; pointer2=&amp;test; for(counter=0;counter&lt;5;counter++) { pointer2-&gt;pointer1=malloc(sizeof(struct list)); pointer2=pointer2-&gt;pointer1; } } </code></pre> <p>I was wondering if there is another way to do the exact same thing. Is the use of one pointer only possible? By the way, I am pretty sure I could do the same thing using an array of <code>struct</code>s too. Any advice would be really helpful!</p>
[]
[ { "body": "<p>This is actually rather unconventional code. The head node of this list, <code>test</code>, resides on the stack. All of the subsequent nodes are allocated from the heap using <code>malloc()</code>. Since you never call <code>free()</code> on the memory returned by <code>malloc()</code>, you have a memory leak. When you eventually try to fix your memory leak, you're very likely to get confused: you need to <code>free()</code> all the nodes <em>except <code>test</code></em>.</p>\n\n<p>Furthermore, linked lists are usually terminated by a <code>NULL</code> pointer. After this program finishes, though, the tail of the list is an uninitialized chunk of memory from <code>malloc()</code>, which you should consider to return random garbage. (In practice, you are likely to get lucky and receive pre-zeroed memory since your program is running on a virgin heap, but you should <em>not</em> count on that behaviour.)</p>\n\n<p>I suggest that you build the linked list all on the heap. Also, build it backwards, starting from the tail, so that your pointer is always pointing to the head. When you're done, you'll be holding a pointer to the head, which is useful.</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n\nint main(void)\n{\n struct list\n {\n int x; \n struct list *next;\n };\n\n /* Create the list */\n struct list *head = NULL;\n /* Just use an int for the counter. A char is just weird. */\n for (int counter = 0; counter &lt; 6; counter++)\n {\n struct list *node = malloc(sizeof(*node));\n node-&gt;next = head;\n head = node;\n }\n\n /* Destroy the list */\n while (head) {\n struct list *node = head;\n head = head-&gt;next;\n free(node);\n }\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-02T14:39:16.450", "Id": "80350", "Score": "0", "body": "since we are in code review site, wouldn't you want the int in the for loop to be unsigned?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T09:37:28.810", "Id": "44949", "ParentId": "44917", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T23:10:45.510", "Id": "44917", "Score": "4", "Tags": [ "c", "linked-list", "pointers" ], "Title": "Creating a list using a struct in C" }
44917
<p>I need to pull the version # out of a Vim script that might look something like:</p> <pre><code> " some header blah blah " Version: 0.1 [a bunch of code] " Version: fake--use only the first version </code></pre> <p>The expected output is <code>0.1</code>. If a Version # doesn't exist, it should return the empty string or something like that.</p> <p>I'm new to Powershell, so this is what I have so far:</p> <pre><code>Get-Content somescript.vim -ErrorAction SilentlyContinue | Select-String '^" Version: (.*)' | select -First 1 -ExpandProperty Matches | select -ExpandProperty Groups | select -Index 1 | select -ExpandProperty Value </code></pre> <p>It's just that it feels... kind of verbose. For comparison, here's my *nix version:</p> <pre><code>perl -ne '/^" Version: (.*)/ &amp;&amp; do { print "$1\n"; exit }' somescript.vim 2&gt;/dev/null </code></pre> <p><em>Or you could write a similarly concise <code>awk</code> script</em></p> <p>Is there any hope for my Windows version being as concise?</p>
[]
[ { "body": "<p>I haven't found a terser approach using only built-ins, but having a little more confidence now in Powershell, I think I'd simply refactor out the group matching code:</p>\n\n<pre><code>filter Select-MatchingGroupValue($groupNum) {\n if (! $groupNum) {\n $groupNum = 0\n }\n select -InputObject $_ -ExpandProperty Matches |\n select -ExpandProperty Groups |\n select -Index $groupNum |\n select -ExpandProperty Value\n}\n</code></pre>\n\n<p>Then you could use it like:</p>\n\n<pre><code>Get-Content .\\somescript.vim -ErrorAction SilentlyContinue |\n Select-String '^\" Version: (.*)' |\n select -First 1 |\n Select-MatchingGroupValue 1\n</code></pre>\n\n<p>In the end, you haven't saved that many lines, but refactoring out the tedious expansions of <code>Matches</code>, <code>Groups</code>, and <code>Value</code> makes the resulting code much clearer IMO.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T15:07:04.643", "Id": "48058", "ParentId": "44920", "Score": "3" } }, { "body": "<p>In PowerShell everything is an object, so you can access properties (and properties of properties) using the dot operator just like you can in most object based languages.</p>\n\n<pre><code>$matches = Get-Content somescript.vim -ErrorAction SilentlyContinue |\n Select-String '^\" Version: (.*)'\n\nif ($matches)\n{\n $matches[0].Matches.Groups[1].Value\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-23T19:40:12.663", "Id": "89119", "Score": "0", "body": "Ah, of course, just use an intermediate result. Hadn't thought of it, but totally obvious in retrospect." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-23T04:24:56.630", "Id": "51478", "ParentId": "44920", "Score": "3" } } ]
{ "AcceptedAnswerId": "51478", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T00:39:39.117", "Id": "44920", "Score": "6", "Tags": [ "regex", "powershell" ], "Title": "Extract version string from text file with Powershell" }
44920
<p>I am doing some programming on the side and would just like to know if I'm going in the right direction with my code.</p> <pre><code>public class FileTransfer { #region Variables private const int MAX_CHUNK_SIZE = (1024 * 5000); private static BinaryWriter fileWriter; private static FileStream fileReader; private static List&lt;string&gt; files; private static NetworkStream clientStream; private static byte[] fileData; private static UInt32 dataLength; #endregion #region Functions /// &lt;summary&gt; /// Default Constructor Initializes a new list of files /// and a new byte array set to the max chunk size /// &lt;/summary&gt; public FileTransfer() { files = new List&lt;string&gt;(); fileData = new byte[MAX_CHUNK_SIZE]; } /// &lt;summary&gt; /// Uses the Given File Stream to receive a file /// &lt;/summary&gt; /// &lt;returns&gt;Returns a bool depending on if the file was succesfully received or not.&lt;/returns&gt; public bool ReceiveFile(TcpClient client, string saveLocation = @"Files") { clientStream = client.GetStream(); string fileName = GetFileName(); dataLength = GetFileLength(); OpenSaveFilePath(saveLocation + "/" + fileName); while (dataLength != 0 &amp;&amp; client.Connected) { int bytesRead = GetNextChunk(); if (bytesRead != 0) WriteChunkToFile(bytesRead); } fileWriter.Close(); return true; } /// &lt;summary&gt; /// Writes the read file chunk to the opened file /// &lt;/summary&gt; /// &lt;param name="bytesRead"&gt;number of bytes read that chunk&lt;/param&gt; private static void WriteChunkToFile(int bytesRead) { fileWriter.Write(fileData, 0, bytesRead); dataLength -= (UInt32)bytesRead; SetByteArray(out fileData, dataLength); } /// &lt;summary&gt; /// Gets the next chunk of data from the file /// &lt;/summary&gt; /// &lt;returns&gt; Returns the total number of bytes read this chunk&lt;/returns&gt; private static int GetNextChunk() { int byteTotal = 0; do { int dataBytes = clientStream.Read(fileData, byteTotal, (fileData.Length - byteTotal)); byteTotal += dataBytes; } while (byteTotal &lt; fileData.Length || clientStream.DataAvailable); return byteTotal; } /// &lt;summary&gt; /// Opens the file path to save the file in /// Checks for existence of file and renames file with (number) if it does exist /// &lt;/summary&gt; /// &lt;param name="filePath"&gt;file path to save file to&lt;/param&gt; private static void OpenSaveFilePath(string filePath) { int enumeration = 1; string tempPath = filePath.Substring(0, filePath.IndexOf(".", StringComparison.Ordinal)); string tempExtension = filePath.Substring(filePath.IndexOf(".", StringComparison.Ordinal), (filePath.Length - tempPath.Length)); if (File.Exists(filePath)) { while (File.Exists(tempPath + tempExtension)) { tempPath = filePath.Substring(0, filePath.IndexOf(".", StringComparison.Ordinal)); tempPath += "(" + enumeration + ")"; enumeration++; } filePath = tempPath + tempExtension; } fileWriter = new BinaryWriter(File.Open(filePath, FileMode.CreateNew)); } /// &lt;summary&gt; /// Gets the file name from the current client stream /// &lt;/summary&gt; /// &lt;returns&gt;Returns the file name as a string&lt;/returns&gt; private static string GetFileName() { byte[] fileNameLengthBytes = new byte[sizeof(int)]; clientStream.Read(fileNameLengthBytes, 0, 4); int fileNameLength = BitConverter.ToInt32(fileNameLengthBytes, 0); byte[] fileName = new byte[fileNameLength]; clientStream.Read(fileName, 0, fileNameLength); return Encoding.UTF8.GetString(fileName, 0, fileNameLength); } /// &lt;summary&gt; /// Get the length of the file from the received client stream /// &lt;/summary&gt; /// &lt;returns&gt;Returns the length of the file&lt;/returns&gt; private static UInt32 GetFileLength() { byte[] length = new byte[sizeof(UInt32)]; clientStream.Read(length, 0, sizeof(UInt32)); return BitConverter.ToUInt32(length, 0); } /// &lt;summary&gt; /// Sets the size of the byte array depending on number of bytes left to send/receive /// &lt;/summary&gt; /// &lt;param name="file"&gt;byte array to set&lt;/param&gt; /// &lt;param name="bytesLeft"&gt;number of bytes left to send/receive&lt;/param&gt; private static void SetByteArray(out byte[] file, UInt32 bytesLeft) { file = bytesLeft &lt; MAX_CHUNK_SIZE ? new byte[bytesLeft] : new byte[MAX_CHUNK_SIZE]; } /// &lt;summary&gt; /// Retrieves all the files from the Files folder in the current directory /// &lt;/summary&gt; private static void GetCurrentFiles() { DirectoryInfo directory = new DirectoryInfo("Files"); files = directory.GetFiles().OfType&lt;string&gt;().ToList&lt;string&gt;(); } /// &lt;summary&gt; /// Sends the preliminary data to the client /// file name and length of file in bytes /// &lt;/summary&gt; /// &lt;param name="filePath"&gt;File path to file&lt;/param&gt; private static void SendFileData(string filePath) { string fileName = Path.GetFileName(filePath); fileReader = new FileStream(filePath, FileMode.Open, FileAccess.Read); UInt32 numberOfBytesToRead = (UInt32)fileReader.Length; if (fileName != null) { byte[] fileNameBytes = Encoding.UTF8.GetBytes(fileName); byte[] fileNameLength = BitConverter.GetBytes(fileName.Length); byte[] dataSize = BitConverter.GetBytes(numberOfBytesToRead); byte[] clientData = new byte[4 + fileName.Length + sizeof(UInt32)]; fileNameLength.CopyTo(clientData, 0); fileNameBytes.CopyTo(clientData, 4); dataSize.CopyTo(clientData, (fileName.Length + 4)); clientStream.Write(clientData, 0, clientData.Length); } } /// &lt;summary&gt; /// Sends a file to the remote client /// &lt;/summary&gt; /// &lt;param name="client"&gt;Client to send file to&lt;/param&gt; /// &lt;param name="filePath"&gt;File Path to the file&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public bool SendFile(TcpClient client, string filePath) { clientStream = client.GetStream(); SendFileData(filePath); UInt32 fileSizeInBytes = (UInt32)fileReader.Length; int numberOfBytesRead = 0; SetByteArray(out fileData, fileSizeInBytes); while (numberOfBytesRead &lt; fileSizeInBytes) { numberOfBytesRead += WriteFileToStream(fileSizeInBytes); } fileReader.Close(); return true; } /// &lt;summary&gt; /// Reads the bytes from the file and sends it over the network /// &lt;/summary&gt; /// &lt;param name="fileSizeInBytes"&gt;Total size of file in bytes&lt;/param&gt; /// &lt;returns&gt;returns number of bytes read from the file&lt;/returns&gt; public static int WriteFileToStream(UInt32 fileSizeInBytes) { int done = fileReader.Read(fileData, 0, fileData.Length); clientStream.Write(fileData, 0, fileData.Length); SetByteArray(out fileData, fileSizeInBytes); return done; } #endregion #region Accessors public int GetMaxChunkSize { get { return MAX_CHUNK_SIZE; } } public BinaryWriter FileWriter { get { return fileWriter; } } public FileStream FileReader { get { return fileReader; } } public List&lt;string&gt; GetFiles { get { return files; } } public NetworkStream ClientStream { set { clientStream = value; } get { return clientStream; } } public UInt32 GetDataLength { get { return dataLength; } } #endregion } </code></pre>
[]
[ { "body": "<p>Why all these <code>private static</code> members? Instead of making them <code>private static</code>, you should be passing them around as parameters and return values, or take them in (from the constructor) as <em>dependencies</em>.</p>\n\n<p>These <code>private static</code> variables make the code quite hard to follow, every method can access any of them, the message is not clear.</p>\n\n<p>If you have ReSharper, it will <em>suggest</em> to make a method <code>static</code> if it's not accessing any instance members, or if it's only accessing <code>static</code> members. Don't take this <em>suggestion</em> as a <em>recommendation</em> - it's not. R# is only <em>letting you know</em> that the method <em>can</em> be made static. Nothing more. In general, it's best to steer away from anything <code>static</code>, especially when you're dealing with <code>IDisposable</code> stuff.</p>\n\n<hr>\n\n<p><strong>Some potential issues</strong></p>\n\n<p>Having <code>private static</code> object variables is one thing; having <code>private static</code> object variables <em>that implement <code>IDisposable</code></em> is another.</p>\n\n<p>The class is not thread-safe, and if you tried using multiple instances of it, you could potentially experience behavior I'm sure wasn't intended. Keep things well encapsulated at <em>instance</em> level. <code>static</code> puts a member at <em>type</em> level, which means everything <code>static</code> is <em>shared</em> between instances (hence <code>static</code> is <code>Shared</code> in VB).</p>\n\n<p>Readers, writers, streams - all these things are disposable. Sure, you <code>Close()</code> them, but anything <code>IDisposable</code> should be <code>.Dispose()</code>'d.</p>\n\n<p>Also:</p>\n\n<blockquote>\n<pre><code> do\n {\n int dataBytes = clientStream.Read(fileData, byteTotal, (fileData.Length - byteTotal));\n byteTotal += dataBytes;\n } while (byteTotal &lt; fileData.Length || clientStream.DataAvailable);\n</code></pre>\n</blockquote>\n\n<p>This <code>do</code> loop will always iterate <em>at least once</em>. Thus, if the <code>while</code> condition is met from the start, I'm expecting this method to blow up. This would solve it:</p>\n\n<pre><code>while (byteTotal &lt; fileData.Length || clientStream.DataAvailable)\n{\n int dataBytes = clientStream.Read(fileData, byteTotal, (fileData.Length - byteTotal));\n byteTotal += dataBytes;\n};\n</code></pre>\n\n<hr>\n\n<p><strong>#region</strong></p>\n\n<p>Remove <code>#region</code>. Instead, consistently structure your classes - private readonly fields, constructors, properties and backing fields, public methods, private methods:</p>\n\n<pre><code>public class Foo\n{\n private readonly Bar _dependency;\n\n public Foo(Bar dependency)\n {\n _dependency = dependency;\n }\n\n public Something FooBar { get; set; }\n\n private Something _barFoo;\n public Something BarFoo\n {\n get { return _barFoo; }\n set { _barFoo = value; }\n }\n\n public void DoSomething()\n {\n }\n\n private void DoSomethingElse()\n {\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Comments</strong></p>\n\n<p>That said, your usage of comments is almost impeccable: the only thing I'd say is, be careful to avoid writing a comment that can eventually turn into a lie:</p>\n\n<blockquote>\n<pre><code>/// &lt;summary&gt;\n/// Default Constructor Initializes a new list of files\n/// and a new byte array set to the max chunk size\n/// &lt;/summary&gt;\n</code></pre>\n</blockquote>\n\n<p>This one is saying <em>what</em> the implementation of the default constructor is doing. If you decide to ever inline the variables' initialization with their declaration (<code>private IList&lt;string&gt; files = new List&lt;string&gt;();</code>), you have a comment to maintain - better avoid that.</p>\n\n<p>Another tiny little thing, is that comments should be properly punctuated - they're all missing a final dot</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T18:56:56.690", "Id": "45003", "ParentId": "44921", "Score": "5" } } ]
{ "AcceptedAnswerId": "45003", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T00:57:44.643", "Id": "44921", "Score": "11", "Tags": [ "c#", "file", "stream" ], "Title": "File transfer over a stream" }
44921
<p>I've created this socket class to use in my web server application. I have two classes: one for the socket and the other for the webserver.</p> <pre><code>//#define WIN32_LEAN_AND_MEAN #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;Winsock2.h&gt; #include &lt;Windows.h&gt; #include &lt;Ws2tcpip.h&gt; #include &lt;stdexcept&gt; #include &lt;stdio.h&gt; #pragma comment(lib,"ws2_32") using namespace std; #define WM_SOCKET 0x10000 class Socket { private: HWND WindowHandle; SOCKET hSocket; short port;//port number string addr; //address WSADATA wsaData; bool vlisten; bool init; bool async; public: Socket() {} Socket(short port, std::string addr, bool vlisten , HWND WindowHandle, bool async); ~Socket() { Close(); } int RecvData(void* buff, int bufferSize){ return recv(hSocket, reinterpret_cast&lt;char*&gt;(buff), bufferSize, 0); } int RecvData(SOCKET S,void* buff,int bufferSize){ return recv(S, reinterpret_cast&lt;char*&gt;(buff), bufferSize, 0); } int SendData(void* buff, int bufferSize){ return send(hSocket,0); } int SendData(SOCKET S,void* buff,int bufferSize) { return send(S, reinterpret_cast&lt;char*&gt;(buff), bufferSize, 0); } bool Connect(short port,std::string addr,bool vlisten,HWND WindowHandle,bool async); //SOCKET Accept(sockaddr* clientInfo,int* clientInfoSize) SOCKET Accept() { static int size = sizeof(sockaddr); return accept(this-&gt;hSocket, 0,0); } SOCKET GetSocket() const{return this-&gt;hSocket;} void Close() { if (hSocket) { shutdown(hSocket,SD_BOTH); closesocket(hSocket); hSocket = 0; } if(init) { WSACleanup(); } } bool Connect(short port,std::string addr,bool vlisten,HWND WindowHandle,WSADATA&amp; wsaData,bool async) { if(!hSocket) { this-&gt;port = port; t this-&gt;wsaData =wsaData; this-&gt;init = true; struct sockaddr_in* sockaddr_ipv4; if(WSAStartup(MAKEWORD(2,2),&amp;wsaData) !=0) { throw runtime_error("Error WSAStartup:" + WSAGetLastError()); } if((this-&gt;hSocket = ::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))== INVALID_SOCKET) { Close(); throw runtime_error("Error init sockect:" + WSAGetLastError()); } if(addr != "INADDR_ANY") { struct addrinfo *result = nullptr; struct addrinfo *it; for (it = result; it != nullptr; it = it-&gt;ai_next) { struct addrinfo *result = nullptr; getaddrinfo(addr.c_str(), nullptr, nullptr, &amp;result); struct addrinfo* it; for (it = result; it != nullptr; it = it-&gt;ai_next) { sockaddr_ipv4 = reinterpret_cast&lt;sockaddr_in*&gt;(it-&gt;ai_addr); addr = inet_ntoa(sockaddr_ipv4-&gt;sin_addr); if (addr != "0.0.0.0") break; } freeaddrinfo(result); } } SOCKADDR_IN sockAddrIn; memset(&amp;sockAddrIn,0,sizeof(sockAddrIn)); sockAddrIn.sin_port = htons(port); sockAddrIn.sin_family = AF_INET; sockAddrIn.sin_addr.s_addr = (addr == "INADDR_ANY" ? htonl(INADDR_ANY) : inet_addr(addr.c_str())); if(vlisten &amp;&amp; (bind(hSocket,reinterpret_cast&lt;SOCKADDR*&gt;(&amp;sockAddrIn),sizeof(sockAddrIn))== SOCKET_ERROR)) { Close(); throw runtime_error("Error vlisten &amp; bind: " + WSAGetLastError()); } if(async &amp;&amp; WindowHandle) { if(WSAAsyncSelect(hSocket,WindowHandle,WM_SOCKET,FD_READ|FD_WRITE|FD_CONNECT|FD_CLOSE|FD_ACCEPT) !=0) { Close(); throw runtime_error("Error async &amp; WindowHandle: " + WSAGetLastError()); } } if(vlisten &amp;&amp; (listen(hSocket,SOMAXCONN)== SOCKET_ERROR)) { Close(); throw runtime_error("Error async &amp; WindowHandle: " + WSAGetLastError()); } if(!vlisten &amp;&amp; (connect(hSocket, reinterpret_cast&lt;SOCKADDR*&gt;(&amp;sockAddrIn), sizeof(sockAddrIn)) == SOCKET_ERROR)) { if(async &amp;&amp; WindowHandle &amp;&amp; (WSAGetLastError() != WSAEWOULDBLOCK)) { Close(); throw runtime_error("Error async &amp; WindowHandle: " + WSAGetLastError()); } } } } void SendLine(string str) { SendData(str,str.size()); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T14:53:44.500", "Id": "78520", "Score": "0", "body": "Don't delete the code from the question, nor edit it, after it has been reviewed: [see this for further details](http://meta.codereview.stackexchange.com/a/1483/34757)." } ]
[ { "body": "<p>You use \"short port\" in several places, but a port number should be an \"unsigned short\".</p>\n\n<p>You're calling Close() all over the place before throwing an exception. It smells like duplicate code. Consider catching the exception then freeing the resources.</p>\n\n<p>Instead of manually freeing resources, consider following the <a href=\"http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization\">RAII</a> pattern. Encapsulate any resource that might leak (In your case WSAStartup() needs to be offset with a call to WSACleanup(), and an open socket needs to be closed.) That way when the resource goes out of scope it cleans itself up, even when the code throws an exception.</p>\n\n<p>Connect() is doing an awful lot of work. It's a long method full of code, and its cyclomatic complexity is very high; my eyeballs put it over 20 (according to <a href=\"http://sourceforge.net/projects/cccc/\">cccc</a> it's 29.) Consider breaking it up. </p>\n\n<p>One way to break it up would be to have two versions of connect: ConnectAndListen() or Connect(). That way you don't have a flag controlling behavior, your client simply calls the version that it needs. </p>\n\n<p>And async and WindowHandle appear to go together like hands and gloves: do you really need the 'async' flag when the existence of a non-null WindowHandle tells it how to behave? That also adds complexity. If you have two versions of Connect() and ConnectAndListen(), one accepting a WindowHandle and one not, you could completely control that behavior without an if statement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T04:17:30.590", "Id": "44931", "ParentId": "44928", "Score": "5" } }, { "body": "<p>Code feedback:</p>\n\n<p>This should not be there:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n</code></pre>\n\n<p>If you really want stdio (normally you shouldn't), you should probably include <code>&lt;cstdio&gt;</code> instead.</p>\n\n<p>This should never be in a header file:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>This should be a static const:</p>\n\n<pre><code>#define WM_SOCKET 0x10000\n</code></pre>\n\n<p>Why do you have these two functions?</p>\n\n<pre><code>int RecvData(SOCKET S,void* buff,int bufferSize) { ... }\nint SendData(SOCKET S,void* buff,int bufferSize) { ... }\n</code></pre>\n\n<p>The methods of the class should work on their own data, not on <code>S</code>.</p>\n\n<p>These should be RAII:</p>\n\n<pre><code>SOCKET hSocket;\nWSADATA wsaData;\n</code></pre>\n\n<p>The calls to <code>Close</code> and <code>throw std::runtime_error</code> should not be repeated. Consider creating an aditional function (<code>Socket::ThrowRuntimeError</code>) that also calls <code>Close</code>, or placing the code in a try-catch and calling <code>Close</code> when catching an exception.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T10:06:32.810", "Id": "44951", "ParentId": "44928", "Score": "5" } } ]
{ "AcceptedAnswerId": "44951", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T02:29:45.733", "Id": "44928", "Score": "5", "Tags": [ "c++", "windows", "socket" ], "Title": "Socket class for use in web server" }
44928
<blockquote> <p>A prime number util, which provides 3 APIs - find the nth prime, find the next prime, and find all primes up to n.</p> </blockquote> <p>I must admit this code has been influenced a lot by discussions <a href="https://codereview.stackexchange.com/questions/38084/suggestions-for-improvement-on-project-euler-7">here</a>. I'm looking for code review, optimizations and best practices.</p> <pre><code>public final class PrimeUtil { private static final boolean COMPOSITE = true; private static final int DEFAULT_SIZE = 100; // cache of primes. public final List&lt;Integer&gt; primes; public int cachedMaxPrime; public PrimeUtil() { primes = new ArrayList&lt;Integer&gt;(); // initial seed primes.addAll(Arrays.asList(2, 3, 5, 7, 11, 13)); cachedMaxPrime = primes.get(primes.size() - 1); } private void validatePositive(int n) { if (n &lt;= 0) { throw new IllegalArgumentException("Expecting a non-zero value"); } } private void validateOutOfBound(int n) { // resulted in int-overflow. if (n &lt;= 0) { throw new IllegalArgumentException("The value is too large to calculate"); } } /** * Find the nth prime. ie if n == 6, then return 13. * * @param n the nth prime * @return the prime at nth position */ public synchronized int getNthPrime(int n) { validatePositive(n); if (n &lt;= primes.size()) { return primes.get(n - 1); } int size = cachedMaxPrime + DEFAULT_SIZE; // adding cachedMaxPrime to DEFAULT_SIZE is a tiny optimization, nothing else. while (primes.size() &lt; n) { validateOutOfBound(size); computePrimesUptoN(size); size += DEFAULT_SIZE; } return primes.get(n - 1); } /** * Given an input prime, return the next prime. * ie, if prime == 13 then return 17, ie 17 is the next prime of 13. * * @param prime the prime number whose next should be found * @return the next prime of the input prime. */ public synchronized int getNextPrime(int prime) { validatePositive(prime); int primeIndex = Collections.binarySearch(primes, prime); if (primeIndex != -1 &amp;&amp; primeIndex != primes.size()) { return primes.get(primeIndex + 1); } int prevSize = primes.size(); int size = cachedMaxPrime + DEFAULT_SIZE; // adding cachedMaxPrime to DEFAULT_SIZE is a tiny optimization, nothing else. while (primes.size() == prevSize) { validateOutOfBound(size); computePrimesUptoN(size); size += DEFAULT_SIZE; } return primes.get(primeIndex + 1); } /** * Given an input n, find all primes from 0 to n * Returns an unmodifiable list. * * @param n the number upto which the primes should be calculated * @return An unmodifiable list. */ public synchronized List&lt;Integer&gt; getPrimesUptoN(int n) { validatePositive(n); validateOutOfBound(n); if (n &lt; cachedMaxPrime) { List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;(); for (int i = 0; primes.get(i) &lt;= n; i++) { list.add(i); } return Collections.unmodifiableList(list); } return Collections.unmodifiableList(computePrimesUptoN(n)); } private List&lt;Integer&gt; computePrimesUptoN(int n) { // composite is name of the sieve, ie nothing else but the sieve. // optimizing the sieve size, but trimming it to "n - cacheprime" boolean[] composites = new boolean[n - cachedMaxPrime]; int root = (int)Math.sqrt(n); // loop through all "first prime upto max-cached-primes" /* * We need i &lt;= root, and NOT i &lt; root * Try cache of {3, 5, 7} and n of 50. you will really why */ for (int i = 0; i &lt; primes.size() &amp;&amp; primes.get(i) &lt;= root; i++) { int prime = primes.get(i); // get the first odd multiple of this prime, greater than max-prime int firstPrimeMultiple = (cachedMaxPrime + prime) - ((cachedMaxPrime + prime) % prime); if (firstPrimeMultiple % 2 == 0) { /* * since we know that no even number other than 2 can be a prime, we only want to consider odd numbers * while filtering. */ firstPrimeMultiple += prime; } filterComposites(composites, prime, firstPrimeMultiple, n); } // loop through all primes in the range of max-cached-primes upto root. for (int prime = cachedMaxPrime + 2; prime &lt; root; prime = prime + 2) { if (!composites[prime]) { // selecting all the prime numbers. filterComposites(composites, prime, prime, n); } } // by doing i + 2, we essentially skip all even numbers // also skip cachedMaxPrime, since quite understandably its already cached. for (int i = 1; i &lt; composites.length; i = i + 2) { if (!composites[i]) { primes.add(i + cachedMaxPrime + 1); } } cachedMaxPrime = primes.get(primes.size() - 1); return primes; } private void filterComposites(boolean[] composites, int prime, int firstMultiple, int n) { // we want to add prime, twice to the multiple so that we only bother to filter odd-numbers. for (int multiple = firstMultiple; multiple &lt; n; multiple += prime + prime) { // eg: assume n = 50, cachemax = 13, and multiple = 15, then 15 should be at composite position of 1. composites[multiple - cachedMaxPrime - 1] = COMPOSITE; } } public static void main(String[] args) { PrimeUtil primeUtil = new PrimeUtil(); List&lt;Integer&gt; primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47); Assert.assertEquals(primes, primeUtil.getPrimesUptoN(50)); primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97); Assert.assertEquals(primes, primeUtil.getPrimesUptoN(100)); Assert.assertEquals(2, primeUtil.getNthPrime(1)); Assert.assertEquals(3, primeUtil.getNextPrime(2)); Assert.assertEquals(13, primeUtil.getNthPrime(6)); Assert.assertEquals(17, primeUtil.getNextPrime(13)); Assert.assertEquals(281, primeUtil.getNthPrime(60)); Assert.assertEquals(283, primeUtil.getNextPrime(281)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T11:17:47.320", "Id": "78261", "Score": "0", "body": "Nice question!!" } ]
[ { "body": "<ol>\n<li><p>You should indicate in the javadoc of the class that it's thread-safe. </p></li>\n<li><p>You should use a private lock object instead of <code>synchronized</code> methods:</p>\n\n<pre><code>private final Object lock = new Object();\n...\npublic synchronized List&lt;Integer&gt; getPrimesUptoN(int n) {\n synchronized (lock) {\n validatePositive(n); \n validateOutOfBound(n);\n ...\n return Collections.unmodifiableList(computePrimesUptoN(n));\n }\n}\n</code></pre>\n\n<p>Consider the following code:</p>\n\n<pre><code>final PrimeUtil primeUtil = new PrimeUtil();\nsynchronized (primeUtil) {\n\n}\n</code></pre>\n\n<p>Anyone can lock on this instance which could lead to poor performance or deadlock.</p>\n\n<p>See also: <em>Effective Java 2nd Edition</em>, <em>Item 70: Document thread safety</em></p></li>\n<li><blockquote>\n<pre><code>private static final int DEFAULT_SIZE = 100;\n</code></pre>\n</blockquote>\n\n<p>I think <code>DEFAULT_LOOK_AHEAD</code> would be more descriptive. <code>DEFAULT_SIZE</code> is a little bit misleading.</p></li>\n<li><p>I'd rename the field to <code>primeCache</code> and remove the comment:</p>\n\n<blockquote>\n<pre><code>// cache of primes.\npublic final List&lt;Integer&gt; primes;\n</code></pre>\n</blockquote>\n\n<p>See <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Don’t Use a Comment When You Can Use a Function or a Variable</em>, p67</p></li>\n<li><blockquote>\n<pre><code>primes = new ArrayList&lt;Integer&gt;();\n</code></pre>\n</blockquote>\n\n<p>You could save a line by putting this on the same line as the declaration:</p>\n\n<pre><code>public final List&lt;Integer&gt; primes = new ArrayList&lt;Integer&gt;();\n</code></pre>\n\n<p>I think it would be a little bit easier to follow.</p></li>\n<li><p>I'd put the validate methods at the end of the file. The are not so important to be the first methods.</p></li>\n<li><blockquote>\n<pre><code>if (primeIndex != -1 &amp;&amp; primeIndex != primes.size()) {\n</code></pre>\n</blockquote>\n\n<p>I'd create a <code>NOT_FOUND</code> constant for <code>-1</code> here for better readability.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:05:00.030", "Id": "79057", "Score": "0", "body": "Small issue with #2. There is no possible way for a deadlock with this class to occur. The class is entirely self contained. They only way there could be a deadlock is if a PrimeUtil instance relied on an another object that, in turn relied on that instance." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T04:48:10.993", "Id": "44933", "ParentId": "44929", "Score": "2" } }, { "body": "<p>The code seems pretty good. I just have a few eclectic comments.</p>\n\n<p>Consider making the class a singleton so that computations can be shared. There may be lock contention issues, though.</p>\n\n<h3>Input Validation</h3>\n\n<ul>\n<li><code>getNextPrime()</code> could be more lenient: why require the parameter to be prime itself? It seems reasonable to ask, \"What is the next prime after 14?\" Also, why require the input to be positive? The next prime after -50 is 2.</li>\n<li><code>validatePositive()</code> and <code>validateOutOfBound()</code> do essentially the same thing, with a slightly different error message. In <code>getPrimesUptoN()</code>, you call both validators. Obviously, the second call is just wasted.</li>\n<li>Why not move the overflow check into <code>computePrimesUptoN()</code> itself, instead of calling <code>validateOutOfBound()</code> all over the code?</li>\n<li>In my judgment, only <code>getNthPrime()</code> and <code>computePrimesUptoN()</code> need to check that they have positive parameters. At that point, you might as well get rid of the validation helper and throw the exception directly. It would also result in a less weird stack trace, since the function that throws the <code>IllegalArgumentException</code> is the one that actually has been passed the illegal argument.</li>\n</ul>\n\n<h3>Prime distribution theory</h3>\n\n<p>You expand the sieve 100 numbers at a time. I think we can do better.</p>\n\n<ul>\n<li>The <em>n</em><sup>th</sup> prime should be approximately <a href=\"http://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number\" rel=\"nofollow\"><em>p</em><sub><em>n</em></sub> ≈ <em>n</em> ln(<em>n</em>)</a>. You can use that estimate in <code>getNthPrime()</code>.</li>\n<li>What's the <a href=\"http://en.wikipedia.org/wiki/Prime_gap\" rel=\"nofollow\">probable gap between successive prime numbers</a>? The average gap is ln(<em>p</em>), so you could take that into consideration instead of blindly expanding by 100 at a time.</li>\n</ul>\n\n<p>Expanding 100 at a time might have better overflow behaviour, though. I haven't thought that through.</p>\n\n<h3>computePrimesUptoN()</h3>\n\n<ul>\n<li><p>Your code doesn't match your comment:</p>\n\n<pre><code>// Try cache of {3, 5, 7}…\nfor (int i = 0; i &lt; primes.size() &amp;&amp; primes.get(i) &lt;= root; i++) {\n …\n}\n</code></pre>\n\n<p>You can start with <code>i = 1</code>, as there is no sense in striking out multiples of 2.</p></li>\n<li><p>The way you arrive at <code>firstPrimeMultiple</code> is clumsy. This expression works:</p>\n\n<pre><code>// get the first odd multiple of this prime, greater than max-prime\nint firstPrimeMultiple = prime * ((cachedMaxPrime / prime + 1) | 1);\n</code></pre>\n\n<p>The <code>| 1</code> at the end rounds up to the next odd multiple.</p></li>\n</ul>\n\n<h3>Recommended tests</h3>\n\n<p>Nice that you have unit tests. I would add a few tests:</p>\n\n<ul>\n<li><code>Assert.assertEquals(Arrays.asList(), primeUtil.getPrimesUptoN(-5));</code> — to check for the more lenient validation</li>\n<li><code>Assert.assertEquals(17, primeUtil.getNextPrime(15));</code> — to check for the more lenient validation</li>\n<li><code>Assert.assertEquals(30529, primeUtil.getNextPrime(30526));</code> — to see what happens with a sudden large expansion of the sieve</li>\n</ul>\n\n<hr>\n\n<p>Sample of changed functions:</p>\n\n<pre><code>public synchronized int getNthPrime(int n) {\n validatePositive(n); \n\n // The nth prime should be approximately n ln(n). Let's overestimate by 20%.\n assert primes.size() &gt;= 5;\n for (int size = (int)(1.2 * n * Math.log(n)); primes.size() &lt; n; size = (int)(1.2 * size)) {\n computePrimesUptoN(size);\n }\n return primes.get(n - 1);\n}\n\n/**\n * Given an input number, return the next prime.\n * ie, if n == 13 or n == 14 then return 17.\n * \n * @param n the number whose next prime number should be found\n * @return the next prime of the input.\n */\npublic synchronized int getNextPrime(int n) {\n if (n &lt; 2) {\n return 2;\n }\n int primeIndex;\n while (Math.abs(primeIndex = Collections.binarySearch(primes, n)) &gt;= primes.size()) {\n int size = Math.max(n, primes.get(primes.size() - 1));\n computePrimesUptoN(size + (int)(1.2 * Math.log(size)));\n }\n return primes.get((primeIndex &lt; 0 ? ~primeIndex : primeIndex + 1));\n}\n\nprivate List&lt;Integer&gt; computePrimesUptoN(int n) {\n if (n &lt;= 0) {\n throw new ArithmeticException(\"Arithmetic overflow\");\n }\n\n // composite is name of the sieve, ie nothing else but the sieve.\n // optimizing the sieve size, but trimming it to \"n - cacheprime\"\n boolean[] composites = new boolean[n - cachedMaxPrime];\n int root = (int)Math.sqrt(n); \n\n // loop through all \"first prime upto max-cached-primes\"\n\n /*\n * We need i &lt;= root, and NOT i &lt; root\n * Try cache of {3, 5, 7} and n of 50. you will really why\n */\n for (int i = 1; i &lt; primes.size() &amp;&amp; primes.get(i) &lt;= root; i++) {\n int prime = primes.get(i);\n\n // get the first odd multiple of this prime, greater than max-prime\n int firstPrimeMultiple = prime * ((cachedMaxPrime / prime + 1) | 1);\n filterComposites(composites, prime, firstPrimeMultiple, n);\n }\n\n // loop through all primes in the range of max-cached-primes upto root.\n for (int prime = cachedMaxPrime + 2; prime &lt; root; prime = prime + 2) {\n if (!composites[prime]) {\n // selecting all the prime numbers.\n filterComposites(composites, prime, prime, n);\n }\n }\n\n // by doing i + 2, we essentially skip all even numbers\n // also skip cachedMaxPrime, since quite understandably its already cached.\n for (int i = 1; i &lt; composites.length; i = i + 2) {\n if (!composites[i]) {\n primes.add(i + cachedMaxPrime + 1);\n }\n }\n\n cachedMaxPrime = primes.get(primes.size() - 1);\n return primes;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T09:11:54.140", "Id": "44947", "ParentId": "44929", "Score": "3" } }, { "body": "<p>In my <a href=\"https://codereview.stackexchange.com/a/44947/9357\">previous answer</a>, I missed two serious bugs, both in this loop in <code>computePrimesUptoN()</code>:</p>\n\n<blockquote>\n<pre><code>// loop through all primes in the range of max-cached-primes upto root.\nfor (int prime = cachedMaxPrime + 2; prime &lt; root; prime = prime + 2) {\n if (!composites[prime]) {\n // selecting all the prime numbers.\n filterComposites(composites, prime, prime, n);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The bugs are:</p>\n\n<ul>\n<li><code>composites</code> should be interpreted with an offset, such that <code>composites[0]</code> represents <code>cachedMaxPrime + 1</code>.</li>\n<li>You should not mark <code>prime</code> itself as being composite.</li>\n</ul>\n\n<p>That loop should be:</p>\n\n<pre><code>// loop through all primes in the range of max-cached-primes upto root.\nfor (int prime = cachedMaxPrime + 2; prime &lt; root; prime = prime + 2) {\n if (!composites[prime - cachedMaxPrime - 1]) {\n // selecting all the prime numbers.\n filterComposites(composites, prime, 3 * prime, n);\n }\n}\n</code></pre>\n\n<p>The reason that your unit tests did not catch these bugs is that that codepath only gets exercised when the sieve is expanded to <code>cachedMaxPrime</code><sup>2</sup>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T18:45:43.540", "Id": "45152", "ParentId": "44929", "Score": "2" } } ]
{ "AcceptedAnswerId": "44947", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T03:51:05.247", "Id": "44929", "Score": "5", "Tags": [ "java", "algorithm", "primes" ], "Title": "Prime number util class" }
44929
<p>Please let me know if I have over/under explained my question :)</p> <p>HTML table row - the numerals from each id attribute, in this example "408" and "409", are the database tables primary ID numbers, one database table row per HTML table cell.</p> <pre><code>&lt;tr&gt; &lt;td id="FieldId408"&gt;&lt;!-- input element --&gt;&lt;/td&gt; &lt;td id="FieldId409"&gt;&lt;!-- input element --&gt;&lt;/td&gt; &lt;td class="actionList"&gt;&lt;a class="deleteTableRow"&gt;Delete&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>jQuery - I push these ids to an array and POST it to ajax.php</p> <pre><code>$('tbody').on('click','.deleteTableRow',function(){ var IDs = []; $(this).closest('tr').find('td').each(function(){ IDs.push(this.id); }); var deleteTableRow = IDs; $(this).parent().parent().remove(); jQuery.ajax({ type: "POST", url: "includes/ajax.php", data: {deleteTableRow: deleteTableRow}, success: function (response) { $('body').append(response); }, error: function (response) { alert("Error getting php file"); } }); }); </code></pre> <p>PHP - ajax.php. This works wonderfully, but <strong>is there a better way to bind a variable number of values into a single prepared statement</strong>? Currently I have HTML tables containing 2 MySql rows or 3 MySql Rows, but this will need to handle around a maximum of 10 MySql rows</p> <pre><code>if(isset($_POST['deleteTableRow'])){ // Remove empty array value generated by the table cell containing my delete button $deleteRowArray = array_filter($_POST['deleteTableRow']); // Create an array of '?,' values - one for each id foreach($deleteRowArray as $addBind) { $array[] = '?,'; } // Remove the last array values comma end($array); $array[key($array)] = '?'; reset($array); // Create the finished query with as many binded values as needed $sql = 'DELETE FROM dataformset WHERE DataFormSetId IN (' . implode($array) .') LIMIT 3'; $q = $db-&gt;prepare($sql); $i = 1; foreach($deleteRowArray as $deleteRow) { // Remove the text "FieldId" and bind each ID into a single prepared statement $deleteRow = preg_replace("/[^0-9,.]/", "", $deleteRow); $q-&gt;bindValue($i, $deleteRow, PDO::PARAM_STR); ++$i; } $q-&gt;execute(); } </code></pre>
[]
[ { "body": "<ol>\n<li><p>For this:</p>\n\n<blockquote>\n<pre><code>// Create an array of '?,' values - one for each id\nforeach($deleteRowArray as $addBind) {\n $array[] = '?,';\n}\n\n// Remove the last array values comma\nend($array);\n$array[key($array)] = '?';\nreset($array);\n\n// Create the finished query with as many binded values as needed\n$sql = 'DELETE FROM dataformset WHERE DataFormSetId IN (' . implode($array) .') LIMIT 3';\n</code></pre>\n</blockquote>\n\n<p>I guess the following is the same but much simpler:</p>\n\n<pre><code>$array = array_fill(0, sizeof($deleteRowArray), \"?\");\n$sql = 'DELETE FROM dataformset WHERE DataFormSetId IN (' . implode(\", \", $array) .') LIMIT 3';\n</code></pre>\n\n<p>You don't need to put the separator char into the array, implode can handle it and it doesn't put separator after the last element, so you don't have to remove it.</p></li>\n<li><blockquote>\n<pre><code>// Remove the text \"FieldId\" and bind each ID into a single prepared statement\n$deleteRow = preg_replace(\"/[^0-9,.]/\", \"\", $deleteRow); \n</code></pre>\n</blockquote>\n\n<p>I'd be a little bit more defensive here and remove only <code>FieldId</code> from the beginning of the string, not every non-allowed character. It's a sign of an error of the caller if you got a <code>$deleteRow</code> which doesn't start with <code>FieldId</code>. In that case you should indicate it somehow (throw an exception). There is no point to delete rows if the data is definitely invalid. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T05:28:50.967", "Id": "78244", "Score": "1", "body": "Exactly what I was looking for! I don't think it could get much simpler than this. Cheers! I have used `$deleteRow = str_replace('FieldId', '', $deleteRow);`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T05:18:55.117", "Id": "44934", "ParentId": "44930", "Score": "2" } } ]
{ "AcceptedAnswerId": "44934", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T04:13:15.240", "Id": "44930", "Score": "5", "Tags": [ "php", "jquery", "mysql", "pdo" ], "Title": "PDO prepared statement - binding variable number of values" }
44930
<p>I need to have an unique ID for any type in C++ for a variant type. Is this code reliable for getting the ID? I don't care to have same ID for same type between multiple runs. Sorry for typos/formatting, I wrote the code on my phone and tested on Ideone.</p> <pre><code>#include &lt;iostream&gt; struct Counter { static size_t value; }; size_t Counter::value = 1; template&lt;typename T&gt; struct TypeID : private Counter { static size_t value() { static size_t value = Counter::value++; return value; } }; int main() { std::cout &lt;&lt; TypeID&lt;int&gt;::value() &lt;&lt; " " &lt;&lt; TypeID&lt;int*&gt;::value() &lt;&lt; " " &lt;&lt; TypeID&lt;Counter&gt;::value() &lt;&lt; " " &lt;&lt; TypeID&lt;int&gt;::value(); return 0; } </code></pre> <p>PS: I use this because <code>std::type_index/std::type_info::hash</code> may have the same value for different types (probably not in practice).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T13:59:55.093", "Id": "435492", "Score": "0", "body": "Use [`type_index`](https://en.cppreference.com/w/cpp/types/type_index/operator_cmp). (Yours is a standard problem with a standard solution from the standard library, which is this one.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-20T19:59:37.533", "Id": "502994", "Score": "0", "body": "@not-a-user it is bound to typeid, therefore can't be used with rtti disabled" } ]
[ { "body": "<p>Re. the algorithm, IMO it looks safe, with only two caveats:</p>\n\n<ul>\n<li><p>I'm not sure that it's thread-safe.</p></li>\n<li><p>It looks safe, because of the \"one-definition rule\". I worried that if multiple source files ('translation units') invoke <code>TypeID&lt;int*&gt;::value()</code> they might each get their own copy of the type; however I think that the \"one-definition rule\" requires the linker to collapse the multiple types into one.\nFurthermore I think that's not just a common good-practice (implemented by some compilers but not others), but is actually required by the standard.\nBut I don't think it will be safe if your program includes multiple DLLs: each DLL is built separately so it would get its own copy of a TypeID instantiation.</p></li>\n</ul>\n\n<p>Re. the code, I don't see why TypeID is a subclass of Counter; it works equally well like this:</p>\n\n<pre><code>template&lt;typename T&gt;\nstruct TypeID // : private Counter\n{\n static size_t value()\n {\n static size_t value = Counter::value++;\n return value;\n }\n};\n</code></pre>\n\n<p>Perhaps you used inheritance to try to protect the Counter value; if so that would be more effective with the protected keyword:</p>\n\n<pre><code>struct Counter\n{\nprotected:\n static size_t value;\n};\n</code></pre>\n\n<p>That's still imperfect (because anyone can subclass Counter). So an all-in-one version would be more fool-proof:</p>\n\n<pre><code>class TypeID\n{\n static size_t counter;\n\npublic:\n template&lt;typename T&gt;\n static size_t value()\n {\n static size_t id = counter++;\n return id;\n }\n};\n</code></pre>\n\n<p>... invoked like this ...</p>\n\n<pre><code>TypeID::value&lt;int&gt;()\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>I think a spinlock + atomics will do the job. Do you think it is enough?</p>\n</blockquote>\n\n<p>I found that for some (but perhaps not all) compilers and compiler options, initialization of statics is thread-safe: for detail, see <a href=\"https://stackoverflow.com/q/1270927/49942\">Are (initializing) function static variables thread-safe in GCC?</a>. In that case, using an atomic <code>Counter::value</code> is sufficient (because the initialization of each instance <code>value</code> is thread-safe).</p>\n\n<p>If such a feature isn't in your compiler, then IMO you need:</p>\n\n<ul>\n<li>a lockguard in the value() method</li>\n<li>and the lockguard must lock an already-constructed lock (perhaps not a separate lock for each T)</li>\n<li>but given a 'global' lockguard, it wouldn't be necessary to also use an atomic <code>Counter::value</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T07:24:09.243", "Id": "78249", "Score": "0", "body": "Thanks! Good catch with thread safety! I will use atomic increment for the value:)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T07:45:46.507", "Id": "78252", "Score": "0", "body": "If it has to be thread-safe then atomic increment isn't enough. Initializing a static variable in a function is implicitly `if (!initialized) id = etc.` and that test for `if (!initialized)` isn't thread-safe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T12:28:24.960", "Id": "78265", "Score": "0", "body": "I think a spinlock + atomics will do the job. Do you think it is enough?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T14:07:09.993", "Id": "78304", "Score": "0", "body": "@Felics I edited my answer to try to reply to your comment." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T07:13:47.730", "Id": "44941", "ParentId": "44936", "Score": "8" } }, { "body": "<p>Here is my lightweight solution that involves no operations at run time:</p>\n\n<pre><code>template&lt;typename T&gt;\nstruct type { static void id() { } };\n\ntemplate&lt;typename T&gt;\nsize_t type_id() { return reinterpret_cast&lt;size_t&gt;(&amp;type&lt;T&gt;::id); }\n\nstruct A { };\n\nint main ()\n{\n cout &lt;&lt; type_id&lt;int&gt;() &lt;&lt; \" \" &lt;&lt; type_id&lt;int*&gt;() &lt;&lt; \" \"\n &lt;&lt; type_id&lt;A&gt;() &lt;&lt; \" \" &lt;&lt; type_id&lt;int&gt;() &lt;&lt; endl;\n}\n</code></pre>\n\n<p>The type id of type <code>T</code> is nothing but the address of function <code>type&lt;T&gt;::id</code>, re-interpreted as a number. Being a static method, there is a unique such function per type. These addresses are assigned by the linker (I think), so they remain constant between different runs. The overhead in executable size is linear in the number of type ids requested (that is, the number of instantiations of <code>type&lt;T&gt;</code>).</p>\n\n<p>This solution has been tested in gcc and clang, and works correctly across different compilation units, i.e. you get the same unique type id for the same type in different compilation units. However, I cannot quite explain why/how this happens.</p>\n\n<p><code>type_id()</code> is easily inlined, so has no run-time cost. However, since it contains <code>reinterpret_cast</code> (and since the function address is not known to the compiler), it cannot be made <code>constexpr</code>. But I don't see this as a problem: if you want to use something e.g. as a template argument, you can use the type directly instead of its id. The id is for run-time use only.</p>\n\n<p>My original implementation is using <code>const void*</code> as the return type of <code>type_id()</code>, so I know it has the same size as any pointer. I adapted it to <code>size_t</code> to fit the question. I think this is still safe, but I can't see why <code>const void*</code> wouldn't be fair enough.</p>\n\n<p>By the way, because I haven't used it very much, I'd be happy to hear if there may be problems with this approach.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T12:40:16.047", "Id": "78515", "Score": "0", "body": "`However, I cannot quite explain why/how this happens.` -- `type<T>::id` is a function (method). Apparently there's a so-called \"one-definition rule\" which requires the linker to ensure there's only one definition of each function. For example, what if the function had a local static variable: there should be only one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T13:12:00.163", "Id": "78516", "Score": "0", "body": "Thanks. I only imagined that but I was never good enough at such issues. For instance, a local static variable needs (exactly) one out of class definition, which is not the case for a function, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T13:43:26.733", "Id": "78518", "Score": "0", "body": "Right. `int foo() { static int count = 0; return count; }` will return a count of the number of times the function has been called. There's only one instance of the function: it only has one address. If foo is a template, declared in a header and instantiated by/into several translation units, the linker needs to remove duplicate instances of it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T17:44:01.557", "Id": "78535", "Score": "0", "body": "@iavr Very smart solution indeed! +1 from me! I will stick with my solution as I can start the counter from a specific larger value and specialize the TypeID for some types to have same ID for those types on all platforms and also be able to use them as indices in vectors(for serialization purpose)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T17:55:13.453", "Id": "78539", "Score": "0", "body": "@Felics Fair enough. With my solution, I think it's straightforward to specialize in order to enforce same id for particular types, but otherwise you have no control on the actual values of the ids. You can only use them with `operator==` for equality comparison." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-28T22:38:39.307", "Id": "261844", "Score": "0", "body": "Your solution gives me over and over the same id/address for any arbitrary type. e.g. type_id<int> equals type_id<float> equals type_id<somerandomstruct>. I observed this behavior with MSVC 2015." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T12:28:04.087", "Id": "379675", "Score": "4", "body": "This solution will not work in VC++ with optimizations enabled due to COMDAT folding. In essence it's a linker optimization where all functions with an identical body will be replaced by a single function. Since `type<T>::id()` is identical for all T, it (and all other empty functions) will be replaced by a single function. This explains the behavior seen by @Julien. https://msdn.microsoft.com/en-us/library/bxwfs976.aspx" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-22T18:21:30.717", "Id": "389643", "Score": "3", "body": "This can be simplified to the following:\n`template<typename T> struct type{static size_t id(){return reinterpret_cast<size_t>(&type<T>::id);}};`" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T11:48:43.183", "Id": "45079", "ParentId": "44936", "Score": "17" } } ]
{ "AcceptedAnswerId": "44941", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T06:17:45.140", "Id": "44936", "Score": "13", "Tags": [ "c++", "c++11", "template-meta-programming" ], "Title": "Unique type ID in C++" }
44936
<p>I want some feedback on the program I developed in C for printing the permutations of a given string.</p> <pre><code>#include &lt;stdio.h&gt; bool isUnique(char x[], int y) { int i, j; for (i = 0; i &lt; (y-1); i++) for (j = i+1; j &lt; y; j++) if (x[i] == x[j]) return false; return true; } void perm(char a[], char b[], int x, int y) { if ((y == x) &amp;&amp; isUnique(b,x)) { b[y] = '\0'; printf("%s\n", b); } else for (int i = 0; i &lt; x; i++) { b[y] = a[i]; if (y &lt; x) perm(a,b,x,y+1); } } int main() { char a[] = {'1','2','3','4'}, b[] = {'\0','\0','\0','\0','\0'}; perm(a,b,4,0); return 0; } </code></pre> <p>Also, please tell me where I'm making blunders as far as conventions and good practice are concerned.</p>
[]
[ { "body": "<ul>\n<li><p>Do not use single-character names for variables. This will make your code harder to understand. Give them names based on their significance to the program.</p></li>\n<li><p>Put your two arrays on separate lines for clarity:</p>\n\n<pre><code>char a[] = {'1','2','3','4'};\nchar b[] = {'\\0','\\0','\\0','\\0','\\0'};\n</code></pre></li>\n<li><p>Arguments to a function that aren't modified within the function should be <code>const</code>.</p>\n\n<p>This applies to <code>a[]</code> in <code>main()</code>:</p>\n\n<pre><code>const char a[] = {'1','2','3','4'};\n</code></pre></li>\n<li><p>Parameters that aren't modified within a function could be <code>const</code> in order to prevent any accidental modifications.</p>\n\n<p>This applies to all parameters in this program <em>except</em> for <code>b[]</code>.</p></li>\n<li><p>Since you declare your <code>for</code> loop counters inside the loop statement, and you're using <code>bool</code>s, then it appears you're using C99.</p>\n\n<p>Two things you should be doing here:</p>\n\n<ol>\n<li><p>Consistently declare your loop counters inside the statements. You're doing it the pre-C99 way in <code>isUnique()</code>.</p></li>\n<li><p>Your code does not compile with the <code>bool</code>s. To use them, you must include <a href=\"https://stackoverflow.com/questions/4767923/c99-boolean-data-type\"><code>&lt;stdbool.h&gt;</code></a>.</p></li>\n</ol></li>\n<li><p>You're inconsistently declaring your loop counters inside and outside the <code>for</code> loop statements. Since you initialize them inside in one instance, you must be using C99. If so, then this should be consistent for each of these loops.</p></li>\n<li><p>In <code>perm()</code>, you should have curly braces for the <code>else</code>, just as you have them for the <code>if</code>. Make sure to maintain such consistencies throughout your program.</p>\n\n<p>You should also do this for the <code>for</code> loops and <code>if</code>s in <code>isUnique()</code>. It is especially important here as it helps with maintenance and will allow you to add additional lines if needed.</p></li>\n<li><p>Functions in C that have no parameters should have a <code>void</code> parameter:</p>\n\n<pre><code>int main(void) {}\n</code></pre></li>\n<li><p>The <code>return 0</code> at the end of <code>main()</code> is unneeded; the compiler will do this automatically.</p></li>\n</ul>\n\n<p>With these changes, I've come up with the following code (also tested on <a href=\"http://ideone.com/sUTPxu\" rel=\"nofollow noreferrer\">Ideone</a>):</p>\n\n<pre><code>#include &lt;stdbool.h&gt;\n#include &lt;stdio.h&gt;\n\nbool isUnique(const char x[], const int y)\n{\n for (int i = 0; i &lt; (y-1); i++)\n {\n for (int j = i+1; j &lt; y; j++)\n {\n if (x[i] == x[j])\n {\n return false;\n }\n }\n }\n\n return true;\n}\n\nvoid perm(const char a[], char b[], const int x, const int y)\n{\n if ((y == x) &amp;&amp; isUnique(b, x))\n {\n b[y] = '\\0';\n printf(\"%s\\n\", b);\n }\n else\n {\n for (int i = 0; i &lt; x; i++)\n {\n b[y] = a[i];\n\n if (y &lt; x)\n {\n perm(a, b, x, y+1);\n }\n }\n }\n}\n\nint main(void)\n{\n const char a[] = { '1', '2', '3', '4' };\n char b[] = { '\\0', '\\0', '\\0', '\\0', '\\0' };\n\n perm(a, b, 4, 0);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T06:51:06.743", "Id": "44940", "ParentId": "44938", "Score": "6" } }, { "body": "<ul>\n<li><p>There is no need to write like:</p>\n\n<pre><code>char a[] = {'1','2','3','4'};\n</code></pre>\n\n<p>You can change it to:</p>\n\n<pre><code>char a[] = {\"1234\"};\n</code></pre></li>\n<li><p>Single character variables makes code harder to understand, so use proper names for variables</p></li>\n<li><p>Use <code>{}</code> for <code>if</code>, <code>else</code>, and <code>for</code> statements, even they have a single statement inside</p></li>\n<li>Actually you can do it without using second array like:</li>\n</ul>\n\n<p></p>\n\n<pre><code>// This function is used for swapping two characters (From the array)\nvoid swapCharacters(char *swappingCharacter, char *swappingCharacter)\n{\n char temp;\n temp = *swappingCharacter;\n *swappingCharacter = *swappingCharacter;\n *swappingCharacter = temp;\n}\n\n\n// Calculated the permutation\nvoid calculatePermutation(char *string, int startIndex, int endIndex)\n{\n int counter;\n if (startIndex == endIndex)\n {\n printf(\"%s\\n\", string);\n }\n else\n {\n for (counter = startIndex; counter &lt;= endIndex; counter++)\n {\n swapCharacters((string + startIndex), (string + counter));\n permute(string, startIndex + 1, endIndex);\n swapCharacters((string + startIndex), (string + counter));\n }\n }\n}\n</code></pre>\n\n<p>And call it as:</p>\n\n<pre><code>calculatePermutation(a, 0, 2);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T03:44:37.977", "Id": "79734", "Score": "1", "body": "Note that `char a[] = {\"1234\"}` (or just `char a[] = \"1234\"`) is not quite the same as the original, as it adds a `\\0` terminator." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T07:21:55.157", "Id": "44942", "ParentId": "44938", "Score": "6" } } ]
{ "AcceptedAnswerId": "44940", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T06:25:29.920", "Id": "44938", "Score": "10", "Tags": [ "c", "strings", "recursion", "combinatorics" ], "Title": "Printing permutations of a given string" }
44938
<blockquote> <p>Construct a matrix with the following property:</p> <ol> <li><p>North-west to South East diagonals are squares.</p> </li> <li><p>Matrix[i][j] + 1 = Matrix[j][i] for each i less than j.</p> </li> </ol> </blockquote> <p>Example of such m a matrix is <a href="https://math.stackexchange.com/questions/720797/whats-the-name-of-this-sort-of-matrix">here</a>. Also, since it appears this matrix does not have a name, I have named my class &quot;Sqaure Diagonal, Transpose Increment&quot;.</p> <p>Looking for code review, best practices, clever optimzations etc.</p> <pre><code>public final class SquareDiagonalTransposeIncrement { private SquareDiagonalTransposeIncrement() {} public static int[][] getSqaureDiagonalTransposeIncrementMatrix (int dimension) { if (dimension &lt; 1) { throw new IllegalArgumentException(&quot;dimension: &quot; + dimension + &quot; should be greater than 0&quot;); } final int[][] m = new int[dimension][dimension]; // set the diagonal for (int i = 0; i &lt; dimension; i++) { m[i][i] = (i + 1) * (i + 1); } /* * Definition of the quadrant. * * - 0th quadrant means a quadrant square matrix from (0,0) to (0,0) * - 1st quadrant means a quadrant square matrix from (0,0) to (1,1) * - 2nd quadrant means a quadrant square matrix from (0,0) to (2,2) * */ for (int quadrant = 0; quadrant &lt; dimension - 1; quadrant++) { besiegeQuadrant(m, quadrant); } return m; } private static void besiegeQuadrant(int[][] m, int quadrant) { int value = m[quadrant][quadrant]; // besiege the quadrant from the eastern and southern boundaries. for (int i = 0; i &lt;= quadrant; i++) { m[i][quadrant + 1] = ++value; // eastern m[quadrant + 1][i] = ++value; // southern } } public static void main(String[] args) { int[][] m = SquareDiagonalTransposeIncrement.getSqaureDiagonalTransposeIncrementMatrix (4); assertArrayEquals(new int[]{ 1, 2, 5, 10}, m[0]); assertArrayEquals(new int[]{ 3, 4, 7, 12}, m[1]); assertArrayEquals(new int[]{ 6, 8, 9, 14}, m[2]); assertArrayEquals(new int[]{11,13,15, 16}, m[3]); } } </code></pre>
[]
[ { "body": "<p>I don't believe that your description uniquely defines the matrix. However, you can fill the upper-right triangle merely by pattern recognition. Starting from the diagonal going up, each column is a sequence descending by 2. From there, just apply the transpose-increment rule.</p>\n\n<pre><code>public static int[][] getSqaureDiagonalTransposeIncrementMatrix(int dim) {\n int[][] m = new int[dim][dim];\n\n // Fill diagonal and upper-right\n for (int row = 0, col = row; row &lt; dim; row = ++col) {\n m[row][col] = (row + 1) * (row + 1);\n for (--row; row &gt;= 0; --row) {\n m[row][col] = m[row + 1][col] - 2;\n }\n }\n // Fill the lower-left using the transpose-increment rule\n for (int row = 0; row &lt; dim; ++row) {\n for (int col = 0; col &lt; row; ++col) {\n m[row][col] = m[col][row] + 1;\n }\n }\n return m;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T10:09:55.523", "Id": "44952", "ParentId": "44939", "Score": "2" } }, { "body": "<p>Throwing a different spin on the process, I think you are missing an alternate algorithm that produces the same result....</p>\n\n<p>Here is a 'simple' loop that 'works'. It works because it uses a different 'rule' that is based on the pattern that your matrix creates.</p>\n\n<p>The Pattern is obvious when you study the matrix from the bottom-right corner, and work backwards. The initial value is the square of the matrix size. Then you subtract 1 to the left, then another 1 above, and another 1 to the next left, and another 1 to the next above, etc.</p>\n\n<pre><code>private static final int[][] buildMagicMatrix(int size) {\n int value = size * size + 1;\n int[][] matrix = new int[size][size];\n for (int i = size - 1; i &gt;= 0; i--) {\n matrix[i][i] = --value;\n for (int d = i - 1; d &gt;= 0; d--) {\n matrix[i][d] = --value;\n matrix[d][i] = --value;\n }\n }\n return matrix;\n}\n</code></pre>\n\n<p>Using this algorithm you produce results like:</p>\n\n<blockquote>\n<pre><code>Size 9\n 1 2 5 10 17 26 37 50 65\n 3 4 7 12 19 28 39 52 67\n 6 8 9 14 21 30 41 54 69\n 11 13 15 16 23 32 43 56 71\n 18 20 22 24 25 34 45 58 73\n 27 29 31 33 35 36 47 60 75\n 38 40 42 44 46 48 49 62 77\n 51 53 55 57 59 61 63 64 79\n 66 68 70 72 74 76 78 80 81\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T11:54:03.050", "Id": "44953", "ParentId": "44939", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T06:43:00.687", "Id": "44939", "Score": "2", "Tags": [ "java", "matrix" ], "Title": "A matrix with square diagonals and transpose being increments of other" }
44939
<p>I have settled with this type of structuring of unit tests.</p> <p>Basic idea is that there is a base test class for the tested class, and a subclass for every tested method. They use the mocks and everything from the base test class, the point being that the test would remain small, and you don't have to create everything in the test.</p> <p>Idea for this came from Haacked <a href="http://haacked.com/archive/2012/01/02/structuring-unit-tests.aspx/" rel="nofollow">http://haacked.com/archive/2012/01/02/structuring-unit-tests.aspx/</a></p> <pre><code>public class HomeControllerTest { protected HomeController Controller; protected Mock&lt;IUnitOfWork&gt; UnitOfWork; protected Mock&lt;IRepositoryOne&lt;Entity&gt;&gt; Repository; protected Fixture Fixture; public HomeControllerTest() { UnitOfWork = new Mock&lt;IUnitOfWork&gt;(); Repository = new Mock&lt;IRepositoryOne&lt;LoanRequirement&gt;&gt;(); Controller = new HomeController( UnitOfWork.Object, Repository.Object); Fixture = new Fixture(); } public class GetHomeMethod : HomeControllerTest { [Fact] public void ReturnsEntityDataFromDatabase() { Repository.Setup(x =&gt; x.GetId(1)).Returns(new Entity()); var result = Controller.GetOne(1) as OkNegotiatedContentResult&lt;HomeModel&gt;; Assert.NotNull(result); var model = result.Content; var entityToModel = Mapper.Map&lt;HomeModel&gt;(entity); Assert.Equal(model, entityToModel,HomeModel.HomeModelComparer); } } public class PostHomeMethod : HomeControllerTest { // Test the post method } public class PutHomeMethod : HomeControllerTest { // Test the put method } } </code></pre> <p>I ask in general is there anything wrong about doing it like this, any dangers that I don't spot? Any comments are welcome. Main point for asking a question like this is to polish my unit tests, so they would be even more organized.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T08:34:06.133", "Id": "78253", "Score": "1", "body": "http://codereview.stackexchange.com/a/44879/7076" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T12:47:08.393", "Id": "78283", "Score": "1", "body": "And then you'll end up with 100 classes that test one thing. What does this offer as an advantage over a simple setup method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T06:56:50.877", "Id": "78707", "Score": "0", "body": "What do you mean test only one thing? One class testes one method, usually there is more tests per method than one. This gives you more structured tests, like descried in the post." } ]
[ { "body": "<p>There are a few major differences between what I understand from your code and what I understand from the post you mention.</p>\n\n<p><strong>Inheritance vs Nesting</strong><br>\nYour code suggests that there is a <em>subclass</em> for each tested method, although the post talks about <em>nested classes</em>:</p>\n\n<blockquote>\n <p>The structure has a test class per class being tested. That’s not so\n unusual. But what was unusual to me was that he had a nested class for\n each method being tested.</p>\n</blockquote>\n\n<p><strong>Class per test vs Class per Method</strong><br>\nAlso, your code example implies that each class contains a single test, which loses all meaning for the class. The post talks about a class per <em>method tested</em>, which mean that it may contain more than one test, but all tests are relevant to the same method.</p>\n\n<blockquote>\n<pre><code>using Xunit;\n\npublic class TitleizerFacts\n{\n public class TheTitleizerMethod\n {\n [Fact]\n public void ReturnsDefaultTitleForNullName()\n {\n // Test code\n }\n\n [Fact]\n public void AppendsTitleToName()\n {\n // Test code\n }\n }\n</code></pre>\n</blockquote>\n\n<p>This kind of structure is very similar to how an <a href=\"http://rspec.info/\" rel=\"nofollow\"><code>RSpec</code></a> test would be structured, having multiple layers of <code>describe</code> blocks for different scopes - class, method, feature...</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>describe HomeController do\n\n let (:fixture) { double('fixture') }\n\n before(:each) do\n # something before each test\n end\n\n describe '#get_home' do\n\n before(:each) do\n expect(repository).to receive(:get_id).with(1).and_return(entity)\n end\n\n let(:result) { subject.GetOne(1) }\n\n it 'returns result' do\n expect(result).to_not be_nil\n end \n\n it 'returns entity data from database' do\n expect(result.content).to eq entity\n end\n end\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T14:47:11.353", "Id": "44977", "ParentId": "44945", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T08:07:55.587", "Id": "44945", "Score": "1", "Tags": [ "c#", "unit-testing" ], "Title": "Structuring unit tests" }
44945
<p>This is a simple load more plugin, built for teaching purposes. For this reason, it's not pretty in terms of output.</p> <p>I'd like to know if this can be improved, or if anyone can spot any major problems with this. The one thing I'm concerned about is the 'templating', whereby it gets the template from the initial markup and duplicates it.</p> <p><strong>loadmore.js</strong></p> <pre><code>/*jslint unparam: true, white: true */ (function($) { "use strict"; $.fn.loadmore = function(options) { var self = this, settings = $.extend({ source: '', step: 2 }, options), stepped = 1, item = self.find('.item'), finished = function() { self.find('.items-load').remove(); }, append = function(value) { var name, part; item.remove(); for(name in value) { if(value.hasOwnProperty(name)) { part = item.find('*[data-field="' + name + '"]'); if(part.length) { part.text(value[name]); } } } item.clone().appendTo(self.find('.items')); }, load = function(start, count) { $.ajax({ url: settings.source, type: 'get', dataType: 'json', data: {start: start, count: count}, success: function(data) { var items = data.items; if(items.length) { $(items).each(function(index, value) { append(value); }); stepped = stepped + count; } if(data.last === true) { finished(); } } }); }; if(settings.source.length) { // Event handler for load more button self.find('.items-load').on('click', function() { load(stepped, settings.step); return false; }); load(1, settings.step); } else { console.log('Source required for loadmore.'); } }; }(jQuery)); </code></pre> <p><strong>Example usage</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Load more&lt;/title&gt; &lt;meta charset="UTF-8"&gt; &lt;/head&gt; &lt;body&gt; &lt;h4&gt;Articles&lt;/h4&gt; &lt;div class="articles"&gt; &lt;div class="items"&gt; &lt;div class="item"&gt; &lt;h3&gt;&lt;span data-field="title"&gt;&lt;/span&gt; (&lt;span data-field="id"&gt;&lt;/span&gt;)&lt;/h3&gt; &lt;p data-field="description"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;a href="#" class="items-load"&gt;Load more&lt;/a&gt; &lt;/div&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="js/loadmore.js"&gt;&lt;/script&gt; &lt;script&gt; $('.articles').loadmore({ source: 'articles.php', step: 2 }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Example JSON generated with PHP</strong></p> <pre><code>&lt;?php header('Content-Type: application/json'); $pdo = new PDO("mysql:host=127.0.0.1;dbname=loadmore", "root", ""); $articles = []; $start = isset($_GET['start']) ? (int)$_GET['start'] - 1 : 0; $count = isset($_GET['count']) ? (int)$_GET['count'] : 1; $article = $pdo-&gt;query("SELECT SQL_CALC_FOUND_ROWS * FROM articles LIMIT {$start}, {$count}"); $articlesTotal = $pdo-&gt;query("SELECT FOUND_ROWS() as count")-&gt;fetch(PDO::FETCH_ASSOC)['count']; if($articlesCount = $article-&gt;rowCount()) { $articles = $article-&gt;fetchAll(PDO::FETCH_OBJ); } echo json_encode(array( 'items' =&gt; $articles, 'last' =&gt; ($start + $count) &gt;= $articlesTotal ? true : false, 'start' =&gt; $start, 'count' =&gt; $count )); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-08T05:02:53.523", "Id": "245042", "Score": "0", "body": "May be you help jquery plugin http://makenskiy.com/demo/jquery.spoiler-list/documentation/index_eng.html" } ]
[ { "body": "<p>From some staring at your code</p>\n\n<ul>\n<li>There are no comments, at all</li>\n<li>You <code>$.ajax({</code> call should handle failure by implementing <code>error</code></li>\n<li><p>The <code>items</code> treatment in <code>success</code> seems little clumsy, first I would not put the function inside the ajax call, secondly I would probably go with something like this:</p>\n\n<pre><code>success: function(data) {\n\n $(data.items).each(function(index, value) {\n append(value);\n });\n if(data.last === true) {\n finished();\n }\n}\n</code></pre></li>\n<li>I do not understand the value of <code>stepped</code>, what does it bring to your plugin ? It would have been far better to keep the stepping logic out of the plugin, and let the caller pass a <code>data</code> object that will be passed to the ajax call.</li>\n<li><code>'.items-load'</code> is a magic, repeated constant, you should use a properly named variable</li>\n<li><code>item.find('*[data-field=\"' + name + '\"]');</code> &lt;- I don't like this, why would you not simply search by <code>id</code>, it performs better, and it is more standard. </li>\n<li><code>\"use strict\";</code> on the top level, good stuff</li>\n<li>Passes perfectly on JsHint.com</li>\n<li><code>if(value.hasOwnProperty(name)) {</code> &lt;- good defensive coding</li>\n<li><p>jQuery handles empty/undefined gracefully, so that you can write nicer code, this:</p>\n\n<pre><code>part = item.find('*[data-field=\"' + name + '\"]');\n\nif(part.length) {\n part.text(value[name]);\n}\n</code></pre>\n\n<p>could be this:</p>\n\n<pre><code>item.find('#'+name).text(value[name]);\n</code></pre></li>\n<li><p>The CSS names you use are very generic, you might want to consider adding a small prefix to avoid name clashes</p></li>\n<li><code>loadmore</code> -> <code>loadMore</code> because lowerCamelCase</li>\n<li><code>console.log</code> in production is a no-no</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-03T17:47:58.123", "Id": "46208", "ParentId": "44948", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T09:29:04.807", "Id": "44948", "Score": "5", "Tags": [ "javascript", "php", "jquery", "reinventing-the-wheel" ], "Title": "jQuery Load More Plugin" }
44948
<p>I want to get some best practices and code corrections.</p> <p><strong>JS</strong></p> <pre><code>function clock(){ var currentTime = new Date() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() var seconds = currentTime.getSeconds() var timeOfDay = ( hours &lt; 12 ) ? "AM" : "PM"; hours = ( hours &gt; 12 ) ? hours - 12 : hours; hours = ( hours === 0 ) ? 12 : hours; minutes = ( minutes &lt; 10 ? "0" : "" ) + minutes; seconds = ( seconds &lt; 10 ? "0" : "" ) + seconds; var place = (hours + ":" + minutes + ":" + seconds + timeOfDay); document.getElementById('clock').innerHTML = place; setTimeout(clock,1000); }; clock(); </code></pre> <p><strong>CSS</strong></p> <pre><code>#clock { font-family:arial,helvetica; background:#FFF; box-shadow:3px 3px 5px 6px #ccc; width:86px; -webkit-box-shadow: 0 10px 6px -6px #777; -moz-box-shadow: 0 10px 6px -6px #777; box-shadow: 0 10px 6px -6px #777; } </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div id="clock"&gt;Time&lt;/div&gt; </code></pre>
[]
[ { "body": "<p>initial findings:</p>\n\n<p>You aren't using the <code>init</code> function, so why keep it. Whatever code you don't need: get rid of it.<br>\nYour <code>clock</code> function calls itself sort-of recursively with a 1 second interval, due to your using the <code>setTimeout</code> function.<Br>\nYou could easily avoid calling <code>setTimout</code> every time by simply changing that to <code>setInterval</code>:</p>\n\n<pre><code>function clock()\n{\n //code here\n}\nvar clockInterval = setInterval(clock, 1000);\n</code></pre>\n\n<p>The result of this is that, through the return value of <code>setInterval</code> (which is the interval's ID) you can stop the code from running whenever you need to:</p>\n\n<pre><code>//some event handler, for example a pauseBtn.addEventListener('click'...)\nclearInterval(clockInterval);\n</code></pre>\n\n<p>which makes gives you more flexibility, and will make things easier when you want to debug or indeed add functionality later on.<br>\nThe same can be done with an timeout, of course:</p>\n\n<pre><code>var tId = setTimeout(function()\n{\n console.log('~5 seconds have passed');\n}, 5000);\nclearTimeout(tId);//the callback won't ever be called, unless for some reason this statement takes more than 5 seconds to reach.\n</code></pre>\n\n<p>However, an interval's ID is the same throughout. If you decide to use <code>setTimeout</code>, you'll have to re-assign the return value of every <code>setTimout</code> call to the same variable, simply because each timeout can, and most likely will, have a new ID. For that reason alone I think <code>setInterval</code> is the better choice in your case.</p>\n\n<p>in the function, you have this: <code>document.getElementById('clock')</code> DOM lookup that queries the DOM for the same element over and over again. The DOM API is what it is: clunky and slow, so wherever you can, saving on DOM queries is a good thing. The element in question is, as far as your function is concerned pretty much a constant, is it not?<br>\nWhy not use a closure, so you can query the DOM once, and use the same reference over and over? Something like this:</p>\n\n<pre><code>var clock = (function(clockNode)\n{//clockNode will remain in scope, and won't be GC'ed\n return function()\n {//the actual clock function\n //replace document.getElementById('clock') with\n clockNode.innerHTML = place;\n };\n}(document.getElementById('clock')));//pass DOM reference here\nvar clockInterval = setInterval(clock, 1000);\n</code></pre>\n\n<p>However, it's worth noting that <code>innerHTML</code> is <a href=\"http://snook.ca/archives/javascript/whats_wrong_wit\" rel=\"nofollow\">quite slow, looks dated and is non-standard</a>. The <em>\"correct\"</em> way of doing things would be:</p>\n\n<pre><code>clockNode.replaceChild(document.createTextNode(place), clockNode.childNodes.item(0));\n</code></pre>\n\n<p>Which, admittedly looks a tad more verbose and over-complicates things, but just thought you'd like to know.</p>\n\n<p>Speaking of over-complicating things, and as phyrfox rightfully pointed out, you're essentially building a <em>locale time string</em> from the <code>Date</code> instance. You are re-inventing the wheel, considering the <code>Date</code> object comes with a ready-made method for just such a thing: <code>toLocaleTimeString</code>. This dramatically simplifies our code:</p>\n\n<pre><code>clockNode.replaceChild(\n document.createTextNode((new Date()).toLocateTimeString()),\n clockNode.childNodes.item(0)\n);\n</code></pre>\n\n<p>That's all you need!</p>\n\n<h1><a href=\"http://jsfiddle.net/4B9H5/2/\" rel=\"nofollow\">here's a fiddle</a></h1>\n\n<p>Oh, and remember how I said that the interval ID returned by <code>setInterval</code> can be a useful thing to have?</p>\n\n<h1>Here's <a href=\"http://jsfiddle.net/chZzS/1/\" rel=\"nofollow\">another fiddle</a> that illustrates that point</h1>\n\n<p>The code you have can, therefore be re-written to be more standard-compliant <em>and</em> at the same time be made shorter. What you end up with is simply this:</p>\n\n<pre><code>var clock = (function (clockNode)\n{\n return function()\n {\n clockNode.replaceChild(\n document.createTextNode(\n (new Date).toLocaleTimeString()\n ),\n clockNode.childNodes.item(0)\n );\n };\n}(document.getElementById('clock')));\nvar clockInterval = setInterval(clock, 1000);\n</code></pre>\n\n<p><strong>Conventions</strong><br>\nYes, semi-colons are optional in JS, but it is considered a good habit to write them nonetheless. That's an easy convention to follow, and it'll help you when you decide to learn, or have to switch to, other languages. Many of which see the semi-colon as being <em>non</em> optional.<Br>\nIt's a bit of a hang-up of mine, I admit, but try to adhere to the conventions as much as possible, like: avoiding too many <code>var</code> declarations in a block of code. You can easily compact them into a single statement, using a comma:</p>\n\n<pre><code>var currentTime = new Date(),\n hours = currentTime.getHours(),\n minutes = currentTime.getMinutes(),\n seconds = currentTime.getSeconds(),\n timeOfDay = ( hours &lt; 12 ) ? \"AM\" : \"PM\";\n</code></pre>\n\n<p>You can do away with the temp var <code>place</code> all together, and can even move the var declarations to the IIFE which we've used to store the <code>clockNode</code> DOM reference in:</p>\n\n<pre><code>var clock = function(clockNode)\n{\n var currentTime, hours, minutes, seconds, timeOfDay;\n return function(){};\n}());\n</code></pre>\n\n<p>Pass your code through the rather pedantic <a href=\"http://jslint.org\" rel=\"nofollow\">JSLint</a> tool never hurts.</p>\n\n<p>It'll probably complain about your keenness on using the ternary operator, too, because, though I'm not particularly opposed to the odd ternary, you do seem to be using it an awful lot.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T12:18:09.180", "Id": "44957", "ParentId": "44955", "Score": "12" } }, { "body": "<p>Your clock is going to be between 0 and 1 seconds behind local system time, since your function isn't fixed to fire at the turn of the second. Once in a while a second will be missed entirely due to a small delay beyond the 1000 ms, contrary to popular belief <code>setInterval</code> show a similar delay in most browsers, you never get exactly the time you ask for.</p>\n\n<pre><code>setTimeout(clock,1000-currentTime%1000);\n</code></pre>\n\n<p>Will to the best of the browsers timekeeping ability fire at the turn of the second, if the function is fired early (which does happen in some versions of some browsers), it will schedule for being fired again at the correct time, and when it is fired slightly late it will compensate.</p>\n\n<p>That is all there is to say about the functionality.</p>\n\n<p>You are not using the <code>init</code> function, so why is it there? If you were using it it would create the global <code>timeDisplay</code>, which seem to be intended to be a private variable of the function.</p>\n\n<p>You have <code>box-shadow</code> twice in your CSS and your use of semicolons and whitespace is inconsistent.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T05:03:53.407", "Id": "78470", "Score": "0", "body": "Thre is an error on the `setTimeout(clock,1000-currentTime%1000);`. The error is: `Uncaught ReferenceError: currentTime is not defined `" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T08:50:58.267", "Id": "78486", "Score": "0", "body": "@jakobaindreas_11 It has to be placed within the `clock` function, replacing `setTimeout(clock,1000);`. That is where you have `currentTime` defined." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T21:50:11.873", "Id": "45030", "ParentId": "44955", "Score": "1" } } ]
{ "AcceptedAnswerId": "44957", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T12:03:44.927", "Id": "44955", "Score": "7", "Tags": [ "javascript", "datetime" ], "Title": "JS Clock widget" }
44955
<p>Is better to use <code>$id_name ( Class A Method b() )</code> OR <code>$id_name_2 ( Class A Method c())</code>?</p> <pre><code>&lt;?php Class A { function a(){ $params = array( 'id'=&gt; 1, 'name' =&gt; 'b', ); $id_name = $this-&gt;b($params); $id_name_2 = $this-&gt;c($params); } function b($params){ $id = $params['id']; $name = $params['name']; /******* Some code performing operations with $name and $id ********/ $str = $id . $name; return $str; } function c($params){ /******* Some code performing operations with $params['name'] and $params['id'] ********/ $str = $params['name'] . $params['id']; return $str; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T02:42:34.633", "Id": "79284", "Score": "0", "body": "Is `$params` being used at all inside of the \"Code Performing Operations?\" If not, both methods are nearly identical." } ]
[ { "body": "<p>You want to be using method B. It will make for more readable code and will lead to less mystery bugs.</p>\n\n<p>One cool PHP trick for extracting an assosiative array into variables is the <a href=\"http://www.php.net/extract\" rel=\"nofollow\">Extract</a> method.</p>\n\n<pre><code>$params = array(\n 'id' =&gt; 1,\n 'name' =&gt; 'foo'\n);\n\nextract($params);\n\necho $name . $id;\n//\"Foo1\"\n</code></pre>\n\n<p>This makes more sense when you've got more elements, but I've always found it to be a clean way to express what you're trying to do.</p>\n\n<p>The reverse is <a href=\"http://www.php.net/compact\" rel=\"nofollow\">Compact</a> which is great if you need to convert your values back to their original array form. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T12:38:15.707", "Id": "78275", "Score": "1", "body": "My experience is that using `extract` can be a bit dangerous unless you are really sure of what you are doing and what the contents of the array are. Consider the fact that the old register_globals setting were doing an extract of `$_POST`, `$_GET` and others... and register_globals was one of the most horrible security leaks of PHP ever." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T12:47:40.490", "Id": "78284", "Score": "0", "body": "I'm always sure what I'm doing ;) But you are definitely correct. I've always used extract on some kind of data model I wanted to operate on that had tons of properties. The arrays themselves were returned through class methods that I either wrote or thoroughly understood, so the safety was there. If you don't have this consistency with your input arrays, it will be safer to just assign them manually." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T12:34:22.027", "Id": "44960", "ParentId": "44956", "Score": "0" } }, { "body": "<p>Using method <code>c</code> will have an side-effect if <code>$params</code> is modified. This is because arrays are passed by reference, and so any changes to <code>$params</code> will be visible to the caller when the function returns. Use <code>b</code> if you need to manipulate id or name, unless you intend to return the modifications to the caller.</p>\n\n<p>Example:</p>\n\n<pre><code>$params = array('id' =&gt; 1, 'name' =&gt; 'b');\n$this-&gt;d($params);\necho $params['id']; // outputs 2\n...\n\nfunction d($params) {\n $params['id']++;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T12:35:19.663", "Id": "44961", "ParentId": "44956", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T12:16:08.073", "Id": "44956", "Score": "1", "Tags": [ "php" ], "Title": "Practice extracting variables" }
44956
<p>I have a PL/SQL stored procedure which searches for a row in 3 different tables (not all columns are the same).</p> <p>The logic goes as follows:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Search for the item in the first table If item was found select the details of it from the first table If item was not found search for the item in the second table If Item was found Select the details of it from the second table If item was not found Select the item from the third table (returning blank if it's not found here neither) </code></pre> </blockquote> <p>Here's the actual code (actual symbol names modified for security):</p> <pre class="lang-sql prettyprint-override"><code>PROCEDURE GETREQUEST(REQUESTID IN NUMBER, request OUT pkg_request.refcur) IS requestFound NUMBER := 0; BEGIN -- Search for the request ID in the first table SELECT COUNT(REQ_ID) INTO requestFound FROM FIRSTTABLE WHERE FIRSTTABLE.REQ_ID = REQUESTID AND (REQ_STATUS = 'D' OR REQ_STATUS = 'A'); IF(REQUESTFOUND &gt; 0) THEN -- Select the request details OPEN REQUEST FOR SELECT REQ_ID, REQ_TYPE_STATUS FROM FIRSTTABLE WHERE FIRSTTABLE.REQ_ID = REQUESTID AND (REQ_STATUS = 'D' OR REQ_STATUS = 'A'); ELSE -- Search for the request from the second table SELECT COUNT(REQ_ID) INTO REQUESTFOUND FROM SECONDTABLE WHERE SECONDTABLE.REQ_ID = REQUESTID; IF(REQUESTFOUND &gt; 0) THEN -- Select the request details from second table OPEN REQUEST FOR SELECT REQ_TYPE, '-' AS REQ_TYPE_STATUS FROM SECONDTABLE WHERE SECONDTABLE.REQ_ID = REQUESTID; ELSE -- Get the request from third table (will return as blank if nothing found) OPEN REQUEST FOR SELECT REQ_TYPE, '-' AS REQ_TYPE_STATUS FROM THIRDTABLE WHERE THIRDTABLE.REQ_ID = REQUESTID; END IF; END IF; END GET_REQUEST </code></pre> <p>My issues with this are as follows: </p> <ul> <li>It's not very concise, with a lot of nesting.</li> <li>It's not very efficient, since it needs to perform a count, then if it exists it selects the details. That's two operations. How can I modify it to have a single operation for each search?</li> </ul> <p>Also, the <code>REQ_TYPE_STATUS</code> column doesn't exist in the second and third table, so as you can see I have just assigned the value '-' to the returned result, indicating a blank value. I'm not really sure if there's a better or more standard way of doing this.</p>
[]
[ { "body": "<p>I am not sure there is a way to reduce the number of if-statements and nesting. What is possible though is to improve the performance of the conditions you have that check those conditions.</p>\n\n<p>The count(*) is inefficient. Consider adding a 'ROWNUM = 1' condition to your where clause in a way that makes the following conditions possible:</p>\n\n<pre><code> SELECT COUNT(REQ_ID) INTO requestFound\n FROM FIRSTTABLE\n WHERE FIRSTTABLE.REQ_ID = REQUESTID\n AND (REQ_STATUS = 'D' OR REQ_STATUS = 'A')\n AND ROWNUM = 1;\n</code></pre>\n\n<p>This will be optimized by Oracle to exit the condition on the first matching result, ending up with a <code>requestFound</code> value that will be either 0, or 1. A value of 1 means there is some data, and does not indicate how much data.</p>\n\n<p><a href=\"http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html\" rel=\"nofollow\">Reading up on ROWNUM is useful. Ask Tom!</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T13:06:02.703", "Id": "44967", "ParentId": "44963", "Score": "4" } }, { "body": "<p>I'm afraid you current solution is a prime example of inappropriate use of PL/SQL when plain SQL provides much more elegant solution:</p>\n\n<pre><code>create table t1 (\n id number,\n status varchar2(10)\n);\n\ncreate table t2 (\n id number\n);\n\ncreate table t3 (\n id number\n);\n\ninsert into t1 values(1,'A');\ninsert into t2 values(2);\ninsert into t3 values(3);\ninsert into t1 values(4,'A');\ninsert into t2 values(4);\ninsert into t3 values(4);\n\nselect source, priority, id, status from (\n select 't1' as source, 1 as priority, id, status from t1 where status in ('A', 'D')\n union\n select 't2' as source, 2, id, null from t2\n union\n select 't3' as source, 3, id, null from t3\n)\nwhere id = 1\norder by priority\n;\n</code></pre>\n\n<p>The <code>source</code> is just for demonstration and <code>priority</code> is to guarantee the correct ordering of the tables. The <code>priority</code> is not needed if you have other rules ensuring the id is found only from one table. If the id can be found from different tables just add a wrapper <code>rownum = 1</code>-query (the details left for exercise) to pick the first one only. Now just wrap that inside your PL/SQL as you see appropriate.</p>\n\n<p>When some information is not available in all tables it's up to you what is the value indicating missing value. It can be e.g. <code>null</code> or <code>-</code> or <code>-1</code> depending on the context. However I'd recommend <code>null</code> unless there is other factors that rule that out.</p>\n\n<p>Hope this helps !</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:31:35.427", "Id": "78723", "Score": "0", "body": "Brilliant work, this is a much shorter and simpler solution!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T19:05:24.950", "Id": "45005", "ParentId": "44963", "Score": "4" } } ]
{ "AcceptedAnswerId": "45005", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T12:46:28.560", "Id": "44963", "Score": "3", "Tags": [ "sql", "oracle", "stored-procedure", "plsql" ], "Title": "Searching through tables for a value" }
44963
<p>I have a server side PHP file which processes Ajax requests from the client browser. Some requests are only valid if they originate from an Administrator in the application, others are only valid if they originate from a Manager in the application, and the rest are valid if any system user makes the request.</p> <p>I covered all the user authentication code above this snippet and and am quite happy with the way it turned out. When I got to the request processing part I came up with the following:</p> <p><strong>Ajax Request Processing in PHP:</strong></p> <pre><code> $user = User::load($_COOKIE['login']); $requestData = json_decode($_POST['json']); switch($requestData-&gt;requestType) { case 'CreateUser': if(!$user-&gt;isAdmin()) die('Unauthorized Request'); else createUser($requestData); break; case 'DeleteUser': if(!$user-&gt;isAdmin()) die('Unauthorized Request'); else deleteUser($requestData); break; case 'PasswordReset': if(!$user-&gt;isAdmin()) die('Unauthorized Request'); else passwordReset($requestData); break; case 'ChangeTitle': if(!$user-&gt;isAdmin()) die('Unauthorized Request'); else changeTitle($requestData); break; case 'ChangeWorkStatus': if(!$user-&gt;isAdmin()) die('Unauthorized Request'); else changeWorkStatus($requestData); break; case 'ChangeVacationDays': if(!$user-&gt;isAdmin()) die('Unauthorized Request'); else changeVacationDays($requestData); break; case 'AddToSchedule': if(!$user-&gt;isManager()) die('Unauthorized Request'); else addToSchedule($requestData); break; case 'RemoveFromSchedule': if(!$user-&gt;isManager()) die('Unauthorized Request'); else removefromSchedule($requestData); break; case 'UserAvailability': if(!$user-&gt;isManager()) die('Unauthorized Request'); else getUserAvailability($requestData); break; case 'UserInfo': getUserInfo($requestData); break; case 'UserPhone': getPhoneNumbers($requestData); break; case 'AddPhone': addPhoneNumber($requestData); break; case 'PhonePriority': phonePriority($requestData); break; case 'RemovePhone': removePhoneNumber($requestData); break; case 'UserEmail': getEmails($requestData); break; case 'AddEmail': addEmail($requestData); break; case 'EmailPriority': emailPriority($requestData); break; case 'RemoveEmail': removeEmail($requestData); break; case 'UserList': userList($requestData); break; default: die('Invalid Request Specification'); } </code></pre> <p>I don't want to re-instantiate <code>$user</code> inside each method of the <code>switch</code> statement to check if <code>$user</code> is of the correct type because the instantiation is expensive (database access) and aside from checking the <code>$user</code> type, the <code>$user</code> would be unnecessary to <em>"do the thing"</em>.</p> <p>I also don't want to pass the <code>$user</code> into the function because again, the <code>$user</code> would be unused except for type checking. Hence having <code>$user</code> in the method signature would be "incorrect".</p> <p>Lastly, to keep things at a single level of abstraction, I think the validation of the user should be done outside of the method calls, because the methods <em>"do the thing"</em>, not <em>"validate if the user can do the thing"</em> <strong><em>and</em></strong> <em>"do the thing"</em>.</p> <p>I'm pretty convinced that the <code>$user</code> type validation and the request processing should be done on this level of abstraction, yet I don't really like the way the code is structured. The <code>switch</code> statement with the internal <code>if</code> statements looks awful.</p> <p><em>Is there a better way to handle this kind of logic? Perhaps a design pattern I am overlooking?</em></p> <hr> <h2>Edit:</h2> <p>Inspired from <a href="https://codereview.stackexchange.com/a/44985/27529">aileronajay's input</a>, I think the following very nicely separates the abstractions.</p> <pre><code>$user = User::load($_COOKIE['login']); $requestData = json_decode($_POST['json']); $adminOnlyRequests = array('CreateUser','DeleteUser','PasswordReset' ...); $managerOnlyRequests = array('AddToSchedule','RemoveFromSchedule', ...); if( (!$user-&gt;isAdmin() &amp;&amp; in_array($requestData-&gt;requestType,$adminOnlyRequests)) || (!$user-&gt;isManager() &amp;&amp; in_array($requestData-&gt;requestType,$managerOnlyRequests))) die('Unauthorized Request'); // Now the user MUST be authorized to make the request (or the request is unspecified) // No longer need $user instantiated processRequest($requestData); // Bury switch statement in here </code></pre>
[]
[ { "body": "<p>you could find out initially whether the user is admin or manager and then maintain negative lists for the two.</p>\n\n<pre><code>boolean isManager = isManager();\nboolean isAdmin = isAdmin();\n\nmanagerNegativeList = {addToSchedule,...};\nadminNegativeList = { changeTitle,...}\n\nif(isManager){\n if(inMangerNegativeList){\n die();\n }\n}\nif(isAdmin){\n if(inAdminNegativeList){\n die();\n }\n}\nprocessRequest(requestType,$requestData)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:53:04.010", "Id": "78337", "Score": "0", "body": "I get what you are saying, this a much more elegant way to organize the code!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T16:22:15.803", "Id": "44985", "ParentId": "44972", "Score": "1" } }, { "body": "<p>(I don't work with PHP nowadays, so code is pseudocode.)</p>\n\n<blockquote>\n<pre><code>if(!$user-&gt;isAdmin()) die('Unauthorized Request'); else createUser($requestData);\n</code></pre>\n</blockquote>\n\n<p>You could reformat the line above to </p>\n\n<pre><code> if(!$user-&gt;isAdmin()) {\n die('Unauthorized Request'); \n } else { \n createUser($requestData); \n }\n</code></pre>\n\n<p>From this it's clear that the else block is unnecessary, since <code>die</code> stops the processing entirely, so the following is the same:</p>\n\n<pre><code> if(!$user-&gt;isAdmin()) {\n die('Unauthorized Request'); \n }\n createUser($requestData); \n</code></pre>\n\n<p>Here you can extract out a <code>checkAdmin($user)</code> function:</p>\n\n<pre><code>function checkAdmin($user) { \n if(!$user-&gt;isAdmin()) {\n die('Unauthorized Request'); \n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code> case 'CreateUser': checkAdmin(); createUser($requestData); break;\n case 'DeleteUser': checkAdmin(); deleteUser($requestData); break;\n ...\n</code></pre>\n\n<p>Another, more object-oriented approach is creating separate classes for the commands which implement a common interface:</p>\n\n<pre><code>public interface Command() {\n String getCommandName();\n void run($requestData);\n}\n\npublic class CreateUserCommand implements Command {\n\n public String getCommandName() {\n return \"CreateUser\";\n }\n\n public void run($requestData) {\n ...\n }\n}\n</code></pre>\n\n<p>You can also create an interface for the access checker:</p>\n\n<pre><code>public interface AccessChecker {\n void checkAccess($user);\n}\n\npublic class AdminAccessChecker {\n public void checkAccess($user) {\n if(!$user-&gt;isAdmin()) {\n die('Unauthorized Request'); \n }\n }\n}\n</code></pre>\n\n<p>Then combine them in a composite class:</p>\n\n<pre><code>public class AccessCheckedCommand {\n\n private Command command;\n private AccessChecker accessChecker;\n\n public AccessCheckedCommand(Command command, AccessChecker accessChecker) {\n // assign fields\n }\n\n public String getCommandName() {\n return command.getName();\n }\n\n public void run($user, $requestData) {\n accessChecker.checkAccess($user);\n command.run($requestData);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>AdminAccessChecker adminAccessChecker = new AdminAccessChecker();\n\nList&lt;AccessCheckedCommand&gt; commands = ...;\ncommands.put(new AccessCheckedCommand(new CreateUserCommand(), adminAccessChecker));\n...\n\nfor (AccessCheckedCommand accessCheckedCommand: commands) {\n if (command.getCommandName() == $requestData-&gt;requestType) {\n command.run($user, $requestData);\n return;\n }\n}\ndie('Invalid Request Specification');\n</code></pre>\n\n<p>I guess it shows the idea and you could modify that in a lot of ways according to your needs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:41:27.880", "Id": "78332", "Score": "0", "body": "Thanks for your input, it has given me a lot to think about!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T16:51:18.180", "Id": "44989", "ParentId": "44972", "Score": "1" } } ]
{ "AcceptedAnswerId": "44985", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T14:09:05.630", "Id": "44972", "Score": "4", "Tags": [ "php" ], "Title": "Better PHP Ajax Request Processing Structure" }
44972
<p>I have completed an application which gathers specific records and marks them as <code>Collected</code>. As of now, the application runs perfectly and does exactly what I need it to, but the problem comes in when a large data set is reviewed. If I am pulling records for one day or even maybe a week, it runs at a decent pace, but once you get a month of data or more, it takes a fairly long amount of time.</p> <pre><code>DataTable ModelData = getModelData() // Returns all records to search. ... EnumerableRowCollection&lt;DataRow&gt; modelRows = (from model in ModelData.AsEnumerable() where (model.Field&lt;object&gt;(GeographicalKey) ?? (object)String.Empty).ToString() == GeographicCode select model); ModelResults = modelRows.Any() ? modelRows.CopyToDataTable() : ModelData.Clone(); for (int i = 0; i &lt; ModelResults.Rows.Count; i++) { for (int j = 0; j &lt; ModelData.Rows.Count - 1; j++) { if (ModelResults.Rows[i]["Request ID"].ToString() == ModelData.Rows[j]["Request ID"].ToString()) { ModelData.Rows[j]["Collected"] = "1"; } } } </code></pre> <p>The only part that executes slowly would be the <code>for</code> and the nested <code>for</code>. Is there possibly a better way that I can code this? I can't imagine this is the optimal coding for data table update operations, but it might be. Is this a possibility in LINQ (I'm completely new to LINQ)? I think this is enough code to make sense of what I'm doing, but if more is needed just let me know and I can post it up as well.</p>
[]
[ { "body": "<p>There are a few optimizations that can be done in your code (such as using a <code>break</code> in the inner loop after a match is found - but reverting the order of the 2 loops) - but leaving the complexity order to O(n^2).</p>\n\n<p>A better approach instead is using a dictionary. Since you have a list of results, identified by a unique ID (<code>Request ID</code>), and a list of rows, uniquely identified in the same way, I would:</p>\n\n<ul>\n<li>create a dictionary, adding all <code>ModelData</code> rows, using <code>Unique ID</code> as key</li>\n<li>remove the 2nd loop, and just check for an element in the dictionary having the same ID as the <code>ModelData</code> row - if a match is found, set the <code>Collected</code> flag</li>\n</ul>\n\n<p>This should reduce the complexity from O(n^2) to O(n).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T15:25:17.740", "Id": "44981", "ParentId": "44973", "Score": "3" } }, { "body": "<blockquote>\n <p>The only part that executes slowly would be the for and the nested\n for. Is there possibly a better way that I can code this?</p>\n</blockquote>\n\n<p>I take you ask us to optimize the nested loops:</p>\n\n<p>The most obvious problem, as @Antonio also noted, is the O(n^2) filtering in the nested <code>for</code>s. Also as he noted, you need some kind of data structure with O(1) <code>Contains</code> method. However since you do not use other fields of from the rows of <code>ModelResults</code>, you only need a <code>HashSet</code> of <code>[\"Request ID\"]</code>s. </p>\n\n<blockquote>\n <p>I can't imagine this is the optimal coding for data table update\n operations, maybe though? Is this a possibility in LINQ (I'm\n completely new to LINQ)?</p>\n</blockquote>\n\n<p>I take you are asking for a more compact, more LINQy way of updating a collection, in this case a <code>DataTable</code>:</p>\n\n<p>LINQ is a query language and a LINQ query does not modify underlying <code>IEnumerable</code>. (In most cases you would <code>select</code> a modified copy of the underlying <code>IEnumerable</code>, instead.)</p>\n\n<p>However, you can use <code>List.ForEach</code> on the result of such a query, as a more compact replacement of <code>for</code> loop.</p>\n\n<p>Applying two suggestions above, we get:</p>\n\n<pre><code>var collectedRequestIds = new HashSet&lt;string&gt;(\n modelResults.AsEnumerable().Select(row =&gt; row[\"Request ID\"].ToString()));\n\nmodelData.AsEnumerable()\n .Where(collectedRequestIds.Contains(row =&gt; row[\"Request ID\"].ToString())))\n .ToList().ForEach(row =&gt; row[\"Collected\"] = \"1\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T10:10:08.780", "Id": "45190", "ParentId": "44973", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T14:37:39.763", "Id": "44973", "Score": "5", "Tags": [ "c#", "performance", "linq", ".net-datatable" ], "Title": "Better method for updating data table" }
44973
<p>The code below takes a specified number of card decks, and shuffles them according to the Fisher-Yates method. Does this implementation have any bias?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace randomShuffle { class Program { static void Main(string[] args) { List&lt;int&gt; deck = Cards.startDeck(1); } } class Cards { public static List&lt;int&gt; startDeck(int numDecks) { List&lt;int&gt; initial = new List&lt;int&gt;(); List&lt;int&gt; shuffled = new List&lt;int&gt;(); //set up list of all cards in order while (numDecks &gt; 0) { for (int i = 2; i &lt;= 14; i++) //2-ace(14) { for (int j = 0; j &lt; 4; j++) //each card in deck 4 times { initial.Add(i); } } numDecks--; } //Fisher-Yates method to shuffle Random r = new Random(DateTime.Now.Millisecond); int count = initial.Count; for (int i = 0; i &lt; count; i++) //go through entire unshuffled deck { //get random number from 0 to new range of unshuffled deck int randomDraw = r.Next(0, initial.Count); //take whatever is drawn and insert at beginning of shuffled list shuffled.Insert(0, initial[randomDraw]); //replace the card drawn with the end card initial[randomDraw] = initial.Last(); //remove the end card from initia deck initial.RemoveAt(initial.Count - 1); } return shuffled; } } } </code></pre>
[]
[ { "body": "<h3>Comments:</h3>\n\n<p>about all of your comments add close to no value to your code.</p>\n\n<blockquote>\n<pre><code>//get random number from 0 to new range of unshuffled deck\nint randomDraw = r.Next(0, initial.Count);\n</code></pre>\n</blockquote>\n\n<p>Your comment just writes out, what your code does in the next line. This is unneccesary noise and you should not do it. The probably only acceptable comment is this one:</p>\n\n<blockquote>\n<pre><code>for (int i = 2; i &lt;= 14; i++) //2-ace(14)\n</code></pre>\n</blockquote>\n\n<p>This exactly explains why you start on 2 and end with 14, the rest can be removed.</p>\n\n<p>But as @Marc-Andre pointed out correctly, this comment also becomes pure noise, as soon as you extract these magic numbers to named constants:</p>\n\n<pre><code>const int LOWEST_CARD = 2;\nconst int HIGHEST_CARD = 14;\nfor (int i = LOWEST_CARD; i &lt;= HIGHEST_CARD; i++)\n</code></pre>\n\n<h3>Extracting methods:</h3>\n\n<p>Why not extract your whole shuffle algorithm to a method? This makes the code in your startDeck less cluttered. Example:</p>\n\n<pre><code>public static List&lt;int&gt; startDeck(int numDecks)\n{\n List&lt;int&gt; initial = new List&lt;int&gt;();\n\n prepareDeck();\n\n return shuffled(initial);\n}\n</code></pre>\n\n<p>You now exactly know, what your startDeck does.</p>\n\n<h3>Naming:</h3>\n\n<p>Your class <code>Cards</code>. this is definitely not nice, but that name is not OK. What does your class do? Name it after that. Try to keep your classes in SRP, they only should do one thing and nothing more.</p>\n\n<p><code>Deck</code> might have been better depending on what it does apart from what you posted.<br>\nAlternatively use <code>Shuffler</code>, <code>Helper</code> or similar.</p>\n\n<h3>Algorithm:</h3>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/Fisher_Yates_shuffle#The_modern_algorithm\" rel=\"nofollow\">english wikipedia article</a> on the Fischer-Yates algorithm gives pretty nice pseudocode and tells us, that the algorithm is an in-place algorithm.<br>\nThis means you will not need a second list to put your shuffled cards in.</p>\n\n<pre><code>//To shuffle an array a of n elements (indices 0..n-1):\nfor i from n − 1 downto 1 do\n j ← random integer with 0 ≤ j ≤ i\n exchange a[j] and a[i]\n</code></pre>\n\n<p>this means, if you were strictly following the algorithm your code should look (something) like this:</p>\n\n<pre><code>int temp, randomNumber;\nint count = initial.Count;\nfor (int index = count -1; index &gt; 0; index--){\n randomNumber = r.Next(0, index+1);\n temp = initial [index];\n initial[index] = initial[randomNumber];\n initial[randomNumber] = temp;\n}\nreturn initial;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T16:38:01.583", "Id": "78323", "Score": "0", "body": "Thanks @Vogel612. My code comments are really just to help me with detailing each step of the fisher-yates method. My real concern with the above code is whether it's actually producing a acceptable randomly shuffled deck?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:45:21.590", "Id": "78335", "Score": "1", "body": "The acceptable comments to me looks like those \"magic numbers\" need to be extracted as variable with a proper name. This leave the comment obsolete." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T01:42:59.650", "Id": "78858", "Score": "0", "body": "`But as @Malachi pointed out correctly` did you mean me ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T07:31:11.413", "Id": "78878", "Score": "0", "body": "@Marc-Andre that reminds me of the C# question, where I wrote: \"there is var in c#, but unfortunately not in java\"... It's definitely getting worse. fixed it now." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T16:32:34.950", "Id": "44986", "ParentId": "44980", "Score": "7" } }, { "body": "<p>As for the random bias of the results.... your code appears to be unbiased.</p>\n\n<p>The Fisher-Yates (variant) looks correctly implemented....</p>\n\n<p>I would prefer if you organized the code to be <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm\" rel=\"nofollow\">more representative of the algorithm (the modern algorithm)</a>. If you need to shuffle the data in a separate list, then load all the data in to that list, and shuffle it in-place.</p>\n\n<p>If you don't need the second list, then just shuffle it in-place regardless....</p>\n\n<p>Shuffling in place is quite easy (assuming the data is all in <code>data</code> )... :</p>\n\n<pre><code> //Fisher-Yates method to shuffle\n Random r = new Random(DateTime.Now.Millisecond);\n int count = data.Length;\n while (count &gt; 1) //go through entire unshuffled deck\n {\n //get random number from 0 to new range of unshuffled deck\n int randomDraw = r.Next(0, count);\n\n //take whatever is drawn and swap it with the end of the list\n int tmp = data[randomDraw];\n data[randomDraw] = data[count-1];\n data[count-1] = tmp;\n\n count--;\n\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:45:27.390", "Id": "44994", "ParentId": "44980", "Score": "5" } }, { "body": "<p>i repeated 4 times is not a valid deck<br>\nYou have no way to know which suit it represents </p>\n\n<pre><code>shuffled.Insert(0, initial[randomDraw]);\n</code></pre>\n\n<p>Is O(N). Just insert and let it go in the end </p>\n\n<pre><code>shuffled.Insert(initial[randomDraw]);\n</code></pre>\n\n<p>You don't need to move it and then remove the last position<br>\nJust remove the position<br>\nThis is a List<br>\nThat method is used for an array and you don't remove<br>\nYou just move just copy the card and track range down one </p>\n\n<pre><code>//replace the card drawn with the end card\ninitial[randomDraw] = initial.Last();\n\n//remove the end card from initia deck\ninitial.RemoveAt(initial.Count - 1);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-13T20:59:37.077", "Id": "160709", "ParentId": "44980", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T15:18:06.600", "Id": "44980", "Score": "11", "Tags": [ "c#", "random", "playing-cards", "shuffle" ], "Title": "Card shuffling with Fisher-Yates method" }
44980
<p>I've been creating javascript things for a good few months now, as practise but whenever I use a functions I just create it and plug in the arguments. I'm never touching modules or classes or anything, and I just want to know how this code could be better, using modules and classes. Various function are sort of part of the same "family", such as <code>launchTypeA</code>, <code>launchTypeB</code> and <code>launchSlider</code>. <code>launchTypeA</code>, <code>launchTypeB</code> are similar, and both call<code>launchSlider</code>. I feel like this should be in some sort of module.</p> <p>So what does this script do? It basically destroys and reappends a <a href="http://flexslider.woothemes.com/" rel="nofollow">flexslider</a> element on initial load and on subsequent breakpoint changes. This is so I can update the flexslider with different attributes for responsive design. (on the mobile breakpoint it maybe only displays one <code>li</code>, on larger breakpoints, maybe <code>5</code>).</p> <p>To find these slider elements, it uses a loop to automatically loop through all elements with a <code>sliderElm</code> class on the page and then iterate through the object later on. This is so the same script will work just as well with one slider as it will for hundreds on the same page. It also works with types of slider. Look at the example for a better idea:</p> <p><a href="http://jsfiddle.net/sWBcw/4/" rel="nofollow">http://jsfiddle.net/sWBcw/4/</a></p> <p>The first three sliders are of <code>TypeA</code>. All type a sliders automatically slide at the standard speed. The last slider is of <code>TypeB</code>. All that's different about <code>TypeB</code> is its speed, but I could use any of <a href="https://github.com/woothemes/FlexSlider/wiki/FlexSlider-Properties" rel="nofollow">any of these attributes</a> to make <code>TypeB</code> vastly different.</p> <p>Anyway, I just want to know what you think of this code (my first serious project) and how I can improve it. I mean I've kept it dry as possible, <strong>but it still feels different to code I read in github repositories. How should package this script? Make it into an object?</strong></p> <p>I would seriously appreciate some guidance. </p> <pre><code>$(document).ready(function() { // a bit of workaround but I quite like it. The css breakpoints apply a // font-size of either 1px, 2px 3px or 4px to the empty div `#viewport` // from there we can work out the current breakpoint (1 for xs, 2 for sm, 3 for md and 4 for lg ) function getBreakpoint(){ // also cleans the breakpoint (some browsers add inverted commas) return $('#viewport').css('font-size').replace(/.*(1|2|3|4).*/g, '$1'); } // stores the html of the slider in the variable, destroys the html and recreates it. Is there a better way to do this? function reappendSlider(sliderId){ slider = $(document).find( '#' + sliderId ) sliderParent = $(document).find( '#' + slider.parent().attr('id') ); sliderHtml = $(slider).html(); slider.remove(); sliderParent.append('&lt;div id = "' + sliderId + '"&gt;&lt;/div&gt;'); $(document).find( '#' + sliderId ).append( sliderHtml ); } function launchSlider(sliderId, a){ var o = { 'namespace' : 'flex-', 'selector' : '.slides &gt; li', 'animation' : 'slide', 'easing' : 'swing', 'direction' : 'horizontal', 'reverse' : false, 'animationLoop' : true, 'smoothHeight' : false, 'startAt' : 0, 'slideshowSpeed' : 7000, 'animationSpeed' : 600, 'initDelay' : 0, 'randomize' : false, 'pauseOnAction' : true, 'pauseOnHover' : false, 'useCSS' : true, 'touch' : false, 'video' : false, 'controlNav' : false, 'directionNav' : false, 'prevText' : 'Previous', 'nextText' : 'Next', 'keyboard' : false, 'multipleKeyboard' : false, 'mousewheel' : false, 'pausePlay' : false, 'pauseText' : 'Pause', 'playText' : 'Play', 'controlsContainer' : '', 'manualControls' : '', 'sync' : '', 'asNavFor' : '', 'itemWidth' : '', 'itemMargin' : '', 'minItems' : 0, 'maxItems' : 0, 'move' : 1, 'start' : function(){}, 'before' : function(){}, 'after' : function(){}, 'end' : function(){}, 'added' : function(){}, 'removed' : function(){} } $.extend(o, o, a); o['minItems'] = o['maxItems'] o['itemWidth'] = $(document).find( '#' + sliderId ).width() / o['maxItems'] console.log( o['move'] ); $(document).find( '#' + sliderId ).flexslider({ namespace : o['namespace'], selector : o['selector'], animation : o['animation'], easing : o['easing'], direction : o['direction'], reverse : o['reverse'], animationLoop : o['animationLoop'], smoothHeight : o['smoothHeight'], startAt : o['startAt'], slideshowSpeed : o['slideshowSpeed'], animationSpeed : o['animationSpeed'], initDelay : o['initDelay'], randomize : o['randomize'], pauseOnAction : o['pauseOnAction'], pauseOnHover : o['pauseOnHover'], useCSS : o['useCSS'], touch : o['touch'], video : o['video'], controlNav : o['controlNav'], directionNav : o['directionNav'], prevText : o['prevText'], nextText : o['nextText'], keyboard : o['keyboard'], multipleKeyboard : o['multipleKeyboard'], mousewheel : o['mousewheel'], pausePlay : o['pausePlay'], pauseText : o['pauseText'], playText : o['playText'], controlsContainer : o['controlsContainer'], manualControls : o['manualControls'], sync : o['sync'], asNavFor : o['asNavFor'], itemWidth : o['itemWidth'], itemMargin : o['itemMargin'], minItems : o['minItems'], maxItems : o['maxItems'], move : 1, start : o['start'], before : o['before'], after : o['after'], end : o['end'], added : o['added'], removed : o['removed'] }); } function launchTypeB(id, maxItems, itemMargin){ slider = findSlider(id) sliderParent = slider.parent().parent() sliderLeftNav = sliderParent.find('.left-nav') sliderRightNav = sliderParent.find('.right-nav') if(initial == false){ reappendSlider(id) } sliderLeftNav.click(function(){ findSlider( id ).flexslider('prev'); }); sliderRightNav.click(function(){ findSlider( id ).flexslider('next'); }); launchSlider(id, {'maxItems' : maxItems, 'itemMargin' : itemMargin, 'slideShow' : true, 'slideshowSpeed': 10 }); } function launchTypeA(id, maxItems, itemMargin){ if(initial == false){ reappendSlider(id) } sliderLeftNav.click(function(){ findSlider( id ).flexslider('prev'); }); sliderRightNav.click(function(){ findSlider( id ).flexslider('next'); }); launchSlider(id, {'maxItems' : maxItems, 'itemMargin' : itemMargin }); } function findSlider(id){ return $(document).find( '#' + id ) } function loopSliders(){ $.map( typeASlidersIds, function( value, type ){ $.map( value, function( value, key){ switch(type){ case 'sliderTypeA': console.log(breakpoint); switch(breakpoint){ case 'xs': console.log( 'xs launched' ); launchTypeA(value, 1,0); break; case 'sm': launchTypeA(value, 2,0); break; case 'md': launchTypeA(value, 2,0); break; case 'lg': launchTypeA(value, 2,0); break; } break; case 'sliderTypeB': switch(breakpoint){ case 'xs': launchTypeB(value, 1,0); break; case 'sm': launchTypeB(value, 2,0); break; case 'md': launchTypeB(value, 2,0); break; case 'lg': launchTypeA(value, 2,0); break; } break; } }); }); } function xsBreakpoint(){ breakpoint = 'xs' loopSliders(); } function smBreakpoint(){ breakpoint = 'sm' loopSliders(); } function mdBreakpoint(){ breakpoint = 'md' loopSliders(); } function lgBreakpoint(){ breakpoint = 'lg' loopSliders(); } function launchBreakpoint(breakpoint){ switch( breakpoint ){ case '1': xsBreakpoint(); break; case '2': smBreakpoint(); break; case '3': mdBreakpoint(); break; case '4': lgBreakpoint(); break; } initial = false } /* begin */ typeASlidersIds = {} currentBreakpoint = getBreakpoint() initial = true timer = 0 $('.sliderElm').each(function( key, slider ){ type_class = $(slider).attr('class').split(' ')[0] if( typeASlidersIds.hasOwnProperty(type_class) == false) { typeASlidersIds[type_class] = [] } // typeASlidersIds[type_class].push(slider); typeASlidersIds[type_class].push($(slider).attr('id')); }); /* start now */ launchBreakpoint(currentBreakpoint); /* start after reszie */ $(window).resize(function(){ clearTimeout(timer); timer = setTimeout( function(){ // below is run every 1/4 of a second! var newBreakpoint = getBreakpoint(); $.map( typeASlidersIds, function( typaASliderId ){ findSlider(typaASliderId).resize(); }); if(newBreakpoint != currentBreakpoint){ launchBreakpoint( newBreakpoint ); currentBreakpoint = newBreakpoint } // above is run every 1/4 of a second! }, 250) }); }); </code></pre>
[]
[ { "body": "<p>On the first pass the code was pretty easy to follow but are all those global variable intended?</p>\n\n<p>Globals I noticed in my look through... May be more.</p>\n\n<pre><code>breakpoint\ntypeASlidersIds\ncurrentBreakpoint\ninitial\ntimer\nslider\nsliderParent\nsliderHtml\n</code></pre>\n\n<p>I would add a <code>var breakpoint, typeASlidersIds, ...</code> after your <code>doc.ready()</code></p>\n\n<p>Also the helpers you use in <code>launchBreakpoint</code> seem pretty redundant. I would personally drop the helpers and write that function:</p>\n\n<pre><code>function launchBreakpoint(brkpnt){\n switch( brkpnt ){\n case '1':\n breakpoint = 'xs'\n break;\n case '2':\n breakpoint = 'sm'\n break;\n case '3':\n breakpoint = 'md'\n break;\n case '4':\n breakpoint = 'lg'\n }\n\n loopSliders();\n initial = false\n}\n</code></pre>\n\n<p>One last thing before I head out... These are terrible variable names and, moreover, extending an object with its self is pointless</p>\n\n<pre><code>$.extend(o, o, a);\n</code></pre>\n\n<p>To answer the actual question OP seems to be posing -- the pattern is fine I wouldn't change it but I would expose whatever you want to expose explicitly into a namespace using this format (window or whatever namespace):</p>\n\n<pre><code>window.myglobal = {\n prop1: ...\n prop2: ...\n}\n</code></pre>\n\n<p>That pattern would closely match <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript\" rel=\"nofollow\">The javascript revealing pattern</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T19:57:02.423", "Id": "78365", "Score": "0", "body": "Thanks, are the only bad variable names `o` and `a`? Is this because they don't describe what they contain?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:13:34.080", "Id": "78368", "Score": "0", "body": "Also, could you emphasize a lot more on your last point? An example using my code would be of great help :) And globals are just variables declared at the global scope? So what is the benefit of using `var`? Stop strange bugs by not letting them get inside functions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:53:01.523", "Id": "78390", "Score": "0", "body": "Global variables are poor practice for various readability, maintainability, performance, etc. see [this SO post](http://stackoverflow.com/questions/10525582/why-are-global-variables-considered-bad-practice-javascript). As far as the last point is concerned theres plenty of resources I can point you to if the linked one is insufficent (its my personal favourite) but I'm not going to write your code as I don't know whats supposed to be exposed" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:54:06.767", "Id": "78392", "Score": "0", "body": "Variable names should be descriptive.. I don't know what they mean but I'm assuming id probably call `o` config or something and `a` options" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:54:54.903", "Id": "78394", "Score": "0", "body": "Cool...I'll admit I don't really know what you mean by `exposed`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:55:25.743", "Id": "78396", "Score": "0", "body": "What you want other modules/programmers to be allowed to access from your code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T15:56:45.080", "Id": "79778", "Score": "0", "body": "@Starkers what you decide to expose is your [API](http://en.wikipedia.org/wiki/Application_programming_interface)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:44:23.547", "Id": "44993", "ParentId": "44984", "Score": "2" } } ]
{ "AcceptedAnswerId": "44993", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T16:14:12.453", "Id": "44984", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Should I use modules here? Could someone explain objects?" }
44984
<p>I have multiple menus that will change languages in one Sub that will handle multiple events of the menus click, It is working for me right now, I'm just wondering if there is better way to do it... I'm using the menus name to call the process for each menus.</p> <pre><code> Private Shared Sub CheckMenuItem(ByVal mnu As ToolStripMenuItem, ByVal checked_item As ToolStripMenuItem) For Each menu_item As ToolStripMenuItem In mnu.DropDownItems.OfType(Of ToolStripMenuItem)() menu_item.Checked = (menu_item Is checked_item) Next End Sub Private Sub mnuEnglish_Click(sender As System.Object, e As EventArgs) _ Handles mnuEnglish.Click, mnuFrench.Click, mnuDutch.Click, _ mnuGerman.Click,mnuCroatian.Click, mnuCzech.Click, mnuHungarian.Click, _ mnuIndonesian.Click, mnuItalian.Click, mnuPolish.Click, mnuSlovak.Click, _ mnuSpanish.Click, mnuSwedish.Click, mnuTurkish.Click, mnuVietnamese.Click Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem) CheckMenuItem(mnuLanguage, item) Select Case item.Name Case "mnuEnglish" MsgBox("english") Case "mnuFrench" MsgBox("French") Case Else MsgBox("Other Languages") End Select End Sub </code></pre>
[]
[ { "body": "<p>The <code>ToolStripItem</code> contains a property called <code>Tag</code> which is used to store extra information about a menu item. This is where you could store information about the language. Then your event could be generalized by using the information in <code>Tag</code>.</p>\n\n<pre><code>mnuEnglish.Tag = \"English\" ' Instead of just a string, I would have a language class\nmnuFrench.Tag = \"French\"\n...\n\nPrivate Sub mnuEnglish_Click(...\n\nDim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)\n CheckMenuItem(mnuLanguage, item)\n\n MsgBox(item.Tag)\n\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:55:37.633", "Id": "45629", "ParentId": "44987", "Score": "3" } }, { "body": "<p>See <a href=\"https://stackoverflow.com/a/17511209/1188513\">this Stack Overflow answer</a>, where <a href=\"https://stackoverflow.com/users/366904/cody-gray\">Cody Gray</a> explains the syntax for the two ways of registering event handlers in <a href=\"/questions/tagged/vb.net\" class=\"post-tag\" title=\"show questions tagged &#39;vb.net&#39;\" rel=\"tag\">vb.net</a>:</p>\n\n<blockquote>\n <p><em>The first involves the use of the Handles keyword, which you append to the end of the event handler method's definition. [...] The second involves the explicit use of the AddHandler statement, just like += in C#.</em></p>\n</blockquote>\n\n<p>This means instead of statically declaring all the handled events with a <code>Handles</code> keyword, you write code to add the handlers yourself:</p>\n\n<pre><code>Public Sub New()\n\n InitializeComponents()\n\n AddHandler mnuEnglish.Click, AdressOf mnuEnglish_Click\n AddHandler mnuFrench.Click, AdressOf mnuEnglish_Click\n '...\n\nEnd Sub\n</code></pre>\n\n<p>Or even better, loop through the menu items in that menu object, and assing all <code>Click</code> events the <code>AdressOf mnuEnglish_Click</code>, so you won't have the opportunity to forget updating that piece of code when you add a new language / menu item in the designer:</p>\n\n<pre><code>Public Sub New()\n\n InitializeComponents()\n\n ForEach item As ToolStripMenuItem In mnu.DropDownItems.OfType(Of ToolStripMenuItem)()\n AddHandler item.Click, AdressOf mnuEnglish_Click\n Next\n\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-27T15:55:14.450", "Id": "84835", "Score": "1", "body": "thanks to this, works great, still you need to check for type for ToolStripSeparator...the code you provided will have an error if there is a separator in DropDownItems in menus" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-27T19:31:04.657", "Id": "84872", "Score": "0", "body": "@mercenary interesting.. I would have thought `item` would be `Nothing` when it's a `ToolStripSeparator`, because of `As ToolStripMenuItem` - looks like you need to further filter the items with `.OfType(Of ToolStripMenuItem)`... I'll edit out the last part of my answer then ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-13T00:59:11.047", "Id": "47032", "ParentId": "44987", "Score": "5" } }, { "body": "<p>so silly of me, simple google solve my problem</p>\n\n<pre><code>For Each item As ToolStripMenuItem In mnuLanguage.DropDownItems.OfType(Of ToolStripMenuItem)()\n If item.Name IsNot \"mnuEnglish\" Then\n AddHandler item.Click, AddressOf mnuEnglish_Click\n End If\nNext\n</code></pre>\n\n<p>of this converted to LINQ expression thanks to Resharper</p>\n\n<pre><code>For Each item As ToolStripMenuItem In From mnu_items In mnuLanguage.DropDownItems.OfType(Of ToolStripMenuItem)() Where mnu_items.Name IsNot \"mnuEnglish\"\n AddHandler item.Click, AddressOf mnuEnglish_Click\nNext\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-29T19:35:58.767", "Id": "194292", "Score": "1", "body": "Could you explain what the difference between these is and how it improves things? It's not much of a review when it doesn't teach better practices." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-27T16:55:29.503", "Id": "48353", "ParentId": "44987", "Score": "1" } }, { "body": "<p>Make sure you have only one handler for every event. If you use the \"Handles\" syntax at the end of the subroutine declaration for the click handler, that registers a handler.</p>\n\n<p>For derived classes, if the base handler is defined with a \"Handles\" clause, it register a handler. If the overrides handler in the derived class is also defined with a \"Handles\" clause, it will register a second handler, and both will be triggered when the event is fired.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-15T02:37:21.890", "Id": "66699", "ParentId": "44987", "Score": "1" } } ]
{ "AcceptedAnswerId": "47032", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T16:42:43.900", "Id": "44987", "Score": "3", "Tags": [ "vb.net", "winforms" ], "Title": "Handle multiple menu click events in one Sub" }
44987
<p>I am creating a user permission system. I will have my user permissions set up off of "objects" and not pages. For example, I have an <code>EVENTS</code> section. Within that section, there are <code>FORMS</code>, <code>FEES</code>, etc. I want to be able to handle permissions down to the child levels.</p> <p>Here is my permission_objects table:</p> <pre><code>| id | object | parent_id | +----+--------+-----------+ | 1 | EVENTS | NULL | | 2 | FORMS | 1 | | 3 | FEES | 1 | </code></pre> <p>Here is my current query:</p> <pre><code>SELECT `up`.* FROM `permission_objects` `po` INNER JOIN `user_permissions` `up` ON `up`.`object`=`po`.`id` AND (`up`.`user_group`=2 OR `up`.`user_id`=17) WHERE `po`.`object`='EVENTS' OR `po`.`parent_id`=( SELECT `id` FROM `permission_objects` WHERE `object`='EVENTS' ) </code></pre> <p>I really want to avoid doing a subquery. I thought that instead of having a <code>parent_id</code> I could have <code>parent_object</code> and have that contain the parent's object value. i.e. <code>| 2 | FORMS | EVENTS |</code>. That way I could change my <code>WHERE</code> clause to:</p> <pre><code>WHERE `po`.`object`='EVENTS' OR `po`.`parent_object`='EVENTS' </code></pre> <p>However I feel that keeping it as <code>parent_id</code> is a better approach. Is there a way to keep that but not have to have a subquery in my sql?</p>
[]
[ { "body": "<p>The sub-query as a concept is not a problem... you need to do that work, and this is a decent way to do it.</p>\n\n<p>It would be better if it was expressed as a direct lookup... like:</p>\n\n<pre><code>WHERE `po`.`object`='EVENTS'\n OR exists (\n SELECT `sub`.`id`\n FROM `permission_objects` `sub`\n WHERE `sub`.`object`='EVENTS'\n and `sub`.`id` = `po`.`parent_id`\n)\n</code></pre>\n\n<p>This sub-select is better because it can do an indexed lookup in the table in the sub-select based on the <code>id</code> column.</p>\n\n<p>Apart from that, I don't see a better, or neater way to do it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:40:25.253", "Id": "78330", "Score": "0", "body": "Did you mean `and sub.id = po.parent_id`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:46:02.203", "Id": "78336", "Score": "0", "body": "@Aust Yes, I did ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T18:00:46.657", "Id": "78339", "Score": "0", "body": "I thought so but I've never seen `exists` so I wasn't exactly sure. =) I do have one question though, how does `exists` compare to adding `LEFT JOIN permission_objects po2 ON po2.parent_id=po.id` and changing `... up ON (up.object=po.id OR up.object=po2.id) ...`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T18:05:51.493", "Id": "78342", "Score": "0", "body": "The left-join wont give you what you want because you need the OR condition on the parent's Event..... and that will produce duplicate results. `exists` is the right tool for this job. You **do** have an index on the permission_objects.id column, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T18:49:31.183", "Id": "78349", "Score": "0", "body": "Yes I have my id columns indexed." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:04:50.527", "Id": "44990", "ParentId": "44988", "Score": "3" } }, { "body": "<p>Your query probably doesn't do what you intend, because <code>AND</code> has higher precedence that <code>OR</code>. It is therefore equivalent to</p>\n\n<pre><code>SELECT `up`.*\n FROM `permission_objects` `po`\n INNER JOIN `user_permissions` `up`\n ON (`up`.`object`=`po`.`id` AND `up`.`user_group`=2)\n OR `up`.`user_id`=17\n WHERE `po`.`object`='EVENTS'\n OR `po`.`parent_id`=(\n SELECT `id` FROM `permission_objects` WHERE `object`='EVENTS'\n )\n</code></pre>\n\n<p>You probably meant</p>\n\n<pre><code>SELECT `up`.*\n FROM `permission_objects` `po`\n INNER JOIN `user_permissions` `up`\n ON `up`.`object`=`po`.`id`\n AND (`up`.`user_group`=2 OR `up`.`user_id`=17)\n WHERE `po`.`object`='EVENTS'\n OR `po`.`parent_id`=(\n SELECT `id` FROM `permission_objects` WHERE `object`='EVENTS'\n )\n</code></pre>\n\n<p>However, that's not really a join condition. I'd move the <code>user_group</code> and <code>user_id</code> filter to the <code>WHERE</code> clause. Since you are interested in the <code>user_permissions</code> more than the <code>permission_objects</code>, I'd make <code>user_permissions</code> the primary table.</p>\n\n<pre><code>SELECT `up`.*\n FROM `user_permissions` `up`\n INNER JOIN `permission_objects` `po`\n ON `up`.`object` = `po`.`id`\n WHERE\n (`up`.`user_group` = 2 OR `up`.`user_id` = 17)\n AND (\n `po`.`object`='EVENTS'\n OR `po`.`parent_id`=(\n SELECT `id` FROM `permission_objects` WHERE `object`='EVENTS'\n )\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T19:00:02.000", "Id": "78542", "Score": "0", "body": "Yes you're right. I meant to put that OR in (). Oops! ... Are there performance gains from using user_permissions as the primary table instead of permission_objects?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T19:55:28.137", "Id": "78544", "Score": "0", "body": "Using `user_permissions` as the primary table is a stylistic change; performance should be the same." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T23:46:23.230", "Id": "45045", "ParentId": "44988", "Score": "2" } } ]
{ "AcceptedAnswerId": "44990", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T16:44:18.050", "Id": "44988", "Score": "5", "Tags": [ "optimization", "performance", "mysql", "sql" ], "Title": "SQL Query that pulls rows in current table based on parent id optimization" }
44988
<p>This code is to allow calling any stored procedure with one user defined table as the parameter.</p> <p>I usually use Entity Framework, but I just don't need it for my current solution, so I am rolling my own connection here:</p> <pre><code>public class GenericDataModel { public GenericDataModel(string connectionString) { this.connectionString = connectionString; } /// &lt;summary&gt; /// Connection string for the database /// &lt;/summary&gt; private readonly String connectionString; /// &lt;summary&gt; /// Calls a stored procedure with a single table as the parameter /// &lt;/summary&gt; /// &lt;param name="storedProcedureName"&gt;Name of the stored procedure to call (ie integration.UpsertTestOrderTrackingNum)&lt;/param&gt; /// &lt;param name="parameterName"&gt;Name of the parameter (ie "@TestOrderTrackingNumObjects")&lt;/param&gt; /// &lt;param name="sprocParamObjects"&gt;Parameter for the sproc&lt;/param&gt; /// &lt;param name="tableParamTypeName"&gt;name of the table valued parameter. (ie. integration.TestOrderTrackingNumTableType)&lt;/param&gt; /// &lt;param name="connection"&gt;The connection to use. This is optional and is there to allow transactions.&lt;/param&gt; public void ExecuteTableParamedProcedure&lt;T&gt;(string storedProcedureName, string parameterName, string tableParamTypeName, IEnumerable&lt;T&gt; sprocParamObjects, SqlConnection connection = null) { // If we don't have a connection, then make one. // The reason this is optionally passed in is so we can do a transaction if needed. bool connectionCreated = false; if (connection == null) { connection = new SqlConnection(connectionString); connection.Open(); connectionCreated = true; } // Create the command that we are going to be sending using (SqlCommand command = connection.CreateCommand()) { command.CommandText = storedProcedureName; command.CommandType = CommandType.StoredProcedure; SqlParameter parameter = command.Parameters.AddWithValue(parameterName, CreateDataTable(sprocParamObjects)); parameter.SqlDbType = SqlDbType.Structured; parameter.TypeName = tableParamTypeName; // Call the sproc. command.ExecuteNonQuery(); } // if we made the connection then we need to clean it up if (connectionCreated) connection.Close(); } /// &lt;summary&gt; /// Calls a list of sprocs in a transaction. /// Example Usage: CallSprocsInTransaction(connection=&gt;model.SprocToCall(paramObjects, connection), connection=&gt;model.Sproc2ToCall(param2Objects, connection...); /// &lt;/summary&gt; /// &lt;param name="sprocsToCall"&gt;List of sprocs to call.&lt;/param&gt; public void CallSprocsInTransaction(params Action&lt;SqlConnection&gt;[] sprocsToCall) { // Create a new connection that will run the transaction using (SqlConnection connection = new SqlConnection(connectionString)) { // Create a transaction to wrap our calls in var transaction = connection.BeginTransaction(); try { // Call each sproc that was passed in. foreach (var action in sprocsToCall) { // We send the connection to the action so that it will all take place on the same connection. // If we don't then if we do a rollback, the rollback will be for a connection that did not run the sprocs. action(connection); } } catch (Exception e) { // If we failed then roll back. // The idea here is that the caller wants all the sprocs to succeed or none of them. transaction.Rollback(); throw; } // If everything was good, then commit our calls. transaction.Commit(); } } /// &lt;summary&gt; /// Create the data table to be sent up to SQL Server /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Type of object to be created&lt;/typeparam&gt; /// &lt;param name="sprocParamObjects"&gt;The data to be sent in the table param to SQL Server&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private static DataTable CreateDataTable&lt;T&gt;(IEnumerable&lt;T&gt; sprocParamObjects) { DataTable table = new DataTable(); Type type = typeof (T); PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { table.Columns.Add(property.Name, property.PropertyType); } foreach (var sprocParamObject in sprocParamObjects) { var propertyValues = new List&lt;object&gt;(); foreach (PropertyInfo property in properties) { propertyValues.Add(property.GetValue(sprocParamObject, null)); } table.Rows.Add(propertyValues.ToArray()); Console.WriteLine(table); } return table; } } </code></pre> <p>Looking for any resource leaks or other missed/hidden issues.</p> <p>I have tested it and it works fine for normal calls. I have not been able to test the Transaction method yet.</p> <p>Example useage:</p> <pre><code>public void UpsertMethod(List&lt;ITypeThatHasTheSamePropertiesAsTheTbleType&gt; rows, SqlConnection connection = null) { ExecuteTableParamedProcedure("schema.UpsertSproc", "@UpsertParam", "schema.UpsertTableType", rows, connection); } </code></pre> <p>Example Transaction Usage:</p> <pre><code>public void CallInTransaction(List&lt;ITypeThatHasTheSamePropertiesAsTheTbleType&gt; firstObjects, List&lt;ISecondObjects&gt; secondObjects) { CallSprocsInTransaction(connection =&gt; UpsertMethod(firstObjects, connection), connection =&gt; UpsertSecondObjects(secondObjects, connection)); } </code></pre>
[]
[ { "body": "<blockquote>\n <p>Looking for any resource leaks or other missed/hidden issues.</p>\n</blockquote>\n\n<p>Have a <code>using</code> statement for your <code>var transaction</code> instance: because <code>SqlTransaction</code> implements <code>IDisposable</code> (<a href=\"http://msdn.microsoft.com/en-us/library/bf2cw321.aspx\" rel=\"nofollow noreferrer\">see link</a> and <a href=\"https://stackoverflow.com/q/1127830/49942\">link</a>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:49:15.150", "Id": "44995", "ParentId": "44991", "Score": "4" } }, { "body": "<blockquote>\n<pre><code>/// &lt;summary&gt;\n/// Calls a stored procedure with a single table as the parameter\n/// &lt;/summary&gt;\n/// &lt;param name=\"storedProcedureName\"&gt;Name of the stored procedure to call (ie integration.UpsertTestOrderTrackingNum)&lt;/param&gt;\n/// &lt;param name=\"parameterName\"&gt;Name of the parameter (ie \"@TestOrderTrackingNumObjects\")&lt;/param&gt;\n/// &lt;param name=\"sprocParamObjects\"&gt;Parameter for the sproc&lt;/param&gt;\n/// &lt;param name=\"tableParamTypeName\"&gt;name of the table valued parameter. (ie. integration.TestOrderTrackingNumTableType)&lt;/param&gt;\n/// &lt;param name=\"connection\"&gt;The connection to use. This is optional and is there to allow transactions.&lt;/param&gt;\npublic void ExecuteTableParamedProcedure&lt;T&gt;(string storedProcedureName, string parameterName, string tableParamTypeName, IEnumerable&lt;T&gt; sprocParamObjects, SqlConnection connection = null)\n</code></pre>\n</blockquote>\n\n<p>This is probably highly arguable, but I don't like C# optional parameters. The language supports method overloading, which produces methods that are more focused/cohesive.</p>\n\n<p>Thus, I would consider:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Calls a stored procedure with a single table as the parameter.\n/// &lt;/summary&gt;\npublic void ExecuteTableParamedProcedure&lt;T&gt;(string storedProcedureName, \n string parameterName, \n string tableParamTypeName, \n IEnumerable&lt;T&gt; sprocParamObjects)\n{\n using (var connection = new SqlConnection(this.connectionString))\n {\n connection.Open();\n ExecuteTableParamedProcedure(storedProcedureName, \n parameterName, \n tableParamTypeName, \n sprocParamObjects, \n connection); // multiline to avoid side-scrolling\n }\n}\n\n/// &lt;summary&gt;\n/// Calls a stored procedure with a single table as the parameter,\n/// using the specified connection.\n/// &lt;/summary&gt;\n/// &lt;remarks&gt;\n/// Useful when executing a stored procedure within a transaction.\n/// &lt;/remarks&gt;\npublic void ExecuteTableParamedProcedure&lt;T&gt;(string storedProcedureName, \n string parameterName, \n string tableParamTypeName, \n IEnumerable&lt;T&gt; sprocParamObjects,\n SqlConnection connection)\n{\n // do your thing, you *do* have a connection, and don't need to care about cleaning up.\n}\n</code></pre>\n\n<p>This way the overload that <em>does</em> take a <code>connection</code> parameter can do away with <code>bool connectionCreated</code> and the comments that explain <em>why</em> a connection needs to be created and closed (<strong>what about <em>disposed</em>?</strong>).</p>\n\n<p>The overload that <em>does not</em> take a <code>connection</code> parameter wraps it in a <code>using</code> block, so you're always sure it gets disposed correctly.</p>\n\n<hr>\n\n<p><strong>Naming</strong></p>\n\n<p>I think there's possibly a typo in the method's name: <code>ExecuteTableParamedProcedure</code> doesn't look right. Either <code>Parameterized</code>, or the commonly recognized (and used elsewhere) <code>Param</code> - <code>Paramed</code> makes me wonder where the ambulance is.</p>\n\n<hr>\n\n<p><strong>Comments</strong></p>\n\n<blockquote>\n<pre><code>// Create the command that we are going to be sending\n</code></pre>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n<pre><code>// Call the sproc.\n</code></pre>\n</blockquote>\n\n<p>These comments say nothing that the code doesn't say already. They should be removed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:49:54.477", "Id": "44996", "ParentId": "44991", "Score": "5" } }, { "body": "<p><strong>Naming</strong><br>\nOn the whole, your naming is just fine. I wonder, though, why you called your class <code>GenericDataModel</code>? What makes it generic? Can't it be called <code>DataModel</code>?</p>\n\n<p><strong>Comments</strong><br>\nSince your method naming and parameter naming are descriptive - most of your comments are completely redundant - I don't need a comment to tell me that <code>CallSprocsInTransaction</code> call sprocs in transaction, or that <code>sprocsToCall</code> is a list of sprocs to call... These comments just add clutter and nothing else.<br>\nThis also goes for inline comments, which tell us trivial things like you are creating the command you are going to send.</p>\n\n<p><strong>Potential leak - not using <code>using</code></strong><br>\nWhen you create the connection inside the method, you <code>Close</code> it at the end of the method, but you do not count for possible <code>Exceptions</code> inside the method. In such a case - the connection will not be closed.<br>\nTo prevent it you can use <code>try...finally</code>, but you can also take advantage of the fact that <a href=\"https://stackoverflow.com/questions/2522822/c-sharp-using-statement-with-a-null-object\"><code>using</code> supports <code>null</code> objects</a>:</p>\n\n<pre><code>public void ExecuteTableParamedProcedure&lt;T&gt;(string storedProcedureName, string parameterName, string tableParamTypeName, IEnumerable&lt;T&gt; sprocParamObjects, SqlConnection connection = null)\n {\n SqlConnection adHocConnection = null;\n if (connection == null)\n {\n connection = new SqlConnection(connectionString);\n connection.Open();\n adHocConnection = connection;\n }\n\n using (adHocConnection)\n {\n using (SqlCommand command = connection.CreateCommand())\n {\n command.CommandText = storedProcedureName;\n command.CommandType = CommandType.StoredProcedure;\n\n SqlParameter parameter = command.Parameters.AddWithValue(parameterName, CreateDataTable(sprocParamObjects));\n parameter.SqlDbType = SqlDbType.Structured;\n parameter.TypeName = tableParamTypeName;\n\n command.ExecuteNonQuery();\n }\n }\n\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:53:18.490", "Id": "78391", "Score": "0", "body": "Thank you for your comments! The only problem with the using is that if it is in a transaction, then I don't want to close the connection. However, I will add in the catch block." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T21:55:45.123", "Id": "78405", "Score": "2", "body": "Read again - if the connection was not opened by the method - `adHocConnection` is `null`, so the connection won't be closed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T18:34:18.850", "Id": "78813", "Score": "0", "body": "You are right! I missed the null check." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:55:12.000", "Id": "44997", "ParentId": "44991", "Score": "5" } } ]
{ "AcceptedAnswerId": "44997", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:16:40.483", "Id": "44991", "Score": "4", "Tags": [ "c#", "sql" ], "Title": "Generic class to call table parametered stored procedures" }
44991
<p>I need some help refactoring my solution to the problem below:</p> <p><strong>Problem Statement</strong></p> <blockquote> <p>An Association of Computer Scientists meets on a weekly basis. There is a certain number of seats in the meeting room and all members know their seats. For example, if there are 10 seats and only 5 members attending, each member will sit on his own seat, and there may be empty seats left between the members, because all have to sit on their 'reserved' seats.</p> <p>If a member, sitting on seat <strong>Xi</strong>, starts or joins the discussion, exactly <strong>Ti</strong> people (after him) will take part of the discussion. For every member, we know his seat and his voice. Only those members who are within the reach of the previous member's voice can hear him and participate in the discussion. For example, if we are given the seat and the voice of a member, and they are 1, 7 (respectively), only people seated on seats within range of 1 to 8 (inclusive) can hear him and participate in the discussion.</p> </blockquote> <p><strong>Example Data</strong></p> <blockquote> <p><strong>Input:</strong></p> <p><strong>N</strong> - number of members attending</p> <p><strong>Xi</strong> - seat of member i (for all i=1,2,...N), <strong>Li</strong> - his voice</p> <p><strong>Output:</strong></p> <p>The number of people participating in the discussion after member <strong>i</strong>.</p> <p><strong>Example Input:</strong></p> <pre><code>5 1 7 2 3 8 7 10 5 100 2 </code></pre> <p><strong>Output:</strong></p> <pre><code>4 1 2 1 1 </code></pre> </blockquote> <p>And now, here's my solution:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; int main() { int n; cin &gt;&gt; n; vector&lt;pair&lt;int, int&gt; &gt; c; for (int i=0; i&lt;n; i++) { int a, b; cin &gt;&gt; a &gt;&gt; b; c.push_back(make_pair(a,b)); } for (int i=0; i&lt;n; i++) { int a, b, r=1; a = c[i].first; b = c[i].second; for (int j=i+1; j&lt;n; j++) { if (a+b &gt;= c[j].first) { if (c[j].first + c[j].second &gt; a+b) { a = c[j].first; b = c[j].second; } r++; } } cout &lt;&lt; r &lt;&lt; endl; } return 0; } </code></pre> <p>The problem with this solution is in its quadratic O-complexity. Is it possible to reduce it somehow? I've been thinking of the divide and conquer approach, but I'm fairly new to the concept, and I have no idea if that's the right approach for this problem, and how I may implement that.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T19:37:45.127", "Id": "78355", "Score": "2", "body": "Do you know the maximum number of inputs and do you have a time limit? I'm curious what kind of runtime is likely going to be required. I'm fairly certain that there is a sub-quadratic algorithm, but everything I can think of is relatively unpleasant to actually implement compared to the naive algorithm. My first thought was a tweaked heap, but the more I think about it, I think this is solvable with dynamic programming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T19:46:21.303", "Id": "78361", "Score": "0", "body": "I've been thinking about a dynamic programming solution too... The naive algorithm is all well, if used for small inputs, but that's not very satisfying." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T19:57:00.927", "Id": "78364", "Score": "0", "body": "Oh yeah, 1 <= **N** <= 100 000 and 1 <= **Xi**,**Li** <= 1 000 000 000, where **N** is the number of attendees, **Xi** the seat of every member **i** and **Li** his voice.\n\nTime limit is 1 second, and memory limit is 64MB." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T10:10:45.410", "Id": "78495", "Score": "0", "body": "Does \"after him\" mean \"not including him\", or does it mean \"only people sitting to his right\"?" } ]
[ { "body": "<p>I plan to think up a better algorithm later and post an answer on that, but for now, I'd like to offer a critique of your existing code.</p>\n\n<hr>\n\n<p>Typically <code>using namespace std;</code> should be avoided in favor of either using the <code>std::</code> qualifier or just importing the identifiers you plan to use at a function level. (E.g. inside of main, doing something like <code>using std::cout;</code>.)</p>\n\n<hr>\n\n<p>You should verify that your input reading succeeds:</p>\n\n<pre><code>if (!(cin &gt;&gt; n)) { return EXIT_FAILURE; }\n</code></pre>\n\n<p>(And something similar in your loop.)</p>\n\n<p>On the off chance that something goes wrong, you'd rather bail out with an exit code than do nothing. If you really wanted, you could even put out an error message (though for contest-style problems like these that would be more for your use than the end purpose).</p>\n\n<hr>\n\n<p>It's a good habit in C++ to use <code>++i</code> whenever you can as opposed to <code>i++</code>. For an int or any other built in, it doesn't particularly matter, but for complex types, <code>++i</code> can avoid an expensive copy. </p>\n\n<p>The most common manifestation of this is iterators. <code>++i</code> increments an iterator in place. <code>i++</code> creates a copy of the iterator, increments the original one and then returns the copy. If you're not actually capturing the copy, there's no reason to create one.</p>\n\n<hr>\n\n<p>Try to give variables more useful names. Imagine coming back to this 6 months from now, or imagine if I hadn't read the problem statement. I would be left wondering what in the world all these 1 character variable names are. Descriptive variables assist the reader in more quickly comprehending what code is doing.</p>\n\n<hr>\n\n<p>Rather than pushing back pairs over and over again, I would take advantage of <code>vector</code>'s values constructor and <code>std::pair</code>'s default constructor:</p>\n\n<pre><code>std::vector&lt;std::pair&lt;int, int&gt; &gt; attendees(numAttendees);\nfor (int i = 0; i &lt; numAttendees; ++i) {\n if (!(cin &gt;&gt; attendees[i].first &gt;&gt; attendees[i].second)) {\n return 1;\n }\n}\n</code></pre>\n\n<p>Not only with this have a bit better performance (since it doesn't have to keep resizing the vector), it is a bit cleaner. (If the pair default ctor actually turns out to be expensive, you could use <code>reserve()</code> to avoid the vector resizing but still allow you to use <code>make_pair</code> to avoid the default construction of each pair.)</p>\n\n<hr>\n\n<p>Is your input guaranteed to be sorted? If not, you need to either sort or scan over the entire data set rather than starting at <code>i + 1</code>.</p>\n\n<hr>\n\n<p>This comes down to opinion, but I find space around operators (e.g. <code>i+1</code> as <code>i + 1</code>) much easier to read. For example <code>for (int i = 0; i &lt; n; ++i)</code> vs <code>for(int i=0; i&lt;n; ++i)</code>.</p>\n\n<hr>\n\n<p>You need to include <code>utility</code> for pair, I believe.</p>\n\n<hr>\n\n<p>Whenever you have a deep nesting of loops, it's typically a sign that something should be pulled into a function. For example, I would pull the <code>for(int j = i+1; ...)</code> part of the loop into a function called <code>countInvolvedAttendees</code> (or something hopefully better named -- I'm drawing a blank).</p>\n\n<hr>\n\n<p><code>std::pair</code> is a double edged sword. It's very, very convenient for holding <em>any</em> pair, but it's generality is also it's downfall. In particular, it basically murders decent naming. When I see a <code>std::pair&lt;int, int&gt;</code>, I have no idea what in the world the two ints are at all. Compare that to a <code>Attendee</code> that has a <code>seatPosition</code> and <code>voiceDistance</code>, and suddenly the meanings are very clear. Unfortunately though, creating a custom struct or class for this seems a bit overkill. </p>\n\n<p>What I'm trying to get across is please be mindful of the problem of <code>std::pair</code>'s vagueness. In all but the simplest of circumstances, it's typically better to create something with proper names. Otherwise, it's too easy to get caught up in <code>first</code> and <code>second</code> and flip them, forgot what one means, and so on.</p>\n\n<hr>\n\n<p><code>std::endl</code> is a common case of <em>I don't think that does what you think it does</em>.</p>\n\n<p>In particular, <code>std::endl</code> is equivalent to <code>os &lt;&lt; '\\n' &lt;&lt; std::flush;</code>.</p>\n\n<p>For lots of outputting, this constant flushing can be shockingly slow. In cases like this, where you're outputting a giant batch and not responding to human input as it comes, I would use <code>'\\n'</code> instead.</p>\n\n<hr>\n\n<p>Since this is a lot to take in, I might write out a revised version in a bit when I get some more time :).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:14:37.970", "Id": "78369", "Score": "0", "body": "For the i++ comment, I don't think it is still relevant nowadays as any half decent compiler should go for the best option." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:20:52.283", "Id": "78373", "Score": "0", "body": "@Josay it's still worth knowing, even just so you understand the underlying differences. Even when the performance concerns are taken away, I still consider it a minor point of correctness. If you want to do task x, but you're actually doing x + y, that's not quite the same thing. And I'm one of *those* people who doesn't like to assume certain optimization a will be made :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:47:29.630", "Id": "78389", "Score": "0", "body": "That's fair enough :-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T18:46:15.973", "Id": "45000", "ParentId": "44998", "Score": "11" } }, { "body": "<p><strong>Introduction</strong></p>\n\n<p>Dynamic programming is applicable to this problem, but unfortunately, it's still quadratic (though a significantly lesser quadratic in the usual case).</p>\n\n<hr>\n\n<p>If you're curious, what tipped me off to DP is the one-directional dependency. In other words, if the voices could go in both directions rather than just forward, dynamic programming would not be possible since a pleasant recurrence relation could not be found.</p>\n\n<p>I've assumed that you've used dynamic programming before and are familiar with it. If you are not, please let me know, and I will try to explain it in more detail.</p>\n\n<hr>\n\n<p><strong>Problem Consideration</strong></p>\n\n<p>Let's consider the formulation of the problem for a second:</p>\n\n<p>There are <code>n</code> people sitting at a table. Each person <code>i</code> (<code>1 &lt;= i &lt;= n</code>) is sitting at seat <code>x(i)</code>, and each person has a voice volume <code>t(i)</code>. A volume of <code>t</code> means that the speaker's voice can reach at most <code>t</code> seats (not people) directly. In other words, if a person is at seat 3 with a volume of 5, he can talk to everyone in between his own seat and seat 8 (including seat 8).</p>\n\n<p>A conversation is started by a person <code>p</code>, and it can consist of all people be reached by <code>p</code>, including through intermediary speakers. In other words, if <code>p</code> is at seat 3, and has a volume of 5, a person at seat 9 cannot hear him. If, however, someone is sitting at seat 5 with a volume of 5, <code>p</code> can talk to seat <code>9</code> by way of the person in seat <code>5</code> (since <code>5 + 5 = 10; 10 &gt;= 9</code>).</p>\n\n<p><strong>Note:</strong> I have used 1-indexing rather than 0-indexing.</p>\n\n<hr>\n\n<p>Ok, so why am I wording it like this? Notice that there is a recursive relation here. <code>p</code> can talk to anyone whom the people <code>p</code> can talk to directly can talk to. In other words, for each person <code>q</code>, if <code>p</code> can talk to <code>q</code>, then <code>p</code> can also talk to all people to whom <code>q</code> can speak. Like wise, for each person <code>r</code>, if <code>q</code> can speak to them, <code>q</code> can speak to all of the people they can speak to.</p>\n\n<p>In more natural terms, if Mark can talk to Jon and Jon can talk to Steve, then Mark can talk to Steve and everyone to whom Steve can talk. </p>\n\n<hr>\n\n<p><strong>Informal Solution</strong></p>\n\n<p>Let's formulate this in English and then we'll formulate it mathematically.</p>\n\n<p>In short, the maximum number of people that person <code>i</code> can speak with is the maximum number of people that the people he can directly speak with can speak with.</p>\n\n<p>Imagine that <code>i</code> can speak directly with <code>j</code>, <code>k</code>, and <code>m</code>. There are three options:</p>\n\n<p>1) j can speak with the most people\n 2) k can speak with the most people\n 3) m can speak with the most people</p>\n\n<p>Note that picking <em>j</em> must implicitly include <em>k</em> (if you don't see why, ask me).</p>\n\n<p>So, if you pick each option, <code>i</code> can speak with this many people:</p>\n\n<p>1) 1 (since <code>i</code> can speak to himself) + the number of people with whom j can speak\n 2) 2 + the number of people with whom k can speak. The addition of two instead of is necessary since k's people do not include <code>j</code>, but <code>i</code> can obviously speak with <code>j</code>.\n 3) 3 + the number of people with whom m can speak. Same logic: j, k, and all of the people with whom m can speak (including m)</p>\n\n<p>Or, in general, for each person, <code>p</code>, to whom <code>i</code> can talk you must consider to how many people <code>p</code> can talk, and add it to the number of people that are between <code>i</code> and <code>p</code>. The maximum of this is the choice you should make.</p>\n\n<hr>\n\n<p>So, now we should be asking ourselves what the base case is.</p>\n\n<p>The last person can only speak to himself as there is no one past him. This is our base case, and thus our dyamic programming loop will start at the end of all of the people and go back to the beginning.</p>\n\n<hr>\n\n<p><strong>Formal Solution</strong></p>\n\n<p>Let's formulate this a bit more mathematically now.</p>\n\n<p>For the sake of ease, let's consider a different perspective of the same data: how many people could chair <code>c</code> talk to?</p>\n\n<ul>\n<li>Let <code>m(c)</code> be the number of people to whom chair <code>c</code> can speak.</li>\n<li>Let <code>v(c)</code> be the number of chairs that c can reach directly.</li>\n<li><p>Let <code>f(c, d)</code> be the number of occupied chairs between c and d, exclusive.</p>\n\n<p>If chair <code>c</code> is empty, <code>m(c) = 0</code>\nIf chair <code>c</code> is the last chair, <code>m(c) = 1\nOtherwise,</code>m(c) = 1 + max{f(c, j) + m(c + j)} for 1 &lt;= j &lt;= v(c)`</p></li>\n</ul>\n\n<p>Let's break down the third case, since it's a bit complicated:</p>\n\n<ul>\n<li>We have 1 since <code>c</code> can always talk to itself if it's non-empty.</li>\n<li><code>f(c + 1, j - 1)</code> is the number of occupied chairs between i and j, not including i or j. This is necessary since <code>c</code> can obviously talk to all of the people between it and <code>j</code> (if it can talk to <code>j</code>), but picking chair <code>j</code> does not count all of these people.</li>\n<li><code>m(c + j)</code> is the recursive (or dynamic programming). It is just the number of people to whom chair <code>c + j</code> can speak. Note that this will always just be a constant-time look up since all <code>m(d)</code> are already known for <code>d &gt; c</code>.</li>\n<li>Ranging from <code>1 to v(c)</code> is necessary so we consider every chair to which chair <code>c</code> can speak.</li>\n</ul>\n\n<hr>\n\n<p>That was easy to formulate, but unfortunately, with up to a billion chairs, it's not very feasible. Instead, we need to formulate it in terms of person <code>i</code> rather than chair <code>c</code>. Luckily, this is pretty easy. The last person can only talk to 1 person. For every other person, just use similar logic as to the chairs, but be careful to hop from person to person rather than from chair to chair.</p>\n\n<hr>\n\n<p><strong>Run time analysis</strong></p>\n\n<p>Unfortunately, now that we've done all of this work, if we stop and think about it, we'll see that this is still quadratic. In the worst case, we must consider every person between the person of question and the last person.</p>\n\n<p>In the non-worst case though, this will handily performance better (asymtotically anyway) than your solution. Your solution keeps going through people until it can no longer reach a person at all. This solution only goes through only people it can reach directly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T10:31:59.777", "Id": "78498", "Score": "0", "body": "Very nice, these were my initial thoughts, but now I think I've got an O(n log n) solution. I'll try to formulate it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T11:06:09.327", "Id": "78503", "Score": "1", "body": "Forget about the previous comment. I now saw the solution by [kkongas](http://codereview.stackexchange.com/a/45073/39083)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T22:59:26.343", "Id": "45042", "ParentId": "44998", "Score": "7" } }, { "body": "<p>Instead of a vector of pairs, use a map. After all, you are guaranteed that no two members will occupy the same seat.</p>\n\n<p>I found your variable names infuriating: <code>a</code>, <code>b</code>, <code>c</code>, <code>r</code>. Surely you could use more descriptive names.</p>\n\n<pre><code>void process(const std::map&lt;int, int&gt; &amp;seatVoice) {\n for (int i = 0; i &lt; seatVoice.size(); i++) {\n std::map&lt;int, int&gt;::const_iterator it = std::next(seatVoice.begin(), i);\n int range = it-&gt;first;\n int members = 0;\n do {\n int seat = it-&gt;first;\n int voice = it-&gt;second;\n if (seat &gt; range) {\n break;\n }\n members++;\n range = std::max(range, seat + voice);\n } while (++it != seatVoice.end());\n std::cout &lt;&lt; members &lt;&lt; std::endl;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:30:53.950", "Id": "78424", "Score": "0", "body": "Wow, +1! I don't know why a map didn't occur to me in my dynamic programming algorithm. That would allow the chair-wise algo instead of the much more complicated person one with a minimal performance hit." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T23:29:18.953", "Id": "45044", "ParentId": "44998", "Score": "5" } }, { "body": "<p>Here the first element is denoted as <code>0</code>-th and last as <code>N-1</code>-th.</p>\n\n<h2>Algorithm description</h2>\n\n<p>For each element, we can memorize an additional integer: <code>skip[i]</code>, initially <code>skip[i] = i + 1</code>. <code>skip[i]</code> points to the next person that has to be considered, when somebody before <code>i</code> is figuring out the total number of people who can hear him. For example, if there are people 0, 1, 2, 3 and it has already been figured out that 1's voice can reach 2, but not 3, then <code>skip[1] = 3</code> (not 2). So if 0's voice already reaches 1, there is no need to consider whether 2 can also be reached. The algorithm can straight move from 1 to <code>skip[1] = 3</code>-th person.</p>\n\n<p>Also we define <code>K[i] = L[i] + x[i]</code> for each element, the last place where voice of this person can be heard.</p>\n\n<p>The dynamic programming outer loop goes from <code>i = N - 1</code> to <code>0</code>. The algorithm also has an inner loop, like this:</p>\n\n<pre><code>for (int j = i; j &lt; N &amp;&amp; x[j] &lt;= K[i]; j = skip[j]){\n K[i] = max(K[i], K[j]);\n skip[i] = skip[j];\n}\n</code></pre>\n\n<p>The next time someone's voice would already reach <code>i</code>-th, the voice would also reach everybody before <code>skip[i]</code>-th. Thus next time, we straight go from <code>i</code> to <code>skip[i]</code>. Outer loop ends here.</p>\n\n<p>In the end, the answer for k-th person is simply <code>skip[k] - k</code>.</p>\n\n<hr>\n\n<h2>Proof for O(N) time complexity</h2>\n\n<p>Proof for the linear running time:</p>\n\n<p>Observe the sequence</p>\n\n<pre><code>(skip[0], skip[skip[0]], ..., skip[..skip[0]..] = N)\n</code></pre>\n\n<p>(the sequence will always end with <code>N</code>)</p>\n\n<p>Initially it is <code>(1, 2, ..., N)</code>. Each time the inner for loop is executed more than once, one element is skipped from the sequence <code>(skip[0], skip[skip[0]], ..., skip[..skip[0]..] = N)</code> and it will become shorter by exactly one. So the maximal number of inner loop executions during the total execution of the algorithm increases with O(N). Thus total running time complexity is O(N).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T11:04:58.790", "Id": "78502", "Score": "1", "body": "Excellent! I was thinking of an O(n log n) solution but you saved me the effort!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T09:27:15.053", "Id": "45073", "ParentId": "44998", "Score": "6" } }, { "body": "<h1>Typedefs as an alternative to new types</h1>\n\n<p>As others have mentioned, single letter variables are a detriment to readability. One way to help this is of course to add new types. As <em>Corbin</em> mentioned, adding a class or struct to hold just two ints can be a bit overkill (personally I don't mind). I'm not sure if this is considered good practice, but what I do in these situations is to create an alias:</p>\n\n<pre><code>typedef int seat;\ntypedef int voice;\ntypedef std::pair&lt;seat, voice&gt; scientist;\n</code></pre>\n\n<p>Or using the hash solution:</p>\n\n<pre><code>typedef std::map&lt;seat, voice&gt; congress;\n</code></pre>\n\n<p>Some editors may even help you by showing the type of the alias, rather than the underlying type.</p>\n\n<h1>Extracting code to functions to improve singularity of purpose</h1>\n\n<p>Finally, as has been mentioned before, it's helpful to extract each level of nesting into a little function. Not only is it easier on the eye, you can give each extracted piece of code it's own name. That helps to reason about what each step in an algorithm is doing as well.</p>\n\n<p>For example the first for loop is really just initializing a big old vector. I would move that whole loop into a function called <code>parse_input</code> or something and then move the second big loop into a function called <code>calculate_number_of_people_participating</code> or something a little snappier. And then maybe even have it return a new list or perhaps update its input and extract the printing section (<code>cout &lt;&lt; r &lt;&lt; endl;</code>) to a different function as well. I know that its not quite as compact and also slightly (but not in a big OhO sort of way) inefficient, but it separates each section of code into what is logically doing. Some pseudo code to illustrate:</p>\n\n<pre><code>typedef int seat;\ntypedef int voice;\ntypedef std::map&lt;seat, voice&gt; scientists;\n\nscientists parse_input();\nint calculate_people_participating(const scientists&amp; participants);\nvoid print_people_participating(int number);\n\nint main() {\n participants = parse_input();\n number_of_people_participating = calculate_people_participating(participants);\n print_people_participating(number_of_people_participating);\n return 0;\n}\n</code></pre>\n\n<p>Probably the names are a bit too verbose* and your algorithm may not make them quite as appropriate, but I hope you get the idea.</p>\n\n<p>* I don't mind long names for top level functions you call only once. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T16:35:00.573", "Id": "45697", "ParentId": "44998", "Score": "2" } } ]
{ "AcceptedAnswerId": "45000", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:57:27.957", "Id": "44998", "Score": "11", "Tags": [ "c++", "complexity" ], "Title": "Refactoring my problem-solution to reduce complexity" }
44998
<p>I have a map of objects and errors associated with those objects.</p> <p>I have to do the following:</p> <ol> <li>populate the errors in the object</li> <li><p>populate errors for valid objects based on the following:</p> <ul> <li>check the indicator property in the object ( Y | N | other )</li> <li>if all have Y and if there are invalid records - need to reject all</li> </ul></li> </ol> <p>Scenario 1: if there are records with different indicators, then get all the valid records if any ( i.e., no errors associated with them ) and set the error description to inconsistent indicator.</p> <p>Scenario 2: if all the records have indicator as Y and if there are any invalid records then get all the valid records if any and set the error description to rejected because indicator is set to Y.</p> <hr> <p>The following is a working code. How can I improve this further? I feel like I am looping the list more times than required.</p> <pre><code>private List&lt;SomeClazz&gt; populateBeansWithErrors(final Map&lt;SomeClazz, Errors&lt;String&gt;&gt; errorsMap) throws FinancialsSystemRuntimeException { final List&lt;SomeClazz&gt; someObjs = new ArrayList&lt;&gt;(); for ( final Entry&lt;SomeClazz, Errors&lt;String&gt;&gt; entry : errorsMap.entrySet() ) { SomeClazz someObj = entry.getKey(); final Errors&lt;String&gt; errors = entry.getValue(); populateErrorColumns(someObj, errors); someObjs.add(someObj); } checkAndSetErrorColumnsForValidRecords(someObjs); return someObjs; } private void checkAndSetErrorColumnsForValidRecords(final List&lt;SomeClazz&gt; someObj) { //split list into sub-lists based on the indicator. final List&lt;SomeClazz&gt; beansWithIndicatorY = new ArrayList&lt;&gt;(); final List&lt;SomeClazz&gt; beansWithIndicatorN = new ArrayList&lt;&gt;(); final List&lt;SomeClazz&gt; beansWithIndicatorNotValid = new ArrayList&lt;&gt;(); filterListPredicatesOnAllOrNoneIndicator(someObj, beansWithIndicatorY, beansWithIndicatorN, beansWithIndicatorNotValid); String errorDescription = IndicatorValidator.INCONSISTENT_INDICATOR; //if there are records with different indicators //then get all the valid records if any //and set the error description to inconsistent indicator. final List&lt;SomeClazz&gt; validRecords = new ArrayList&lt;&gt;(); if(beansWithIndicatorN.size() &gt; 0) { boolean extractValidN = false; if(beansWithIndicatorY.size() &gt; 0) { validRecords.addAll(getValidRecords(beansWithIndicatorY)); extractValidN = true; } else if(beansWithIndicatorNotValid.size() &gt; 0) { extractValidN = true; } if(extractValidN) { validRecords.addAll(getValidRecords(beansWithIndicatorN)); } } else if(beansWithIndicatorY.size() &gt; 0) { boolean extractValidY = false; if(beansWithIndicatorNotValid.size() &gt; 0) { extractValidY = true; } else { //if all the records have indicator as Y //and if there are any invalid records //then get all the valid records if any //and set the error description to rejected because indicator is set to Y. final List&lt;SomeClazz&gt; invalidYRecords = getInvalidRecords(beansWithIndicatorY); if(invalidYRecords.size() &gt; 0) { extractValidY = true; errorDescription = IndicatorValidator.REJECTED_INDICATOR_IS_Y; } } if(extractValidY) { validRecords.addAll(getValidRecords(beansWithIndicatorY)); } } populateErrorColumnsForValidRecords(errorDescription, validRecords); } private void filterListPredicatesOnAllOrNoneIndicator( @NotNull final List&lt;SomeClazz&gt; someObj, @NotNull final List&lt;SomeClazz&gt; beansWithIndicatorY, @NotNull final List&lt;SomeClazz&gt; beansWithIndicatorN, @NotNull final List&lt;SomeClazz&gt; beansWithIndicatorNotValid) { for(SomeClazz someObj : someObj) { if(StringUtils.equalsIgnoreCase(SomeClazz.getAllOrNoneIndicator(), INDICATOR_IS_Y)) { beansWithIndicatorY.add(someObj); } else if(StringUtils.equalsIgnoreCase(SomeClazz.getAllOrNoneIndicator(), INDICATOR_IS_N)) { beansWithIndicatorN.add(someObj); } else { beansWithIndicatorNotValid.add(someObj); } } } private List&lt;SomeClazz&gt; getInvalidRecords(final List&lt;SomeClazz&gt; someObj) { return select(someObj, having(on(SomeClazz.class).getStatus(), equalTo(CollateralTransactionReportStatus.REJECTED.name()))); } private List&lt;SomeClazz&gt; getValidRecords(final List&lt;SomeClazz&gt; someObj) { return select(someObj, having(on(SomeClazz.class).getStatus(), isEmptyOrNullString())); } private void populateErrorColumnsForValidRecords(final String errorDescription, final List&lt;SomeClazz&gt; validRecords) { for(final SomeClazz validRecord : validRecords) { validRecord.getErrors().add(errorDescription); } } private void populateErrorColumns(final SomeClazz someObj, final Errors&lt;String&gt; errors) { if(errors.hasErrors()) { someObj.setErrors(errors.getErrorDescriptions()); Logger.info("Validation errors exist in the file for row {}", someObj.toString()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T18:40:16.863", "Id": "78347", "Score": "0", "body": "How many records are we talking about here? more than 10, more than 100 more than 10,000 or more than 1,000,000 ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T18:44:50.533", "Id": "78348", "Score": "0", "body": "number of records can be upto 10,000. Also, this can process multiple files at the same time in different threads." } ]
[ { "body": "<p>Just a few generic notes:</p>\n\n<ol>\n<li><p>I guess you're using SLF4J here:</p>\n\n<blockquote>\n<pre><code>Logger.info(\"Validation errors exist in the file for row {}\", someObj.toString());\n</code></pre>\n</blockquote>\n\n<p>The <code>toString()</code> call is unnecessary, SLF4J will call it for you (and it will call only if you have enabled info level logging).</p>\n\n<pre><code>Logger.info(\"Validation errors exist in the file for row {}\", someObj);\n</code></pre></li>\n<li><p>I wouldn't go with <code>size()</code> here:</p>\n\n<blockquote>\n<pre><code>if(beansWithIndicatorN.size() &gt; 0) {\n</code></pre>\n</blockquote>\n\n<p><code>!isEmpty</code> would be a little bit easier to read and closer to English:</p>\n\n<blockquote>\n<pre><code>if (!beansWithIndicatorN.isEmpty()) {\n</code></pre>\n</blockquote></li>\n<li><p>For naming here:</p>\n\n<blockquote>\n<pre><code>private List&lt;SomeClazz&gt; populateBeansWithErrors(final Map&lt;SomeClazz, Errors&lt;String&gt;&gt; errorsMap)\n throws FinancialsSystemRuntimeException {\n final List&lt;SomeClazz&gt; someObjs = new ArrayList&lt;&gt;();\n ...\n return someObjs;\n}\n</code></pre>\n</blockquote>\n\n<p>I'd rename to <code>someObjs</code> to <code>result</code> to express its purpose.</p></li>\n<li><p>The name of the following variables are too similar to each other:</p>\n\n<pre><code>beansWithIndicatorY\nbeansWithIndicatorN\nbeansWithIndicatorNotValid\n</code></pre>\n\n<p>I'd try to choose something which is easier to tell each other apart, like: <code>yesBeans</code>, <code>noBeans</code>, <code>invalidBeans</code>.</p></li>\n<li><p>I supposed that the <code>someObj</code> parameter should be <code>someObjs</code>:</p>\n\n<blockquote>\n<pre><code>private void filterListPredicatesOnAllOrNoneIndicator(\n @NotNull final List&lt;SomeClazz&gt; someObj,\n @NotNull final List&lt;SomeClazz&gt; beansWithIndicatorY,\n @NotNull final List&lt;SomeClazz&gt; beansWithIndicatorN,\n @NotNull final List&lt;SomeClazz&gt; beansWithIndicatorNotValid) {\n\n for(SomeClazz someObj : someObj) {\n if(StringUtils.equalsIgnoreCase(SomeClazz.getAllOrNoneIndicator(), INDICATOR_IS_Y)) {\n beansWithIndicatorY.add(someObj);\n } else if(StringUtils.equalsIgnoreCase(SomeClazz.getAllOrNoneIndicator(), INDICATOR_IS_N)) {\n beansWithIndicatorN.add(someObj);\n } else {\n beansWithIndicatorNotValid.add(someObj);\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Are you sure that the loop is correct here? The inner conditions don't depend on the iterated value, so if <code>SomeClazz.getAllOrNoneIndicator()</code> doesn't change on its subsequent calls, the following is the same:</p>\n\n<pre><code> private void filterListPredicatesOnAllOrNoneIndicator(\n @NotNull final List&lt;SomeClazz&gt; someObjs,\n @NotNull final List&lt;SomeClazz&gt; beansWithIndicatorY, \n @NotNull final List&lt;SomeClazz&gt; beansWithIndicatorN,\n @NotNull final List&lt;SomeClazz&gt; beansWithIndicatorNotValid) {\n\n if (StringUtils.equalsIgnoreCase(SomeClazz.getAllOrNoneIndicator(), INDICATOR_IS_Y)) {\n beansWithIndicatorY.addAll(someObjs);\n } else if (StringUtils.equalsIgnoreCase(SomeClazz.getAllOrNoneIndicator(), INDICATOR_IS_N)) {\n beansWithIndicatorN.addAll(someObjs);\n } else {\n beansWithIndicatorNotValid.addAll(someObjs);\n }\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T06:25:57.900", "Id": "78706", "Score": "1", "body": "agree with all of them, but, I would like to mention a mistake that I made when refactoring my code to paste in stackoverflow. So, #5 is because of improper refactoring. But, thanks for your suggestion." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T06:10:19.330", "Id": "45063", "ParentId": "44999", "Score": "4" } } ]
{ "AcceptedAnswerId": "45063", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T18:26:40.503", "Id": "44999", "Score": "6", "Tags": [ "java" ], "Title": "Populate errors for objects" }
44999
<p>I'm reading/writing half precision floating point numbers in C#. These are basically 16 bit floats, compared to the usual 32/64 bit floats and doubles we are used to working with.</p> <p>I've taken some highly tested Java code from an obvious "expert on the subject" <a href="https://stackoverflow.com/a/6162687/1294758">here</a> and modified it to work with C#. Is this correct?</p> <pre><code>// ignores the higher 16 bits public static float toFloat( int hbits ) { int mant = hbits &amp; 0x03ff; // 10 bits mantissa int exp = hbits &amp; 0x7c00; // 5 bits exponent if( exp == 0x7c00 ) // NaN/Inf exp = 0x3fc00; // -&gt; NaN/Inf else if( exp != 0 ) // normalized value { exp += 0x1c000; // exp - 15 + 127 if( mant == 0 &amp;&amp; exp &gt; 0x1c400 ) // smooth transition return BitConverter.ToSingle(BitConverter.GetBytes( ( hbits &amp; 0x8000 ) &lt;&lt; 16 | exp &lt;&lt; 13 | 0x3ff ), 0); } else if( mant != 0 ) // &amp;&amp; exp==0 -&gt; subnormal { exp = 0x1c400; // make it normal do { mant &lt;&lt;= 1; // mantissa * 2 exp -= 0x400; // decrease exp by 1 } while( ( mant &amp; 0x400 ) == 0 ); // while not normal mant &amp;= 0x3ff; // discard subnormal bit } // else +/-0 -&gt; +/-0 return BitConverter.ToSingle(BitConverter.GetBytes( // combine all parts ( hbits &amp; 0x8000 ) &lt;&lt; 16 // sign &lt;&lt; ( 31 - 15 ) | ( exp | mant ) &lt;&lt; 13 ), 0); // value &lt;&lt; ( 23 - 10 ) } // returns all higher 16 bits as 0 for all results public static int fromFloat( float fval ) { int fbits = BitConverter.ToInt32(BitConverter.GetBytes(fval), 0); int sign = fbits &gt;&gt;&gt; 16 &amp; 0x8000; // sign only int val = ( fbits &amp; 0x7fffffff ) + 0x1000; // rounded value if( val &gt;= 0x47800000 ) // might be or become NaN/Inf { // avoid Inf due to rounding if( ( fbits &amp; 0x7fffffff ) &gt;= 0x47800000 ) { // is or must become NaN/Inf if( val &lt; 0x7f800000 ) // was value but too large return sign | 0x7c00; // make it +/-Inf return sign | 0x7c00 | // remains +/-Inf or NaN ( fbits &amp; 0x007fffff ) &gt;&gt;&gt; 13; // keep NaN (and Inf) bits } return sign | 0x7bff; // unrounded not quite Inf } if( val &gt;= 0x38800000 ) // remains normalized value return sign | val - 0x38000000 &gt;&gt;&gt; 13; // exp - 127 + 15 if( val &lt; 0x33000000 ) // too small for subnormal return sign; // becomes +/-0 val = ( fbits &amp; 0x7fffffff ) &gt;&gt;&gt; 23; // tmp exp for subnormal calc return sign | ( ( fbits &amp; 0x7fffff | 0x800000 ) // add subnormal bit + ( 0x800000 &gt;&gt;&gt; val - 102 ) // round depending on cut off &gt;&gt;&gt; 126 - val ); // div by 2^(1-(exp-127+15)) and &gt;&gt; 13 | exp=0 } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T19:58:42.593", "Id": "78366", "Score": "1", "body": "Does it work? Does it do as you expect?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T04:40:49.733", "Id": "79106", "Score": "0", "body": "Even if it encodes and decodes correctly I'm not an expert in floating point numbers so I won't know if there's a bug in there!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T01:50:16.303", "Id": "79824", "Score": "0", "body": "Do you have any unit tests? I would start there in answering is this correct." } ]
[ { "body": "<blockquote>\n <p>Is this correct?</p>\n</blockquote>\n\n<p>Maybe.</p>\n\n<p>For a start, the <code>&gt;&gt;&gt;</code> operator doesn't exist in C#.</p>\n\n<p>Taking a guess, I replaced <code>&gt;&gt;&gt;</code> with <code>&gt;&gt;</code> and then wrote the following 'unit test' for it:</p>\n\n<pre><code> static void assertFloat(float fval)\n {\n int i = fromFloat(fval);\n float f2 = toFloat(i);\n if (fval != i)\n throw new ApplicationException();\n }\n\n static void Main(string[] args)\n {\n assertFloat(0);\n assertFloat(1);\n assertFloat(0.5f);\n assertFloat(-0.5f);\n assertFloat(-0);\n assertFloat(float.PositiveInfinity);\n assertFloat(float.NaN);\n float big = 1024 * 1024;\n big *= big;\n assertFloat(big);\n }\n</code></pre>\n\n<p>It failed the second test: because <code>1.0</code> is round-trip-converted to <code>1.000122</code>.</p>\n\n<p>I am disappointed by an encoding scheme which cannot encode '1.0' exactly.</p>\n\n<p>However you didn't say how exact you expect the round-trip to be, so I don't know whether it's correct.</p>\n\n<p>The following is a list of some input with corresponding output:</p>\n\n<pre><code>0 -&gt; 0\n1 -&gt; 1.000122\n1.1 -&gt; 1.099609\n-1 -&gt; -1.000122\n0.5 -&gt; 0.500061\n-0.5 -&gt; -0.500061\n0.001 -&gt; 0.001000404\n5.5 -&gt; 5.5\n5.6 -&gt; 5.601563\n5.7 -&gt; 5.699219\n0 -&gt; 0\nInfinity -&gt; Infinity\nNaN -&gt; NaN\n1024 -&gt; 1024.125\n1048576 -&gt; Infinity\n</code></pre>\n\n<p>So it seems approximately correct for those numbers.</p>\n\n<p>I can't say whether it's the best encoding. For example, this encoding gains the ability to express decimals but loses the ability to express integers (they become approximated) and big integers (they become infinity).</p>\n\n<p>A different encoding scheme could be devised (and might be more useful depending on your application) which cannot express decimals but which gains the ability to express (approximately) some numbers which are bigger-than-the-biggest integer.</p>\n\n<hr>\n\n<p>There are a lot of 'magic numbers' (i.e. hard-coded constants) in the code. To inspect for correctness I would need to guess/reverse engineer the way in which you encode/use the 16 bits for your \"half precision float\" numbers. You could make it easier by documenting the format using comments: which bits do you use for what?</p>\n\n<hr>\n\n<p>Note <a href=\"https://stackoverflow.com/questions/6162651/half-precision-floating-point-in-java/6162687#comment15658695_6162687\">this comment in the post you linked to</a>:</p>\n\n<blockquote>\n <p>I see what you mean but these NaN values wont be returned from Float.floatToIntBits which normalizes all NaNs to 0x7fc00000. The rounded val can thus never become nagative. Maybe it would be faster to use floatToRawIntBits (which does not do NaN normalization) and then deal with the overflow NaNs i.e. by adding || val &lt; 0 to the first branch. This would also allow to preserve some of the extra NaN bits. I remember that I had planned to do this but couldn't find sufficient documentation on how to handle these bits and thus settled with normalized NaNs.</p>\n</blockquote>\n\n<p>The <code>BitConverter</code> which you use may not (I haven't tested it) normalize NaN values in the same way.</p>\n\n<hr>\n\n<p>The <a href=\"https://stackoverflow.com/q/6162651/49942\">original OP</a> linked to an spec for <a href=\"http://en.wikipedia.org/wiki/Half_precision_floating-point_format\" rel=\"nofollow noreferrer\">Half-precision floating-point format</a> which says,</p>\n\n<blockquote>\n <p>Integers between 0 and 2048 can be exactly represented</p>\n</blockquote>\n\n<p>So my testing, which shows error in round-tripping <code>1</code>, suggests that this spec is NOT implemented correctly.</p>\n\n<p>When I test it, <code>1.0f</code> is encoded as <code>0x3c00</code> which is correct according to the spec. So the bug is presumably being introduced in the <code>toFloat</code> method, specifically this statement:</p>\n\n<pre><code>return BitConverter.ToSingle(BitConverter.GetBytes( ( hbits &amp; 0x8000 ) &lt;&lt; 16\n | exp &lt;&lt; 13 | 0x3ff ), 0);\n</code></pre>\n\n<p>This is a line which the \"obvious expert on the subject\" said they \"implemented [as a] small extension compared to the book\".</p>\n\n<p>IOW you may have made a translation from the Java, but the Java doesn't correctly/fully implement the spec (it tries to improve on the spec, perhaps resulting in an inability to accurately decode small integers).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T05:47:32.597", "Id": "79842", "Score": "0", "body": "Absolutely mind blowing review! Thanks a ton for your expertise. And yes, the \"small extensions\" can be disabled according to the \"expert\" (\"You can safely remove the lines shown above if you don't want this extension.\") .. see : http://stackoverflow.com/a/6162687/1294758 .. after disabling this extension does the accuracy improve?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T10:03:53.253", "Id": "79863", "Score": "1", "body": "The accuracy improves at `1.0f`: it converts to `1.0f` exactly. You might like to write a set of unit tests to see how well it works at various specific values. You could post that unit-test code as a separate, follow-on question." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T21:06:40.777", "Id": "45709", "ParentId": "45007", "Score": "3" } }, { "body": "<p>The XNA framework provides support for HalfFloats. If you install it you could copy the correct dll into your project.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T04:52:54.100", "Id": "45727", "ParentId": "45007", "Score": "0" } } ]
{ "AcceptedAnswerId": "45709", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T19:07:55.540", "Id": "45007", "Score": "3", "Tags": [ "c#", "floating-point" ], "Title": "Half precision reader/writer for C#" }
45007
<p>I recently made a 140-lined Pong game in C# using forms.</p> <p>Since I'm very new to programming, I'd like if somebody would please read it and give me advice on where to improve, what you believe I did wrong and most of all, what should have been done better and how.</p> <p>Plus, would it be somewhat useful to implement delegates somewhere in the code above ? I'm still studying them but found no useful way to implement those yet.</p> <p>Finally, I found no way to use the <code>Dispose()</code> method on the created graphics in the <code>Pong</code> Class without breaking the code. Is it really that useful ? Isn't the garbage collector supposed to do so anyway?</p> <pre><code>namespace WindowsFormsApplication2 { public class PongGame { public static Rectangle paddle1 = new Rectangle(14, 180, 20, 100); public static Rectangle paddle2 = new Rectangle(566, 180, 20, 100); public static Rectangle ball = new Rectangle(290, 115, 16, 16); static Font Drawfont = new Font("Arial", 40); public static bool p1movesUp, p1movesDown, p2movesUp, p2movesDown; public static SolidBrush sb = new SolidBrush(Color.White); public static double p1p; //Double that will store player 1 score public static double p2p; //Double that will store player 2 score static int RandoMin = 1; //Those 2 random integers are used to randomize ball directions static int RandoMax = 3; //in the Randomize() method to avoid repetition of ball movement public static double Xspeed = -1; //Beginning Initial speed public static double Yspeed = 1; public static void DrawIt(Graphics Draw) { //Draws both paddles and ball Draw.Clear(Color.Black); Draw.FillRectangle(sb, paddle2); Draw.FillRectangle(sb, paddle1); Draw.FillRectangle(sb, ball); //Draw Score Draw.DrawString(p1p.ToString(), Drawfont, sb, 180, 10); Draw.DrawString(p2p.ToString(), Drawfont, sb, 380, 10); } public static void CheckIfMoving() //If player press the key to move the paddle, this method { //changes the Y position of the paddle Accordingly if (p1movesUp == true) { int z = paddle1.Y &lt;= 0 ? paddle1.Y = 0 : paddle1.Y -= 3; } if (p1movesDown == true) { int z = paddle1.Y &gt;= 381 ? paddle1.Y = 381 : paddle1.Y += 3; } if (p2movesUp == true) { int z = paddle2.Y &lt;= 0 ? paddle2.Y = 0 : paddle2.Y -= 3; } if (p2movesDown == true) { int z = paddle2.Y &gt;= 381 ? paddle2.Y = 381 : paddle2.Y += 3; } } public static void Restart() //Method called upon player scoring, to reset speed values { //and ball position ball.X = 290; Yspeed = 1; ball.Y = 115; RandoMin = 1; Xspeed = -1; RandoMax = 3; } public static void CheckScore() //Check if any player has scored, and increase p1p accordingly { if (ball.X &lt; 1) { p2p += 1; Restart(); } else if (ball.X &gt; 579) { p1p += 1; Restart(); } } public static void IncreaseSpeed() //Increase both the normal speed and the results of { //any possible randomization in the Randomize() method RandoMin += 1; RandoMax += 1; Xspeed = Xspeed &lt; 0 ? Xspeed -= 1 : Xspeed += 1; } public static void MoveBall(Timer t1) { ball.X += (int)Xspeed; //Changes ball coordinates based on speed in both x &amp; y axis ball.Y += (int)Yspeed; if (ball.Y &gt; 465 || ball.Y &lt; 0) { Yspeed = -Yspeed; } //If ball touch one of the Y bounds, it's y speed gets a change in sign, and ball rebounce if (ball.X &gt; 579 || ball.X &lt; 1) { Xspeed = -Xspeed; } //Same for X bounds, with x speed if (ball.IntersectsWith(paddle1) || ball.IntersectsWith(paddle2)) { int dst = paddle1.Y + 100; int Distance = dst - ball.Y; if (Distance &gt; 75 || Distance &lt; 25) { Randomize(); } //If the ball intersects the paddle "away" from the centre, the ball movement get randomized else { Xspeed = -Xspeed; } //else, it's speed on the X axis gets simply reverted } } static void Randomize() { Random r = new Random(); double s = r.Next(RandoMin, RandoMax); //Uses RandoMin &amp; RandoMax values to randomize the X speed of the ball Xspeed = ball.IntersectsWith(paddle1) ? Xspeed = s : Xspeed = -s; if (Yspeed &lt; 0) //If ball is moving upward, (so y speed is negative) the random value assigned { //will be changed in sign, so the ball can still go upward double t = r.Next(RandoMin, RandoMax); Yspeed = -t; } else //Else, directly change the Y speed to a positive value { Yspeed = r.Next(RandoMin, RandoMax); } } //End of PongGame Class } public partial class Form1 : Form { Graphics Draw; SolidBrush sb = new SolidBrush(Color.White); public Form1() { InitializeComponent(); pictureBox1.BackColor = Color.Black; Draw = pictureBox1.CreateGraphics(); timer1.Interval = 10; timer1.Start(); timer2.Start(); } private void timer1_Tick(object sender, EventArgs e) { PongGame.DrawIt(Draw); //Draws paddles &amp; ball PongGame.MoveBall(timer1); //Moves the ball PongGame.CheckScore(); //Check if one player scored PongGame.CheckIfMoving(); //Method that check if player is moving up or down the paddle } private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.S) { PongGame.p1movesDown = true; } if (e.KeyData == Keys.W) { PongGame.p1movesUp = true; } if (e.KeyData == Keys.L) { PongGame.p2movesDown = true; } if (e.KeyData == Keys.P) { PongGame.p2movesUp = true; } } private void Form1_KeyUp(object sender, KeyEventArgs e) { if (e.KeyData == Keys.S) { PongGame.p1movesDown = false; } if (e.KeyData == Keys.W) { PongGame.p1movesUp = false; } if (e.KeyData == Keys.L) { PongGame.p2movesDown = false; } if (e.KeyData == Keys.P) { PongGame.p2movesUp = false; } } private void timer2_Tick(object sender, EventArgs e) { PongGame.IncreaseSpeed(); } //Every 3 seconds, this timer will increase Overall speed } } </code></pre>
[]
[ { "body": "<p>Here are a few observations:</p>\n\n<ol>\n<li><p>In <code>Form1_KeyDown</code> and <code>Form1_KeyUp</code>, the logic would be cleaner organized into a <code>switch</code> statement:</p>\n\n<pre><code>private void Form1_KeyDown(object sender, KeyEventArgs e)\n{\n switch (e.KeyData)\n {\n case Keys.S:\n PongGame.p1movesDown = true;\n return;\n case Keys.W:\n PongGame.p1movesUp = true;\n return;\n case Keys.L:\n PongGame.p2movesDown = true;\n return;\n case Keys.P:\n PongGame.p2movesUp = true;\n return;\n }\n}\n\nprivate void Form1_KeyUp(object sender, KeyEventArgs e)\n{\n switch (e.KeyData)\n {\n case Keys.S:\n PongGame.p1movesDown = false;\n return;\n case Keys.W:\n PongGame.p1movesUp = false;\n return;\n case Keys.L:\n PongGame.p2movesDown = false;\n return;\n case Keys.P:\n PongGame.p2movesUp = false;\n return;\n }\n}\n</code></pre></li>\n<li><p>In <code>CheckIfMoving</code>, a variable <code>z</code> is declared just to use a bizarre version of the ternary operator (<code>?:</code>). This should be rewritten to do what you actually want rather than trying to be clever:</p>\n\n<pre><code>public static void CheckIfMoving()\n{\n // If player press the key to move the paddle, this method\n // changes the Y position of the paddle Accordingly\n if (p1movesUp)\n {\n if (paddle1.Y &lt;= 0)\n {\n paddle1.Y = 0;\n }\n else\n {\n paddle1.Y -= 3;\n }\n }\n\n if (p1movesDown)\n {\n if (paddle1.Y &gt;= 381)\n {\n paddle1.Y = 381;\n }\n else\n {\n paddle1.Y += 3;\n }\n }\n\n if (p2movesUp)\n {\n if (paddle2.Y &lt;= 0)\n {\n paddle2.Y = 0;\n }\n else\n {\n paddle2.Y -= 3;\n }\n }\n\n if (p2movesDown)\n {\n if (paddle2.Y &gt;= 381)\n {\n paddle2.Y = 381;\n }\n else\n {\n paddle2.Y += 3;\n }\n }\n}\n</code></pre></li>\n<li><p>\"I found no way to use the <code>Dispose()</code> method on the created graphics in the <code>Pong</code> Class without breaking the code. Is it really that useful? Isn't the garbage collector supposed to do so anyway?\"</p>\n\n<p>This is comparing apples and oranges, but don't feel bad! Many people mix up or conflate <code>Dispose()</code> with the garbage collector. Sometimes they're intertwined, many times they are not. The very simple rule of thumb is - if a class implements <code>IDisposable</code>, call <code>Dispose()</code> at some point. Period. Deep down in the bowels of that class (or one that it has as a member), a non-.NET unmanaged resource is being used. <code>Dispose()</code> ensures that resource is returned in a deterministic fashion. I highly suggest reading and understanding <a href=\"https://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface/538238#538238\">this answer</a>. </p>\n\n<p>So, how do you fix this? Simple. The other <code>partial</code> part of your <code>Form1</code> class has a <code>Dispose()</code> method. It usually looks something like this:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Clean up any resources being used.\n/// &lt;/summary&gt;\n/// &lt;param name=\"disposing\"&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt;\nprotected override void Dispose(bool disposing)\n{\n if (disposing &amp;&amp; (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n}\n</code></pre>\n\n<p>Add the following:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Clean up any resources being used.\n/// &lt;/summary&gt;\n/// &lt;param name=\"disposing\"&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt;\nprotected override void Dispose(bool disposing)\n{\n this.Draw.Dispose();\n if (disposing &amp;&amp; (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n}\n</code></pre>\n\n<p>However, that's sorta cheating. You're holding the <code>Graphics</code> object for the lifetime of your application. A better way would be removing <code>Draw</code> as a class member of <code>Form1</code> and using it just around the piece that draws (<code>timer1_Tick</code>). Note that <code>using</code> will call <code>Dispose()</code> at the end of the scope automatically for you:</p>\n\n<pre><code>private void timer1_Tick(object sender, EventArgs e)\n{\n using (Graphics Draw = this.pictureBox1.CreateGraphics())\n {\n PongGame.DrawIt(Draw); // Draws paddles &amp; ball\n }\n\n PongGame.MoveBall(this.timer1); // Moves the ball\n PongGame.CheckScore(); // Check if one player scored\n PongGame.CheckIfMoving(); // Method that check if player is moving up or down the paddle\n}\n</code></pre></li>\n<li><p>Don't continuously redeclare the random number generator in the <code>Randomize</code> method:</p>\n\n<pre><code> Random r = new Random();\n</code></pre>\n\n<p>instead, do it once as a class-level member:</p>\n\n<pre><code> private static readonly Random r = new Random();\n</code></pre>\n\n<p>This will prevent possible duplicate randoms in a short time span.</p></li>\n<li><p>Do all those members of <code>PongGame</code> really need to be <code>public</code>? I'm thinking not. The only members accessed outside that class are <code>p1movesUp</code>, <code>p1movesDown</code>, <code>p2movesUp</code>, and <code>p2movesDown</code>. Even then, I'd make all of them <code>private</code> and instead make those four auto-implemented properties to aid with encapsulation:</p>\n\n<pre><code>public static bool p1movesUp { get; set; }\npublic static bool p1movesDown { get; set; }\npublic static bool p2movesUp { get; set; }\npublic static bool p2movesDown { get; set; }\n</code></pre></li>\n<li><p>Since everything in the <code>PongGame</code> class is <code>static</code>, declare the class statically as well: <code>public static class PongGame</code>. I have some future thoughts about making everything not-so-static, implementing an interface and injecting dependencies, but let's keep it simple for now.</p></li>\n<li><p>I'm a little confused as to the use of <code>double</code>s in the <code>PongGame</code> class. They only contain whole numbers. Do you expect a score to go over two billion? If not, make them all <code>int</code>. Better performance and intent.</p></li>\n</ol>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:40:08.883", "Id": "78441", "Score": "0", "body": "Hi, and thanks for the very detailed answer : ) I got only a question regarding the using statement to call dispose() at the end of it, this way, the program needs to recreate 100 times a seconds the graphics instance... should this be avoided ? And how, possibly ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T18:19:10.437", "Id": "78811", "Score": "0", "body": "@Rphysx I would suggest running it in both configurations under a profiler and noting the differences in time, memory and GC pressure." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:52:20.587", "Id": "45021", "ParentId": "45011", "Score": "12" } } ]
{ "AcceptedAnswerId": "45021", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T19:40:34.497", "Id": "45011", "Score": "13", "Tags": [ "c#", "beginner", "game", "winforms" ], "Title": "Small C# Pong game" }
45011
<p>I have a form that requires a calculation when clicked on a multiple drop down selector, and still displays the clicks of the courses in real time and lastly calculates the sum total of the courses.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; div { color:blue; } div#five { color:red; } div#show_box { background: wheat; width: 120px; height: 100px; } div#total_box { width: 119px; height: 60px; background: pink; margin-top: 20px; } &lt;/style&gt; &lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="one"&gt;&lt;/div&gt; &lt;div id="two"&gt;&lt;/div&gt; &lt;div id="three"&gt;&lt;/div&gt; &lt;div id="four"&gt;&lt;/div&gt; &lt;div id="five"&gt;&lt;/div&gt; &lt;script&gt; var arr = [ "one", "two", "three", "four", "five" ]; var obj = { one:1, two:2, three:3, four:4, five:5 }; jQuery.each(arr, function() { $("#" + this).text("Mine is " + this + "."); return (this != "three"); // will stop running after "three" }); jQuery.each(obj, function(i, val) { $("#" + i).append(document.createTextNode(" - " + val)); }); &lt;/script&gt; &lt;select id="wow" multiple="multiple"&gt; &lt;option id="def" value="default selected"&gt;select a course&lt;/option&gt; &lt;option id="mth" value="1"&gt;math&lt;/option&gt; &lt;option id="eng" value="2"&gt;english&lt;/option&gt; &lt;option id="chm" value="3"&gt;chem&lt;/option&gt; &lt;option id="phy" value="4"&gt;physics&lt;/option&gt; &lt;/select&gt; &lt;div id="show_box"&gt; &lt;h6 id="1"&gt;&lt;/h6&gt; &lt;h6 id="2"&gt;&lt;/h6&gt; &lt;h6 id="3"&gt;&lt;/h6&gt; &lt;h6 id="4"&gt;&lt;/h6&gt; &lt;h6 id="5"&gt;&lt;/h6&gt; &lt;/div&gt; &lt;div id="total_box"&gt; &lt;/div&gt; &lt;script&gt; //list all the view more in the clicks into arrays... var vm_id=[1,2,3,4,5]; jQuery.each(vm_id, function() { //$('button[value="' + this + "]') $('option[value="' + this + '"]').one('click',function() { //this.value var price=["2000","3000","4000","5000","6000"]; if (this.value == 1) { $('#show_box &gt; #1').html(price[0]); $('#1').after("&lt;input type='hidden' id='2000' value=" + price[0] + "&gt;"); /* $('option[value="' + this + '"]').off('click','option[value="' + this + '"]',function() { $('#2000').remove('#2000'); }); */ }; if (this.value == 2) { $('#show_box &gt; #2').html(price[1]); $('#2').after("&lt;input type='hidden' id='3000' value=" + price[1] + "&gt;"); }; if (this.value == 3) { $('#show_box &gt; #3').html(price[2]); $('#3').after("&lt;input type='hidden' id='4000' value=" + price[2] + "&gt;"); }; if (this.value == 4) { $('#show_box &gt; #4').html(price[3]); $('#4').after("&lt;input type='hidden' id='5000' value=" + price[3] + "&gt;"); }; if (this.value == 5) { $('#show_box &gt; #5').html(price[4]); $('#5').after("&lt;input type='hidden' id='6000' value=" + price[4] + "&gt;"); }; //$("input:hidden").length //alert($("input:hidden").length); $("input:hidden").each(function(index,Element) { var sub=$("input:hidden").index(); var in_len=$("input:hidden").length; if ((in_len == 1)) { //var get_id=Element.id; var ids=[1000,2000,3000,4000,5000]; $.each(ids,function(index,value) { var get_id=Element.id; if (get_id == this) { $('#total_box').text(value); //console.log(get_id + ':' + index + '=' + value); }; }); }; if ((in_len == 2)) { var ids=[1000,2000,3000,4000,5000]; $.each(ids,function(index,value) { var get_id=Element.id; if (get_id == this) { var in_len=$("input:hidden"); one=in_len[0].id; two=in_len[1].id; one=parseInt(one); two=parseInt(two); three= one + two; $('#total_box').text(three); //console.log(get_id + ':' + index + '=' + value); }; }); //var get_id=Element.id; /* var ids=[1000,2000,3000,4000,5000]; $.each(ids,function(index,value) { var get_id=Element.id; //console.log(get_id + ':' + index + '=' + value); }); */ }; if ((in_len == 3)) { var ids=[1000,2000,3000,4000,5000]; $.each(ids,function(index,value) { var get_id=Element.id; if (get_id == this) { var in_len=$("input:hidden"); one=in_len[0].id; two=in_len[1].id; three=in_len[2].id; one=parseInt(one); two=parseInt(two); three=parseInt(three); four= one + two + three; $('#total_box').text(four); //console.log(get_id + ':' + index + '=' + value); }; }); }; if ((in_len == 4)) { var ids=[1000,2000,3000,4000,5000]; $.each(ids,function(index,value) { var get_id=Element.id; if (get_id == this) { price=[2000,3000,4000,5000,6000]; p1=price[0]; p2=price[1]; p3=price[2]; p4=price[3]; $('#total_box').text(p1+p2+p3+p4); }; }); }; }); }); }); /* $('#mth').click(function() { var wow_val=document.getElementById('mth').value; alert(wow_val); }); */ &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I have solved the problem with this code, but I want to see other ways to solve it from other developers.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:30:34.897", "Id": "78378", "Score": "0", "body": "Could you elaborate on the purpose of the script inside the first <script>-tag and the div-elements before it? Are they relevant to the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:43:55.827", "Id": "78386", "Score": "0", "body": "assuming you have run it you will see that there is a drop down box box with two divs the display div and the total divs. so what really happens is that when the user click on any of the dropdown it shows the price of the course and the total box summates the whole process.. please just show me if there is another way to go about it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T21:11:04.647", "Id": "78397", "Score": "0", "body": "Yes, but above the dropdown there are elements too, that seem to have no relevance in your actual question. I'd suggest only posting the relevant parts here, it makes the answers more relevant too." } ]
[ { "body": "<p>From what I understand, the functionality you want is:</p>\n\n<ul>\n<li>Displaying the prices of all the selected items separately</li>\n<li>Displaying the sum of prices of items that are selected</li>\n</ul>\n\n<p>I'd do this by adding the price information directly to the html option elements, for example as <a href=\"http://ejohn.org/blog/html-5-data-attributes/\" rel=\"nofollow\">HTML5 data-attributes</a>:</p>\n\n<pre><code>&lt;select id=\"wow\" multiple=\"multiple\"&gt;\n &lt;option id=\"def\" value=\"default\" selected&gt;select a course&lt;/option&gt;\n &lt;option id=\"mth\" data-price=\"2000\" value=\"1\"&gt;math&lt;/option&gt;\n &lt;option id=\"eng\" data-price=\"3000\" value=\"2\"&gt;english&lt;/option&gt;\n &lt;option id=\"chm\" data-price=\"4000\" value=\"3\"&gt;chem&lt;/option&gt;\n &lt;option id=\"phy\" data-price=\"5000\" value=\"4\"&gt;physics&lt;/option&gt;\n&lt;/select&gt;\n&lt;div id=\"show_box\"&gt;&lt;/div&gt;\n&lt;div id=\"total_box\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>Then bind the handling function to the \"change\"-event of the select-element:</p>\n\n<pre><code>$('#wow').change(function() {\n // Remove any previously set values\n $('#show_box, #total_box').empty();\n var sum = 0,\n price;\n $(this).find('option:selected').each(function() {\n // Check that the attribute exist, so that any unset values won't bother\n if ($(this).attr('data-price')) { \n price = $(this).data('price');\n sum += price;\n $('#show_box').append('&lt;h6&gt;' + price + '&lt;/h6&gt;');\n }\n });\n $('#total_box').text(sum);\n});\n</code></pre>\n\n<p>And that's it. See <a href=\"http://jsfiddle.net/xKL44/2/\" rel=\"nofollow\">my jsFiddle</a> to see it in action.</p>\n\n<p>A couple of points about your question:</p>\n\n<ul>\n<li>Your code is overall rather messy. It really pays off later if you name your variables clearly, add comments to some obscure parts of the code, and remove obsolete old commented-out bits. You should also separate your JS and CSS to separate files for maintainability.</li>\n<li>Having to bind information (price) about the content (courses) directly in javascript should be avoided. Your JS should handle the logic, and your HTML should provide the content. If you decided to add another selectable option, that would require altering some 8-10 places in your code, but just 1 in mine, where logic and content is separate.</li>\n<li>In general if you find that you have multiple very similar if-statements in a row, there would almost certainly be a better, DRYer way.</li>\n<li>When posting your questions here, please only provide the relevant code and clean up the obsolete commented-out parts.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T11:02:01.447", "Id": "78501", "Score": "0", "body": "thanks Waiski for your review i will look into it... i check the jsfiddle link it is ok in your own way but it is not calculating the sum of clicks clicked and displaying it to the total box." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T14:02:09.530", "Id": "78519", "Score": "0", "body": "@user3223851 It calculates the sum of the prices of the selected elements, I thought that's what you wanted. So do you need to store the total number of times the element has been clicked? Or how many elements are selected in total? Please specify what is it exactly that you want, \"calculating the sum of clicks clicked\" is slightly ambiguous." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T10:01:30.353", "Id": "78714", "Score": "0", "body": "the main thing is to display and calculate it based on the clicks. @Waiski" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T21:52:04.983", "Id": "45032", "ParentId": "45012", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T19:57:07.923", "Id": "45012", "Score": "2", "Tags": [ "javascript", "jquery", "dom" ], "Title": "How to do a small calculation on a drop down when clicked?" }
45012
<p>I'm refactoring some code around a couple of ASP.NET Web Forms pages and decided to try out a variation of the Abstract Factory pattern of my own design. I need to create an implementer of an abstract class based on what query string value is available.</p> <p>Here's (a simplified version of) what I have right now:</p> <pre><code>internal static class Factory { public static AbstractClass Create(NameValueCollection queryString) { if (queryString["class1"] != null) { return new Class1(queryString["class1"]); } if (queryString["class2"] != null) { return new Class2(queryString["class2"]); } if (queryString["class3"] != null) { return new Class3(queryString["class3"]); } return null; } } </code></pre> <p>I don't know how I feel about this implementation. It certainly is better than what was there before, but I have a strong sense this could be improved some how. </p> <p>So now, in the relevant pages, I can simply do this:</p> <pre><code>AbstractClass item = Factory.Create(Request.QueryString); item.DoStuff(); </code></pre> <p>Does anyone have any suggestions? Or would this be considered good as-is?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:37:43.760", "Id": "78379", "Score": "0", "body": "What is your desired behavior if your querystring looked something like this: `?class1=someVal&class2=someOtherVal`? That's something to consider, since querystrings are client-facing and can be modified by them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:39:25.180", "Id": "78380", "Score": "1", "body": "Also, do you need a separate `Factory` class? Why not make a static method on your Abstract class called `Create`? There are [examples](http://msdn.microsoft.com/en-us/library/bw00b1dc(v=vs.110).aspx) of this in the .NET Framework." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:40:36.593", "Id": "78381", "Score": "0", "body": "If the client mucks with the query string, the desired behavior would be to simply go with the first value encountered in the order listed above" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:41:17.073", "Id": "78382", "Score": "0", "body": "And no, I don't need a separate Factory class, but my gut feel was to abstract that logic away from the base. That is a good suggestion though..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:45:19.027", "Id": "78387", "Score": "0", "body": "I feel that we can go too far with extracting functionality. Abstract classes allow for implemented methods, as well as static methods. It's worth grouping your logic together, IMO. I suppose my only other question is, how many potential classes do you have? A `switch` statement might be more efficient ([cite](http://stackoverflow.com/questions/445067/if-vs-switch-speed))" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:53:15.683", "Id": "78531", "Score": "0", "body": "Only three implementations of the base class, and a low chance of more being added." } ]
[ { "body": "<p>I Think you should do it more generic:</p>\n\n<pre><code>public static class Factory\n{\n static Dictionary&lt;String, Func&lt;String, Abstract&gt;&gt; classes;\n\n public static Abstract GetInstance(String s){\n if(!classes.ContainsKey(s)) throw new Exception();\n Func&lt;String, Abstract&gt; create=classes[s];\n return create(s);\n }\n\n static Factory ()\n {\n classes=new Dictionary&lt;String, Func&lt;String, Abstract&gt;&gt;(){\n {\"class1\", (x)=&gt;new Class1(x)},\n {\"class2\", (x)=&gt; new Class2(x)}\n };\n }\n}\n</code></pre>\n\n<p>This code is way more readable.\nYou have the static constructor block, where you register the factory methods according to the keys. And the <code>GetInstance</code>-Method shrinks to 3 lines, of which one is a purely guarding clause.</p>\n\n<p>Edit: modified after Mat's Mug's hint.</p>\n\n<p>P.S: Oh, I forgot to mention, that you really never should return <code>null</code>. </p>\n\n<p>Better a) throw an Exception or b) use a <code>NullObject</code>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:51:19.440", "Id": "78444", "Score": "1", "body": "+1 but I'd probably use a [*Collection Initializer*](http://msdn.microsoft.com/en-us/library/bb531208.aspx) to initialize `classes` in the static constructor (in the end it's identical)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:55:43.273", "Id": "78532", "Score": "0", "body": "In your solution, where would the logic be to parse the query string value collection to figure out which class to initialize?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T10:16:05.573", "Id": "78596", "Score": "0", "body": "Nowhere. That's not business of the factory. That should be done before. The factory delivers upon order - so to say. To make the order is not its duty ;)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T01:44:56.647", "Id": "45050", "ParentId": "45013", "Score": "4" } }, { "body": "<p>I would implement it using reflection.</p>\n\n<p>I'm using a <code>Dictionary</code> where the class types (inherited from <code>AbstractClass</code>) are stored, using the query string key as key. Also a <code>List</code> where I store keys, to keep track of sort order (the first inserted is the first checked for existence)</p>\n\n<p>In the static constructor, the key and the type (for each class inherited from <code>AbstractClass</code>) are added to the mentioned data containers.</p>\n\n<p>The <code>Create</code> method loops through all (sorted) keys contained in the <code>_keys</code> list. As soon as a corresponding key is found in the query string, the class type associated to that key is retrieved from the dictionary, and an instance is dynamically created, passing in the value associated to the key in the query string.</p>\n\n<p>Although there is more code than your current implementation, I think it's more elegant and generic, and less error prone.</p>\n\n<pre><code>internal static class Factory\n{\n private static readonly Dictionary&lt;string, Type&gt; _types = new Dictionary&lt;string, Type&gt;();\n private static readonly List&lt;string&gt; _keys = new List&lt;string&gt;();\n\n static Factory () {\n // Note: the order in which elements are inserted into the dictionary\n // determines which class has higher priority (in case multiple classes\n // are specified in the name value collection\n\n Add(\"class1\", typeof(Class1));\n Add(\"class2\", typeof(Class2));\n Add(\"class3\", typeof(Class3));\n }\n\n private static void Add(string key, Type classType) {\n _types[key] = classType;\n _keys.Add(key); \n }\n\n /// Use this if the key corresponds to the class name\n private static void Add(Type classType) {\n Add(classType.Name, classType);\n }\n\n public static AbstractClass Create(NameValueCollection queryString) {\n AbstractClass instance = null;\n\n for (int count = 0; count &lt; _keys.Count; ++count) {\n var key = _keys[count];\n var queryStringValue = queryString[key];\n\n if (queryStringValue != null) {\n var classType = _types[key];\n var constructorParam = queryString[key];\n var parameters = new string[] {constructorParam};\n instance = (AbstractClass) Activator.CreateInstance(classType, parameters); \n break;\n }\n }\n\n return instance;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:58:28.687", "Id": "78533", "Score": "0", "body": "Your for loop has a problem: `++count` instead of `count++`. I don't know how I feel about using reflection for this, but thank you for the answer; very interesting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T09:06:20.693", "Id": "78592", "Score": "0", "body": "`++count` and `count++` end up to the same result when used as standalone statements. I am used to the former because old unoptimized compilers translated `count++` as: `create a copy of count, increment it, then assign to count`, whereas ++count was translated as an atomic `inc` assembler instruction." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T01:09:52.617", "Id": "78679", "Score": "0", "body": "wow, you are right; i did not know that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T13:05:33.943", "Id": "45081", "ParentId": "45013", "Score": "2" } }, { "body": "<p>Passing a query string, or any string really, to the factory is troubling.</p>\n\n<p>Why I avoid strings:</p>\n\n<ol>\n<li>typos</li>\n<li>CasEinG</li>\n<li>Presumed encoding/structure can be problematic.</li>\n</ol>\n\n<p>IMHO the ideal will be to pass a parameter to the factory that unambiguously tells what to construct. As is, the factory is making gross assumptions about the content &amp; validity of the incoming query string. But there is no telling what free-form text is in it.</p>\n\n<p>The client code should evaluate &amp; validate the query string and then pass the appropriate thing to the factory. And IMHO do not pass a string. Use <code>enums</code>. <code>enums</code> are:</p>\n\n<ol>\n<li>type safe</li>\n<li>avoid typos</li>\n<li>self documenting - all the possible class-types are defined here.</li>\n<li>Query string validation - now that we have a definitive list of all possible class-types we can verify the query string contents against the <code>enum</code></li>\n<li>intelisense in visual studio</li>\n</ol>\n\n<p><strong>Design thoughts</strong></p>\n\n<ol>\n<li>Below is not the Abstract Factory Pattern per se. We are not creating factories of factories. The point of a factory is to separate \"complex construction (code)\" from the using class. The more complex the constructions \"the more factory we need\". </li>\n<li>Simple? then a static (or not) method w/in the client class is ok. </li>\n<li>Longish &amp; somewhat complex? a separate class. </li>\n<li>Use the Factory in many places? a separate class might be best. </li>\n<li>Many variations of each class-type? Perhaps a full-blown abstract factory design. etc., etc, and etc.</li>\n<li>IMHO, making the <code>Factory</code> class an instance, static, or singleton is your call.</li>\n</ol>\n\n<p><strong>The Dictionary Examples</strong></p>\n\n<ol>\n<li>Other examples using a dictionary are interesting. I'd use an <code>enum</code> for the key, not strings. overall it <em>feels</em> like the reflection/abstraction aspects are wasted as it's all internal and you still have to \"open the factory\", i.e. modify it, to add/delete class-types.</li>\n<li>The dictionary is necessary only because we pass the entire query string to the factory. Again, Tell the factory what to build don't make it try to guess (see above about \"gross assumptions\"). The calling client is the absolute best place with the proper context to decide what to build.</li>\n<li>Making the factory parse the query string - and therefore handle problems - is violating the single responsibility principle.</li>\n</ol>\n\n<p>.</p>\n\n<pre><code>internal public class Factory{\n public AbstractClass Create(abstracts makeThis) {\n AbstractClass newClass;\n\n switch(makeThis) {\n case abstracts.class1:\n newClass = BuildClass1();\n break;\n\n case abstracts.class2:\n newClass = BuildClass2();\n break;\n // and so on.\n\n default:\n throw new NotImplementedException();\n break;\n }\n return newClass;\n }\n\n // build methods here.\n}\n\npublic enum abstracts {class1, class2, class3}\n\npublic class Client{\n AbstractClass factoryBuiltThing;\n Factory classFactory = new Factory();\n\n // put some error handling in here\n protected bool ParseQueryString(string queryString, out buildThis) {}\n\n // put some error handing here too.\n protected abstracts DeriveAbstractEnum(string theDesiredClass){};\n\n public void BuildSomething(string queryString) {\n string buildThis = string.Empty;\n abstracts whatToBuild;\n\n if (ParseQueryString (queryString, out buildThis)) {\n whatToBuild = DeriveAbstractEnum(buildThis);\n factoryBuiltThing = classFactory.Create(whatToBuild);\n }else { \n throw new NotImplementedException(\n string.format(\"The query string is crap: {0}\", queryString));\n }\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T01:18:04.940", "Id": "78682", "Score": "0", "body": "I really like your point about the way I have it violating the single responsibility principle, excellent." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T23:57:12.047", "Id": "45112", "ParentId": "45013", "Score": "2" } } ]
{ "AcceptedAnswerId": "45112", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:18:52.183", "Id": "45013", "Score": "6", "Tags": [ "c#", "design-patterns", "asp.net" ], "Title": "Advice on \"Factory\" Pattern Implementation" }
45013
<p>I decided to try to make a simple RPS implementation in Java 8, the following notes should be said first:</p> <ul> <li>At a later point it should support RPSLS aswell, as any other Gesture-game variant.</li> <li>At a later point it should support different views, for example a graphical one.</li> <li>I have made a special <code>ConsoleReader</code> class which allows me to kill reading from <code>System.in</code> without closing the stream.</li> </ul> <p>I would like comments on:</p> <ul> <li>Everything</li> <li>Concurrency issues</li> <li>Variable, method and javadoc naming and wording</li> </ul> <p>The code should be quite self-explanatory.</p> <pre><code>/** * Class that provides a console reader, from which other classes can read. * * @author Frank van Heeswijk */ public class ConsoleReader implements Runnable { /** Synchronized mapping from objects to a list of string consumers to consume input lines. */ private final static Map&lt;Object, List&lt;Consumer&lt;String&gt;&gt;&gt; CONSUMER_MAP = Collections.synchronizedMap(new HashMap&lt;&gt;()); /** Synchronized mapping from objects to a blocking queue of strings to read input lines while maintaining blocking behaviour. */ private final static Map&lt;Object, BlockingQueue&lt;String&gt;&gt; BLOCKING_QUEUE_MAP = Collections.synchronizedMap(new HashMap&lt;&gt;()); /** * Adds a consumer on the object you pass. When console input happens, the consumer will be triggered. * * @param object The object to which the consumers belong * @param consumer The consumer to handle new input */ public static void addConsumer(final Object object, final Consumer&lt;String&gt; consumer) { ensureKey(object, CONSUMER_MAP, ArrayList::new); CONSUMER_MAP.get(object).add(consumer); } /** * Removes all consumers related to the object you pass. * * @param object The object to which consumers might be attached */ public static void removeConsumers(final Object object) { CONSUMER_MAP.remove(object); } @Override public void run() { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String nextLine = scanner.nextLine(); try { for (Map.Entry&lt;Object, BlockingQueue&lt;String&gt;&gt; entry : BLOCKING_QUEUE_MAP.entrySet()) { entry.getValue().put(nextLine); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } CONSUMER_MAP.forEach((obj, list) -&gt; list.forEach(consumer -&gt; consumer.accept(nextLine))); } } /** * Waits for a new line of input and then returns it. * * Per object a new queue gets created, such that taking away the line from one queue does not mean that other objects cannot read it anymore. * * @param object The object that asks to read the next line * @return The next line from System.in * @throws InterruptedException If the thread has been interrupted */ public static String nextLine(final Object object) throws InterruptedException { ensureKey(object, BLOCKING_QUEUE_MAP, LinkedBlockingQueue::new); BlockingQueue&lt;String&gt; queue = BLOCKING_QUEUE_MAP.get(object); String nextLine = queue.take(); if (queue.isEmpty()) { BLOCKING_QUEUE_MAP.remove(object); } return nextLine; } /** * Ensures that the key has an empty structure attached to it. * * @param &lt;V&gt; The type of structure of Map&lt;Object, V&gt; * @param object The key of the map * @param map The map on which to ensure a value exists * @param supplier A supplier to supply an empty structure */ private static &lt;V&gt; void ensureKey(final Object object, final Map&lt;Object, V&gt; map, final Supplier&lt;V&gt; supplier) { if (!map.containsKey(object)) { map.put(object, supplier.get()); } } } </code></pre> <hr> <pre><code>/** * Interface to extend when implementing actions. * * @author Frank van Heeswijk */ public interface Action { } </code></pre> <hr> <pre><code>/** * Interface that all types of gestures should extend. * * @author Frank van Heeswijk */ public interface Gesture { /** * Lists from which gestures this gesture wins. * * @return A list describing from which gestures this gesture wins */ public List&lt;? extends Gesture&gt; listWinsFrom(); /** * Lists to which gestures this gesture ties. * * @return A list describing to which gestures this gesture ties */ public List&lt;? extends Gesture&gt; listTiesTo(); /** * Lists from which gestures this gesture loses. * * @return A list describing from which gestures this gesture loses */ public List&lt;? extends Gesture&gt; listLosesFrom(); /** * Returns whether this gesture wins from the other gesture * * @param &lt;G&gt; The concrete type of the gesture * @param gesture The other gesture * @return Whether this gesture wins from the other gesture */ default public &lt;G extends Gesture&gt; boolean winsFrom(final G gesture) { return listWinsFrom().contains(gesture); } /** * Returns whether this gesture ties to the other gesture * * @param &lt;G&gt; The concrete type of the gesture * @param gesture The other gesture * @return Whether this gesture ties to the other gesture */ default public &lt;G extends Gesture&gt; boolean tiesTo(final G gesture) { return listTiesTo().contains(gesture); } /** * Returns whether this gesture loses from the other gesture * * @param &lt;G&gt; The concrete type of the gesture * @param gesture The other gesture * @return Whether this gesture loses from the other gesture */ default public &lt;G extends Gesture&gt; boolean losesFrom(final G gesture) { return listLosesFrom().contains(gesture); } } </code></pre> <hr> <pre><code>/** * An enum providing the RPS gestures. * * @author Frank van Heeswijk */ public enum RPSGesture implements Gesture, Action, GestureRPSRules { ROCK, PAPER, SCISSORS; @Override public List&lt;RPSGesture&gt; listWinsFrom() { return winMapping().get(this); } @Override public List&lt;RPSGesture&gt; listTiesTo() { return tieMapping().get(this); } @Override public List&lt;RPSGesture&gt; listLosesFrom() { return loseMapping().get(this); } } </code></pre> <hr> <pre><code>/** * Provides the rules of a specific gesture, meaning when one wins, ties or loses. * * @author Frank van Heeswijk * @param &lt;T&gt; The type of gesture */ public interface GestureRules&lt;T extends Gesture&gt; { /** * Returns a mapping from the gestures to which gestures they win from. * * @return A mapping from the gestures to which gestures they win from */ public Map&lt;T, List&lt;T&gt;&gt; winMapping(); /** * Returns a mapping from the gestures to which gestures they tie to. * * @return A mapping from the gestures to which gestures they tie to */ public Map&lt;T, List&lt;T&gt;&gt; tieMapping(); /** * Returns a mapping from the gestures to which gestures they lose from. * * @return A mapping from the gestures to which gestures they lose from */ public Map&lt;T, List&lt;T&gt;&gt; loseMapping(); } </code></pre> <hr> <pre><code>/** * Provides an implementation for the GestureRules when considering RPS gestures. * * @author Frank van Heeswijk */ public interface GestureRPSRules extends GestureRules&lt;RPSGesture&gt; { @Override default public Map&lt;RPSGesture, List&lt;RPSGesture&gt;&gt; winMapping() { Map&lt;RPSGesture, List&lt;RPSGesture&gt;&gt; mapping = new HashMap&lt;&gt;(); mapping.put(ROCK, Arrays.asList(SCISSORS)); mapping.put(PAPER, Arrays.asList(ROCK)); mapping.put(SCISSORS, Arrays.asList(PAPER)); return mapping; } @Override default public Map&lt;RPSGesture, List&lt;RPSGesture&gt;&gt; tieMapping() { Map&lt;RPSGesture, List&lt;RPSGesture&gt;&gt; mapping = new HashMap&lt;&gt;(); mapping.put(ROCK, Arrays.asList(ROCK)); mapping.put(PAPER, Arrays.asList(PAPER)); mapping.put(SCISSORS, Arrays.asList(SCISSORS)); return mapping; } @Override default public Map&lt;RPSGesture, List&lt;RPSGesture&gt;&gt; loseMapping() { Map&lt;RPSGesture, List&lt;RPSGesture&gt;&gt; mapping = new HashMap&lt;&gt;(); mapping.put(ROCK, Arrays.asList(PAPER)); mapping.put(PAPER, Arrays.asList(SCISSORS)); mapping.put(SCISSORS, Arrays.asList(ROCK)); return mapping; } } </code></pre> <hr> <pre><code>/** * Interface to extend when implementing results. * * @author Frank van Heeswijk */ public interface Result { } </code></pre> <hr> <pre><code>/** * Enum listing the possible results of a RPS game. * * @author Frank van Heeswijk */ public enum RPSResult implements Result { WIN, TIE, LOSS; } </code></pre> <hr> <pre><code>/** * An interface holding a player that can play any type of game. * * @author Frank van Heeswijk * @param &lt;A&gt; The type of the action * @param &lt;R&gt; The type of the result */ public interface Player&lt;A extends Action, R extends Result&gt; { /** * Processes when some player has done some action and obtained some result. * * @param target The player that performed the action * @param action The action the player performed * @param result The result of the action the player has performed */ default public void onPostAction(final Player&lt;A, R&gt; target, final A action, final R result) { } /** * Does the action of the player. * * @return The action the player has done */ public A doAction(); /** * Does the backup action of the player. * * This will get called when the normal action has timed out. * * @return The backup action the player has done */ public A doActionBackup(); /** * Performs the action of the player with a timeout on an Executor. * * This will execute the normal action of the player waiting for a maximum specified time, if a timeout occurs then it will default to the backup action. * * @param executor The Executor on which the action needs to be executed * @param period The time period it may take until the action gets a timeout * @param unit The time unit of the period * @return The action performed by the player */ default public A doActionWithTimeout(final Executor executor, final int period, final TimeUnit unit) { FutureTask&lt;A&gt; futureTask = new FutureTask&lt;&gt;(this::doAction); executor.execute(futureTask); try { return futureTask.get(period, unit); } catch (InterruptedException ex) { futureTask.cancel(true); Thread.currentThread().interrupt(); return doActionBackup(); } catch (ExecutionException ex) { throw new IllegalStateException(ex); } catch (TimeoutException ex) { timeout(); futureTask.cancel(true); return doActionBackup(); } } /** * Does something when a timeout has occured. */ default public void timeout() { } } </code></pre> <hr> <pre><code>/** * A player that is able to play any gesture related game. * * @author Frank van Heeswijk * @param &lt;A&gt; The type of action * @param &lt;R&gt; The type of result */ abstract public class GesturePlayer&lt;A extends Action, R extends Result&gt; implements Player&lt;A, R&gt; { /** List of actions that the player can execute. **/ protected final List&lt;A&gt; actions; /** A Random instance. **/ private final Random random = new Random(); /** * Constructs the GesturePlayer. * * @param actions The list of actions that can be used */ public GesturePlayer(final List&lt;A&gt; actions) { Objects.requireNonNull(actions); this.actions = actions; } /** * Returns a random action. * * @return A random action. */ protected A getRandomAction() { return actions.get(random.nextInt(actions.size())); } } </code></pre> <hr> <pre><code>/** * A player that is able to play RPS. * * @author Frank van Heeswijk */ abstract public class RPSPlayer extends GesturePlayer&lt;RPSGesture, RPSResult&gt; { /** The RPSView interface. */ protected final RPSView rpsView; /** * Constructs the RPSPlayer with the RPSView interface as argument. * * @param rpsView The RPS view */ public RPSPlayer(final RPSView rpsView) { super(Arrays.asList(RPSGesture.values())); this.rpsView = rpsView; } @Override public RPSGesture doActionBackup() { return getRandomAction(); } @Override public void timeout() { rpsView.enterGestureTimeout(this); } } </code></pre> <hr> <pre><code>/** * A human player that can play RPS. * * @author Frank van Heeswijk */ public class RPSHumanPlayer extends RPSPlayer { public RPSHumanPlayer(final RPSView rpsView) { super(rpsView); } @Override public RPSGesture doAction() { Optional&lt;RPSGesture&gt; gesture; try { gesture = askInput(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return doActionBackup(); } while (!gesture.isPresent()) { rpsView.gestureNotRecognized(actions); try { gesture = askInput(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return doActionBackup(); } } return gesture.get(); } /** * Asks for user input. * * @return The user input, converted to a RPS gesture. * @throws InterruptedException If the method gets interrupted. */ private Optional&lt;RPSGesture&gt; askInput() throws InterruptedException { rpsView.pleaseEnterGesture(); return parseRaw(rpsView.readGestureInput()); } private Optional&lt;RPSGesture&gt; parseRaw(final String raw) { List&lt;RPSGesture&gt; gestures = actions.stream() .filter(action -&gt; action.toString().toLowerCase().startsWith(raw.toLowerCase())) .collect(Collectors.toList()); return ((gestures.size() == 1) ? Optional.of(gestures.get(0)) : Optional.empty()); } } </code></pre> <hr> <pre><code>/** * An AI player that can play RPS. * * @author Frank van Heeswijk */ public class RPSSimpleAIPlayer extends RPSPlayer { /** * Constructs the RPSSimpleAIPlayer. * * @param rpsView The RPS view */ public RPSSimpleAIPlayer(final RPSView rpsView) { super(rpsView); } @Override public RPSGesture doAction() { return getRandomAction(); } } </code></pre> <hr> <pre><code>/** * An interface that can be used for playing any type of game. * * @author Frank van Heeswijk * @param &lt;A&gt; The type of action in the game * @param &lt;R&gt; The type of result in the game * @param &lt;P&gt; The type of player in the game */ public interface Game&lt;A extends Action, R extends Result, P extends Player&lt;A, R&gt;&gt; { /** * Adds a player to this game. * * @param player The new player */ public void addPlayer(final P player); /** * Plays one round of the game. */ public void playRound(); /** * Default implementation of playing a game. * * This will play a game that lasts forever. */ default public void playGame() { boolean playing = true; while (playing) { playRound(); } } /** * Returns the result of a player after having played the current round. * * @param playerActions A mapping from the players to their actions * @param forPlayer The player for which to determine the result * @param forAction The action that belongs to the player * @return The result of the player for this round */ public R determinePlayerResult(final Map&lt;P, A&gt; playerActions, final P forPlayer, final A forAction); } </code></pre> <hr> <pre><code>/** * An abstract class that provides some basic implementations of the Game. * * @author Frank van Heeswijk * @param &lt;A&gt; The type of action in the game * @param &lt;R&gt; The type of result in the game * @param &lt;P&gt; The type of player in the game */ abstract public class AbstractGame&lt;A extends Action, R extends Result, P extends Player&lt;A, R&gt;&gt; implements Game&lt;A, R, P&gt; { /** A list holding all players. */ protected final List&lt;P&gt; players = new ArrayList&lt;&gt;(); @Override public void addPlayer(final P player) { Objects.requireNonNull(player); players.add(player); } } </code></pre> <hr> <pre><code>/** * A class providing an implementation for a RPS game. * * @author Frank van Heeswijk */ public class RPSGame extends AbstractGame&lt;RPSGesture, RPSResult, RPSPlayer&gt; { /** An executor service to run the player calculations on, initialized to two times the available cores. */ private final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); /** The RPSView interface. */ private final RPSView rpsView; /** * Construcs the RPSGame with the RPSView interface as argument. * * @param rpsView The RPS view */ public RPSGame(final RPSView rpsView) { this.rpsView = rpsView; } @Override public void playRound() { Map&lt;RPSPlayer, RPSGesture&gt; playerGestures = players.stream() .collect(Collectors.toMap( player -&gt; player, player -&gt; player.doActionWithTimeout(executorService, 10, TimeUnit.SECONDS)) ); playerGestures.forEach((player, gesture) -&gt; { RPSResult result = determinePlayerResult(playerGestures, player, gesture); players.forEach(p -&gt; p.onPostAction(player, gesture, result)); rpsView.processPlayerAction(player, gesture, result); }); } @Override public RPSResult determinePlayerResult(final Map&lt;RPSPlayer, RPSGesture&gt; playerActions, final RPSPlayer forPlayer, final RPSGesture forGesture) { int wins = 0; int ties = 0; int losses = 0; for (Map.Entry&lt;RPSPlayer, RPSGesture&gt; entry : playerActions.entrySet()) { RPSPlayer player = entry.getKey(); RPSGesture gesture = entry.getValue(); if (player.equals(forPlayer)) { continue; } if (forGesture.winsFrom(gesture)) { wins++; } else if (forGesture.tiesTo(gesture)) { ties++; } else if (forGesture.losesFrom(gesture)) { losses++; } } int max = IntStream.of(wins, ties, losses).max().getAsInt(); if (max == wins) { return RPSResult.WIN; } else if (max == ties) { return RPSResult.TIE; } else { return RPSResult.LOSS; } } } </code></pre> <hr> <pre><code>/** * Interface having all input/output related methods for a RPSGame. * * @author Frank van Heeswijk */ public interface RPSView { /** * Processes a player action. * * @param player The player on which the action occured * @param gesture The gesture the player has used * @param result The result of using that gesture in that specific round */ public void processPlayerAction(final RPSPlayer player, final RPSGesture gesture, final RPSResult result); /** * Processes what happens when the gesture has not been recognized. * * @param gestures All available gestures */ public void gestureNotRecognized(final List&lt;RPSGesture&gt; gestures); /** * Processes what happens when the player should provide his/her gesture. */ public void pleaseEnterGesture(); /** * Processes what happens when the player has a timeout. * * @param player The player that had received a timeout */ public void enterGestureTimeout(final RPSPlayer player); /** * Processes what happens when the player needs to enter his gesture. * * @return The entered gesture in string format * @throws InterruptedException If waiting for the gesture to be entered has been interrupted */ public String readGestureInput() throws InterruptedException; } </code></pre> <hr> <pre><code>/** * Class providing the console implementation of the RPSView. * * @author Frank van Heeswijk */ public class ConsoleRPSView implements RPSView { @Override public void processPlayerAction(final RPSPlayer player, final RPSGesture gesture, final RPSResult result) { Objects.requireNonNull(player); Objects.requireNonNull(gesture); Objects.requireNonNull(result); if (player instanceof RPSHumanPlayer) { System.out.println("I played " + gesture + " and the result was a " + result); } else if (player instanceof RPSSimpleAIPlayer) { System.out.println("The AI played " + gesture + " and the result was a " + result); } } @Override public void gestureNotRecognized(final List&lt;RPSGesture&gt; gestures) { System.out.println("Your gesture was nog recognized or ambigious, please choose from: " + String.join(", ", gestures.stream().map(RPSGesture::toString).collect(Collectors.toList()))); } @Override public void pleaseEnterGesture() { System.out.println("Please enter your gesture: "); } @Override public String readGestureInput() throws InterruptedException { return ConsoleReader.nextLine(this); } @Override public void enterGestureTimeout(final RPSPlayer player) { if (player instanceof RPSHumanPlayer) { System.out.println("You have not entered your gesture in time."); } else if (player instanceof RPSSimpleAIPlayer) { System.out.println("The AI has not entered his gesture in time."); } } } </code></pre> <hr> <pre><code>/** * The main class * * @author Frank van Heeswijk */ public class RPSGameMain { private void init() { new Thread(new ConsoleReader()).start(); RPSView consoleRPSView = new ConsoleRPSView(); RPSGame rpsGame = new RPSGame(consoleRPSView); rpsGame.addPlayer(new RPSHumanPlayer(consoleRPSView)); rpsGame.addPlayer(new RPSSimpleAIPlayer(consoleRPSView)); rpsGame.playGame(); } /** * @param args the command line arguments */ public static void main(String[] args) { new RPSGameMain().init(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-20T19:36:54.353", "Id": "115917", "Score": "2", "body": "Where are the tests?" } ]
[ { "body": "<ul>\n<li><p>I like your usage of Java 8. I'm learning a lot just by reading your code. I'm loving Java 8 a lot and I haven't even used it myself yet.</p></li>\n<li><p>Use a <code>GestureRule</code> class. Take a look at <a href=\"https://codereview.stackexchange.com/questions/36426/rock-paper-scissors-lizard-spock-challenge-take-2\">The Mug's Main class</a> and/or <a href=\"https://codereview.stackexchange.com/questions/36394/rock-paper-scissors-lizard-spock-as-a-code-style-and-challenge\">The Monkey's static initializer in his enum</a>. Your current way is error prone and causes some duplicated code. Currently you can by accident create a Gesture that both wins, loses and ties another gesture. That really shouldn't be possible. I'd recommend using a method such as <code>gesture.fight(otherGesture)</code> that returns a <code>RPSResult</code> to make sure that a fight between one gesture and another cannot be both a win and a loss at the same time.</p></li>\n<li><p>You're currently not using the <code>onPostAction</code> method, and I do wonder whether you're gonna need it at all. And if you are going to need it, it can likely be made in a different/better way. By getting rid of it / doing it differently you also get rid of the <code>R extends Result</code> generic part of your <code>Player</code> interface/class(es). An option would be to use <code>onPostRound(Map&lt;RPSPlayer, RPSGesture&gt; gestures)</code> (using only the 'A' and 'P' generics) and do a for-each on the gestures you're interested in. Because technically, players make their moves at the same time.</p></li>\n<li><p>Your <code>Action</code> and <code>Result</code> interfaces only seems to be <em>marker interfaces</em>, you don't really need them. If you remove them it will decrease your generic dependencies and you can write:</p>\n\n<pre><code>public interface Game&lt;A, R, P extends Player&lt;A, R&gt;&gt; {\n</code></pre></li>\n<li><p>Interface methods doesn't need to be declared <code>public</code>, they're public automatically.</p></li>\n<li><p>In your <code>playGame</code> method, why do you declare a boolean variable instead of using <code>while (true)</code>?</p></li>\n<li><p>You're using <code>newFixedThreadPool</code> which means that your number of threads cannot go above the specified amount. Instead consider using a cached thread pool which will create as many threads as needed while keeping a specified number of threads whether they're busy or not. By using a fixed thread pool you will likely have several threads that will <em>never</em> have anything to do.</p></li>\n<li><p>Use a <code>toString</code> method in your different <code>RPSPlayer</code> classes or a <code>player.isAI()</code> method instead of using <code>instanceof</code> in your ConsoleRPSView. Using <code>instanceof</code> outside an <code>.equals</code> method is not good practice, it can mostly be avoided. Use polymorphism and better interfaces instead.</p>\n\n<pre><code>System.out.println(player + \" played \" + gesture + \" and the result was a \" + result);\n...\nif (!player.isAI())\n System.out.println(\"You have not entered your gesture in time.\");\n</code></pre></li>\n<li><p>Typo: <code>System.out.println(\"Your gesture was nog recognized</code> - nog --> not. 'nog' means 'probably' in Swedish so if reading this in a combined English-Swedish way it'd be quite funny...</p></li>\n<li><p>Your <code>RPSGameMain.init</code> method does more than just initializing, doesn't it? I'd recommend either splitting into two methods or rename it to <code>start</code> or similar.</p></li>\n<li><p>Overall your code quality is good, it is easy to read and mostly easy to understand.</p></li>\n<li><p>I like the way you've decoupled your \"console view\" from your \"model\" with an interface :)</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T21:48:24.463", "Id": "45027", "ParentId": "45015", "Score": "12" } }, { "body": "<p>As a relatively minor thing, I think there are some issues with over commenting. For example:</p>\n\n<pre><code>/**\n * Returns a random action.\n * \n * @return A random action.\n */\n protected A getRandomAction() {\n return actions.get(random.nextInt(actions.size()));\n }\n</code></pre>\n\n<p>This is a clearly written method, it's method name concisely explains what it does, and there are no parameters to trip up a user. It's got a single line and it's very readable. In fact it takes me longer to read the comment than the code. From <a href=\"http://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882\">Clean Code</a>: a comment should be included if it makes the code easier to understand. Here, we have lots of repetition. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T03:12:14.043", "Id": "78447", "Score": "3", "body": "Javadoc is not the same as comments" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T10:33:02.030", "Id": "78499", "Score": "1", "body": "Unfortunately, rolfl is right here. Often there is a requirement on code to have appropriate Javadoc, in this case skiwi put that as a requirement on himself apparently. This is still an answer worth thinking about though. But writing non-duplicated Javadoc is hard." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T22:26:24.477", "Id": "45038", "ParentId": "45015", "Score": "7" } }, { "body": "<p>I am confused by <code>ConsoleReader</code>. It seems too complex. I honestly did not spend that much time reading your code, so maybe I did not understand correctly.</p>\n\n<ul>\n<li><p>In the method declarations, <code>player</code>, <code>key</code> or <code>id</code> would probably be better variables names than <code>object</code>.</p></li>\n<li><p>I don't like that <code>ConsoleRPSReader</code> is highly dependent on <code>ConsoleReader</code> but that dependency is not visible. You should probably have the constructor of <code>ConsoleRPSReader</code> taking a <code>ConsoleReader</code> as argument.</p></li>\n<li><p>Is <code>ConsoleReader</code> just a provider of static methods? a singleton? Maybe it should be a normal class, but you make the constructor private and provide a static method to get the singleton. You could then make member variables and methods non-static.</p></li>\n<li><p><code>ConsoleReader.run()</code> puts a new line in <em>all</em> the queues. Is that a bug? <code>Console.nextLine(key)</code> will read the new line for all keys.</p></li>\n<li><p>To reduce complexity, maybe you could break <code>ConsoleReader</code> in one parent class that just reads from input, than one sub-class which can have \"observers\". I'm still not sure why you specify some key in <code>Console.nextLine(key)</code>, so I'm not sure if that should be a different sub-class.</p></li>\n</ul>\n\n<p>Minor details: </p>\n\n<ul>\n<li><p>Avoid using \"you\" in Javadoc.</p></li>\n<li><p>Instead of <code>for(Entry x : map.entrySet()) { x.getValue()...}</code>, you can use <code>for (Val v : map.values()) { v...}</code>. I think it is cleaner, but it's arguable.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-20T18:26:54.350", "Id": "63450", "ParentId": "45015", "Score": "0" } } ]
{ "AcceptedAnswerId": "45027", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:25:11.983", "Id": "45015", "Score": "15", "Tags": [ "java", "game", "lambda", "rock-paper-scissors" ], "Title": "Basic Rock-Paper-Scissors implementation" }
45015
<p>How can I write this OR statement better, allowing for growth in number of values?</p> <pre><code>var isNewFile = (progressID == 10 || progressID == 20 || progressID == 21); </code></pre> <p>I was thinking of this:</p> <pre><code>var isNewFile = progressID.Contains (10,20,21) </code></pre> <p>OR using Linq:</p> <p><code>.Select</code> or <code>.Contains</code></p> <p>Any thoughts?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-20T16:56:46.020", "Id": "78375", "Score": "2", "body": "What's wrong with that? Do you need a dynamic list of possible IDs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-20T16:59:02.993", "Id": "78376", "Score": "0", "body": "No, just wanted to keep it cleaner (looking) .." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-20T17:00:05.850", "Id": "78377", "Score": "1", "body": "To make it cleaner, I would use an enum or constants instead of the \"magic numbers\" .. and likely leave the `||`s alone for now." } ]
[ { "body": "<p>For something this simple, I think using the <code>||</code> is fine, however, if you need to use the list of acceptable integers more generally or avoid hard-coding the set in a single expression<sup>1</sup>, you can use something like this:</p>\n\n<pre><code>var newFileProgressIds = new[] { 10, 20, 21 };\n\nvar isNewFile = newFileProgressIds.Contains(progressID);\n</code></pre>\n\n<p>Or possibly use a <a href=\"http://msdn.microsoft.com/en-us/library/bb359438%28v=vs.110%29.aspx\"><code>HashSet&lt;T&gt;</code></a>:</p>\n\n<pre><code>var newFileProgressIds = new HashSet&lt;int&gt; { 10, 20, 21 };\n\nvar isNewFile = newFileProgressIds.Contains(progressID);\n</code></pre>\n\n<p><sup>1: Of course, in these examples, the values are still hard coded in one place, but precisely how you generate the list is unimportant.</sup></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-20T16:56:24.967", "Id": "45017", "ParentId": "45016", "Score": "8" } } ]
{ "AcceptedAnswerId": "45017", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-20T16:55:40.453", "Id": "45016", "Score": "2", "Tags": [ "c#", "linq" ], "Title": "Refactor C# OR statement using Linq" }
45016
<p>It returns <code>true</code> for:</p> <blockquote> <pre><code>a*(b+c) ()() (()) ((!!(123(x)))) </code></pre> </blockquote> <p>and returns <code>false</code> for:</p> <blockquote> <pre><code>(a((b+c)) )()( ))(( (rsd+3)*(-3-a)) </code></pre> </blockquote> <p>As you can see, the logic is simple. Can you confirm for me that it works for all-cases? I mean the logic isn't flawed.</p> <p>It must be efficient and by that I mean not go over the linked list more than once.</p> <pre><code>public boolean parentheses() { return parentheses(0,_head); } public boolean parentheses(int p, CharNode current) { if (current == null) { if (p == 0) return true; else return false; } else { if(current.getData() == ')' &amp;&amp; p == 0) return false; else if (current.getData() == '(') return parentheses(p+1,current.getNext()); else if (current.getData() == ')') return parentheses(p-1,current.getNext()); else return parentheses(p,current.getNext()); } } </code></pre>
[]
[ { "body": "<p>You need to maintain open and closed braces count in your method, to check the validity of the closed braces. </p>\n\n<pre><code>boolean isValid(String s, int i, int open, int closed){\n if(i == s.length()){\n if(open != closed) return false;\n return true;\n } \n\n if(s.getChar(i) == '(') open = open+1;\n\n if(s.getChar(i) == ')'){\n if(open &gt; closed) closed = closed+1;\n else return false;\n } \n\n return isValid(s, i+1, open, closed);\n}\n</code></pre>\n\n<blockquote>\n<pre><code>isValid(\"a*(b+c)\") =&gt; true\nisValid(\"((!!(123(x))))\") =&gt; true\nisValid(\" (rsd+3)*(-3-a))\") =&gt; false\nisValid(\"(a((b+c)) \") =&gt; false\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T21:33:23.607", "Id": "78400", "Score": "0", "body": "can you show me a case where my method doesn't work?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T21:39:47.210", "Id": "78401", "Score": "0", "body": "your program looks good to me and should work with all the test cases as far as I can see. Sorry didn't read your question properly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T21:30:11.240", "Id": "45024", "ParentId": "45020", "Score": "2" } }, { "body": "<h2>Short Answer</h2>\n<p>Yes, I believe it will be functional....</p>\n<h2>Dubious Recursion</h2>\n<p>Calling this method <em>recursive</em> is a problem. It is not a recursive method. Just because it is calling itself does not mean it is a recursive function. What you have is a bad loop. <a href=\"http://en.wikipedia.org/wiki/Recursion_%28computer_science%29\" rel=\"noreferrer\">From Wikipedia</a>:</p>\n<blockquote>\n<p>A recursive function definition has one or more base cases, meaning input(s) for which the function produces a result trivially (without recurring), and one or more recursive cases, meaning input(s) for which the program recurs (calls itself).</p>\n</blockquote>\n<p>Your code does not have a base case and a recursive case..... unless you consider <code>current==null</code> to be the base case... but that is just the recursion-terminating statement.</p>\n<p>What I mean, is that, consider this loop:</p>\n<pre><code>boolean checkParenthesis(CharNode current) {\n int p = 0;\n while (current != null) {\n if (current.getData() == '(') {\n p++;\n } else if (current.getData() == ')') {\n p--;\n }\n if (p &lt; 0) {\n return false;\n }\n current = current.getNext();\n }\n return p == 0;\n}\n</code></pre>\n<p>That is how you can write the code iteratively.</p>\n<p>Now, if I change it just like this:</p>\n<pre><code>boolean checkParenthesis(CharNode current, int p) {\n if (current == null) {\n return p == 0;\n } else {\n if (current.getData() == '(') {\n p++;\n } else if (current.getData() == ')') {\n p--;\n }\n if (p &lt; 0) {\n return false;\n }\n return checkParenthesis(current.getNext(), p);\n }\n}\n</code></pre>\n<p>What I am trying to show here is that you essentially have a while-loop that uses the stack to check the end condition.</p>\n<p>For a long input, your code will fail with a stack-overflow exception.</p>\n<h2>Iteration</h2>\n<p>When you have linked data like you do, the natural solution is to use iteration.</p>\n<p>The example I have above shows how it can be done.</p>\n<p>I am not sure why you are using recursion at all.</p>\n<h2>Actual Recursion</h2>\n<p>If you really want to use recursion, the right way to do it would be to recurse down when you encounter a <code>(</code> value, and recurse up when you encounter a <code>)</code></p>\n<p>Each recursive level will make sure it has a matching parenthesis.... it will look something like:</p>\n<pre><code>// used if there is an error.\nprivate static final CharNode ERRORNODE = new CharNode(....);\nprivate static final CharNode ENDOFDATA = new CharNode(....);\n\nboolean checkParenthesis(CharNode current) {\n current = matchParenthesis(current, true);\n if (current == ERRORNODE) {\n return false;\n }\n // current could be null if there was an unexpected ')' as the very last character.\n return current == ENDOFDATA;\n} \n\nCharNode matchParenthesis(CharNode current, boolean toplevel) {\n while (current != null &amp;&amp; current != ENDOFDATA &amp;&amp; current != ERRORNODE) {\n if (current.getData() == ')') {\n // found our matching brace\n return current.getNext();\n }\n if (current.getData() == '(') {\n // need to start a sub-level check for a matching brace.\n current = matchParenthesis(current.getNext(), false);\n } else {\n current = current.nextData();\n }\n }\n if (current == null) {\n return toplevel ? ENDOFDATA : ERRORNODE;\n }\n return current;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T22:50:25.547", "Id": "78414", "Score": "0", "body": "I forgot to mention my method was a question, and it had to be recurssive, but I like your recurrsion much better ;p it does look more recurssive to me..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T22:06:23.990", "Id": "45035", "ParentId": "45020", "Score": "5" } }, { "body": "<p>Your recursive solution works, as long as the input isn't too long. I don't recommend using recursion for this problem, since a long input could easily cause a crash from stack overflow. An iterative solution would be more appropriate for Java.</p>\n\n<p>The method name isn't descriptive enough. Typically, a function that returns a boolean should be named <code>isSomething()</code> or <code>hasSomething()</code>. The parameter <code>p</code> could also be named better.</p>\n\n<p>The helper function should be made private. It can also be static, since is a pure function that does not rely on any object state.</p>\n\n<p>The code could be written more succinctly.</p>\n\n<pre><code>public boolean hasMatchingParentheses()\n{\n return hasMatchingParentheses(head, 0);\n}\n\nprivate static boolean hasMatchingParentheses(CharNode current, int level)\n{\n if (current == null)\n {\n return (level == 0);\n }\n\n switch (current.getData())\n {\n case ')':\n if (level == 0) return false;\n return hasMatchingParentheses(current.getNext(), level - 1);\n case '(':\n return hasMatchingParentheses(current.getNext(), level + 1);\n default:\n return hasMatchingParentheses(current.getNext(), level);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T22:29:08.890", "Id": "45040", "ParentId": "45020", "Score": "1" } }, { "body": "<p>In a more general case, I would implement a <a href=\"http://en.wikipedia.org/wiki/Pushdown_automaton\" rel=\"nofollow\">Push Down Automaton</a> using a Stack and <code>pushing</code> open parentheses on the stack and performing a <code>pop</code> for closing ones - Assuring, that the stack isn't empty. \nSo every occuring closing parentheses has to match the last pushed open one.</p>\n\n<p>For simple cases, a counter is sufficient enough.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T07:16:21.670", "Id": "45066", "ParentId": "45020", "Score": "0" } }, { "body": "<p>Using stack is optimal solution on this question. I would implement as below-</p>\n\n<pre><code>import java.util.Stack;\n\n\npublic class Parenthesis {\n\n public static boolean parenthesisCount(String s){\n if (s== null)\n return false;\n int len=s.length();\n int count=0;\n Stack&lt;Character&gt; pStack=new Stack&lt;Character&gt;();\n char ch;\n for (int i=0;i&lt;len;i++){\n ch=s.charAt(i);\n\n if (ch=='(') {\n pStack.push(ch);\n count=count+1;\n }\n else{\n if ((!pStack.isEmpty()) &amp;&amp; ch==')') {\n pStack.pop();\n count=count-1;}\n\n\n }\n }\n if (pStack.isEmpty() &amp;&amp; count==0)\n return true;\n else\n return false;\n\n }\n\n public static void main(String[] args){\n\n System.out.println(parenthesisCount(\"(add((sdsds)(sdsds))\"));\n\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T21:22:46.480", "Id": "388125", "Score": "0", "body": "Why you have used count?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T13:10:49.053", "Id": "45082", "ParentId": "45020", "Score": "0" } } ]
{ "AcceptedAnswerId": "45035", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T20:44:05.857", "Id": "45020", "Score": "6", "Tags": [ "java", "recursion", "linked-list", "validation" ], "Title": "Validating that all open/close parentheses are correctly matched" }
45020
<p>I wrote a messy function and I am wondering if you see any way I could clean it up. Essentially it takes in a list <code>e_1=2&amp;e_2=23&amp;e_3=1</code> and makes a queryset out of it, maintaining the ordering.</p> <pre><code>from operator import itemgetter def ids_to_students(items, prefix=0): if prefix == 0: # Make ordered QuerySets of Students based on there ids etuples = sorted([(k,v) for k,v in items if k[:2] == 'e_'], key=itemgetter(0)) ituples = sorted([(k,v) for k,v in items if k[:2] == 'i_'], key=itemgetter(0)) tuples = etuples+ituples else: tuples = sorted([(k,v) for k,v in items if k[:2] == '%s_'%prefix], key=itemgetter(0)) pk_list = [v for (k,v) in tuples] clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in enumerate(pk_list)]) ordering = 'CASE %s END' % clauses students = Student.objects.filter(pk__in=pk_list).extra( select={'ordering': ordering}, order_by=('ordering',)) return students </code></pre> <p>It's called like this:</p> <pre><code>students = ids_to_students(request.GET.items()) e_students = ids_to_students(request.GET.items(), 'e') </code></pre>
[]
[ { "body": "<p>Tuples are sorted primarily by the first item of each. If they are all unique, specifying <code>key=itemgetter(0)</code> makes no difference. </p>\n\n<p>This code</p>\n\n<pre><code>if prefix == 0:\n etuples = sorted([(k,v) for k,v in items if k[:2] == 'e_'], key=itemgetter(0))\n ituples = sorted([(k,v) for k,v in items if k[:2] == 'i_'], key=itemgetter(0))\n tuples = etuples+ituples\nelse:\n tuples = sorted([(k,v) for k,v in items if k[:2] == '%s_'%prefix], key=itemgetter(0))\n</code></pre>\n\n<p>can be rearranged like this to avoid repetition:</p>\n\n<pre><code>prefixes = ['%s_'%prefix] if prefix else ['e_', 'i_']\ntuples = sorted(item for item in items if item[0][:2] in prefixes)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T04:31:55.363", "Id": "78467", "Score": "0", "body": "Great improvement! I used your improvement in final code of my answer, hope you do not mind." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T22:25:37.170", "Id": "45037", "ParentId": "45023", "Score": "6" } }, { "body": "<p>In addition to logic, which Janne's answer covered, here is some style analysis (which is an important part of writing good code):</p>\n\n<p>First - it's nice to have a good docstring, with all the information about the function - what does it do, what does it take, what it returns.</p>\n\n<pre><code>from operator import itemgetter\n</code></pre>\n\n<p>This can be a matter of opinion, but it's a good practice not to import member of a module. So doing <code>import operator</code> and calling <code>operator.itemgetter</code> in your module might give someone who is reading your code a better idea of where the <code>itemgetter</code> is coming from.</p>\n\n<pre><code>def ids_to_students(items, prefix=0):\n</code></pre>\n\n<p>Since prefix is a string, it might be more clear to provide default value as <code>''</code>.</p>\n\n<pre><code>etuples = sorted([(k,v) for k,v in items if k[:2] == 'e_'], key=itemgetter(0))\n</code></pre>\n\n<p>Only one space before and after <code>=</code>, missing space after comma.</p>\n\n<pre><code>tuples = etuples+ituples\n</code></pre>\n\n<p>One space before and after <code>+</code> sign.</p>\n\n<pre><code>tuples = sorted([(k,v) for k,v in items if k[:2] == '%s_'%prefix], key=itemgetter(0))\n</code></pre>\n\n<p>This line is longer then 80 characters, which is in most cases a very reasonable limit. Breaking it down into two is a good idea.</p>\n\n<pre><code>students = Student.objects.filter(pk__in=pk_list).extra(\n select={'ordering': ordering}, order_by=('ordering',))\n</code></pre>\n\n<p>When you break the statement into two lines - indent the second line by the multiple of 4.</p>\n\n<p>And the whole thing (I took the list comprehension from Janne's answer, don't forget to upvote it):</p>\n\n<pre><code>def ids_to_students(items, prefix=''):\n \"\"\"Converts request items into a queryset.\n\n Usage:\n &gt;&gt;&gt; students = ids_to_students(request.GET.items())\n &gt;&gt;&gt; e_students = ids_to_students(request.GET.items(), 'e')\n\n Args:\n items: A dict of request.GET.items().\n prefix: A prefix for DB entries.\n\n Returns:\n A queryset.\n \"\"\"\n # Make ordered QuerySets of Students based on their ids.\n prefixes = ['%s_' % prefix] if prefix else ['e_', 'i_']\n tuples = sorted(item for item in items if item[0][:2] in prefixes)\n\n pk_list = [v for (k, v) in tuples]\n clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in enumerate(pk_list)])\n ordering = 'CASE %s END' % clauses\n students = Student.objects.filter(pk__in=pk_list).extra(\n select={'ordering': ordering}, order_by=('ordering', ))\n return students\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T03:49:11.090", "Id": "45059", "ParentId": "45023", "Score": "6" } } ]
{ "AcceptedAnswerId": "45037", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T21:21:38.527", "Id": "45023", "Score": "7", "Tags": [ "python", "django" ], "Title": "Building SQL query" }
45023
<p>The lifetimes of various objects referring to each other are sometimes only known at runtime. For example, in a side scrolling shooter game, a <code>HomingMissile</code> instance might have a pointer to the <code>Target</code> instance it is following. But if the <code>Target</code> is killed before the missile arrives, the <code>HomingMissile</code> is left with a dangling pointer to where the <code>Target</code> was in memory, likely causing a segmentation fault.</p> <p>It would be nice if pointers could just be checked for validity, but it is obvious that the following example for detecting wether or not <code>ptrToFoo</code> is valid by comparison with <code>nullptr</code> will fail, as a pointer is merely an address, having no knowledge about the lifetime of the pointed object.</p> <pre><code>struct Foo { const char *hello() const { return "hello world"; } }; int main() { Foo *foo = new Foo; Foo *ptrToFoo = foo; std::cout &lt;&lt; ((ptrToFoo == nullptr) ? "expired!" : ptrToFoo-&gt;hello()) &lt;&lt; "\n"; delete foo; std::cout &lt;&lt; ((ptrToFoo == nullptr) ? "expired!" : ptrToFoo-&gt;hello()) &lt;&lt; "\n"; return 0; } //output: //hello world //hello world &lt;- bad </code></pre> <p>C++11 smart pointers are great, but they do not feel like the right tool for the job. It makes no sense for the <code>HomingMissile</code> to own the <code>Target</code> trough a <code>std::shared_ptr</code> or a <code>std::unique_ptr</code>. Having <code>HomingMissile</code> hold a <code>std::weak_ptr</code> to the <code>Target</code> does allow checking the state of the <code>target</code> instance, but it forces the <code>Target</code> to be owned trough a <code>std::shared_ptr</code> by some unrelated third party. In addition, constantly calling <code>weak_ptr::lock()</code> is cumbersome at least.</p> <p>As a solution, I have been writing a different kind of smart pointer, one that does not imply any kind of ownership at all. <strong>The idea is to have a reference-count-based pointer-like class that knows if the pointed object has been destroyed or not</strong>, preventing the "dangling pointer" problem:</p> <pre><code>struct Foo : public ObserverPtr&lt;Foo&gt;::Observable { const char *hello() const { return "hello world"; } }; int main() { Foo *foo = new Foo; ObserverPtr&lt;Foo&gt; ptrToFoo(*foo); std::cout &lt;&lt; (ptrToFoo.expired() ? "expired!" : ptrToFoo-&gt;hello()) &lt;&lt; "\n"; delete foo; std::cout &lt;&lt; (ptrToFoo.expired() ? "expired!" : ptrToFoo-&gt;hello()) &lt;&lt; "\n"; return 0; } //output: //hello world //expired! </code></pre> <p>The ObserverPtr implementation should work for all classes derived from <code>ObserverPtr&lt;/*derived class name*/&gt;::Observable</code>, independently of allocation type (stack, heap, gobal) or any type qualifiers (const, volatile). Multithreading support is not required at this stage.</p> <hr> <h2>Implementation of ObserverPtr:</h2> <pre><code>template&lt;class T&gt; class ObserverPtr { public: class Observable { protected: /////////////////////////////////////////////////////////////////////// // Reset all ObserverPtrs that point to this ObserverPtr::Observable- // ..derived object. void resetObserverPtrs() { if(tracker_-&gt;referenceCount &gt; 1) { tracker_-&gt;pointer = nullptr; tracker_-&gt;referenceCount--; tracker_ = new Tracker {static_cast&lt;T*&gt;(this), 1}; } } //The constructor and destructor are protected. This ensures that the //..class ObserverPtr::Observable cannot exist on it's own but must be //..inherited. Observable() : tracker_(new Tracker {static_cast&lt;T*&gt;(this), 1}) { } ~Observable() { if(tracker_-&gt;referenceCount &gt; 1) { tracker_-&gt;pointer = nullptr; tracker_-&gt;referenceCount--; } else delete tracker_; } private: //The Tracker is a reference counted, heap allocated object that //..is used internally by ObserverPtr system for tracking the state //..of the pointed object. struct Tracker { T *pointer; unsigned int referenceCount; }; Tracker* tracker_; friend ObserverPtr; }; /////////////////////////////////////////////////////////////////////////// // Construct a blank ObserverPtr that points to or observes nothing ObserverPtr() : tracker_(nullptr) { } /////////////////////////////////////////////////////////////////////////// // Construct an ObserverPtr to observe an observable class. ObserverPtr(T &amp;observed) : tracker_(observed.tracker_) { tracker_-&gt;referenceCount++; } /////////////////////////////////////////////////////////////////////////// // Construct an ObserverPtr as a copy of another ObserverPtr ObserverPtr(const ObserverPtr &amp;other) : tracker_(other.tracker_) { tracker_-&gt;referenceCount++; } //TODO: Move constructor /////////////////////////////////////////////////////////////////////////// // Destructor. ~ObserverPtr() { reset(); } /////////////////////////////////////////////////////////////////////////// // Resets the the ObserverPtr to observe nothing. void reset() { if(tracker_ != nullptr) { if(tracker_-&gt;referenceCount &gt; 1) tracker_-&gt;referenceCount--; else delete tracker_; tracker_ = nullptr; } } /////////////////////////////////////////////////////////////////////////// // Reset the ObserverPtr to point to and observe a different object void reset(const T &amp;observed) { if(tracker_ != observed.tracker_) //prevent resetting to itself { reset(); tracker_ = observed.tracker_; if(tracker_ != nullptr) { tracker_-&gt;referenceCount++; } } } /////////////////////////////////////////////////////////////////////////// // Reset the ObserverPtr to observe nothing. ObserverPtr &amp;operator=(std::nullptr_t) { reset(); return *this; } /////////////////////////////////////////////////////////////////////////// // Reset the ObserverPtr observe the same object as another ObserverPtr ObserverPtr &amp;operator=(const ObserverPtr &amp;other) { if(tracker_ != other.tracker_) //prevent self-assignment { reset(); tracker_ = other.tracker_; if(tracker_ != nullptr) { tracker_-&gt;referenceCount++; } } return *this; } //TODO: Move assignment operator /////////////////////////////////////////////////////////////////////////// // Swap the observed objects between two ObserverPtrs void swap(ObserverPtr &amp;other) { typename ObserverPtr::Observable::Tracker *previousSentry = tracker_; tracker_ = other.tracker_; other.tracker_ = previousSentry; } /////////////////////////////////////////////////////////////////////////// // Dereference member of the object pointed by ObserverPtr. // ..Calling this on a expired ObserverPtr results in undefined behaviour! T *operator-&gt;() const { return tracker_-&gt;pointer; } /////////////////////////////////////////////////////////////////////////// // Dereference the ObserverPtr. Returns a reference to the pointed object. // ..Calling this on a expired ObserverPtr results in undefined behaviour! T &amp;operator*() const { return *(tracker_-&gt;pointer); } /////////////////////////////////////////////////////////////////////////// // Dereference the ObserverPtr. Returns a reference to the pointed object. // ..Calling this on a expired ObserverPtr results in undefined behaviour! T *get() const { return tracker_-&gt;pointer; } /////////////////////////////////////////////////////////////////////////// // Return true if the ObserverPtr is expired. Returns true if the observed // ..object has been destroyed, or if the ObserverPtr has been constructed // ..or reset to observe nothing. bool expired() const { if(tracker_ == nullptr) return true; if(tracker_-&gt;pointer == nullptr) return true; return false; } /////////////////////////////////////////////////////////////////////////// // Return true if the ObserverPtr is expired. Equivalent to expired(). bool operator==(std::nullptr_t) const { return expired(); } /////////////////////////////////////////////////////////////////////////// // Return true if the ObserverPtr is not expired. Equivalent to !expired(). bool operator!=(std::nullptr_t) const { return !expired(); } /////////////////////////////////////////////////////////////////////////// // Test two ObserverPtrs for equality. Returns true if both pointers point // ..to the same object or if both pointers are expired. bool operator==(const ObserverPtr &amp;other) const { if(expired()) return other.expired(); else { if(other.expired()) return false; else return tracker_-&gt;pointer == other.tracker_-&gt;pointer; } } /////////////////////////////////////////////////////////////////////////// // Test two ObserverPtrs for inequality. Returns false if both pointers // ..point to the same object or if both pointers are expired. bool operator!=(const ObserverPtr &amp;other) const { return !((*this) == other); } private: typename Observable::Tracker *tracker_; }; </code></pre> <p><strong>The implementation is still work in progress:</strong></p> <ul> <li><p>A move constructor has not yet been implemented.</p></li> <li><p>A move assignment operator has not yet been implemented.</p></li> <li><p>Implicit type conversions between ObserverPtrs of different types are not supported, and I think that it should stay that way. Possibly an overload of <code>std::static_pointer_cast</code> should be provided.</p></li> <li><p>An ObserverPtr to a const- declared object (<code>ObserverPtr&lt;const Foo&gt;</code>) does not currently compile.</p></li> <li><p>The code has not yet been troughoutly tested.</p></li> <li><p>The code is at this stage completely unoptimized.</p></li> <li><p>I am still relatively new to C++ and especially C++11, so the code may not be as good as it could be, and writing a robust smart pointer is surprisingly difficult.</p></li> </ul> <p>I would like to receive feedback on the concept in general and my implementation. I currently cannot figure out how to add support for pointing to <code>const</code> objects, but I am working on it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T23:53:20.680", "Id": "78419", "Score": "0", "body": "I'm surprised that the std pointers aren't good enough. Target has to be owned by something which controls its lifetime. If you don't want to have Target in a shared_ptr and give Missile a weak_ptr, then why not have Target in a unique_ptr and give Missile a simple reference to the unique_ptr?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:07:51.270", "Id": "78420", "Score": "1", "body": "@ChrisW I disagree with that solution, since there would be many missiles and targets that are all stored (and owned by) a single vector of std::unique_ptrs. What happens when a target gets destroyed? is the manager holding the vector forced to keep a null unique_ptr in the vector indefinitely, in case a missile checks if the unique_ptr in the vector is null? even a linked list wouldn't help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:22:35.097", "Id": "78423", "Score": "0", "body": "Why don't you use a shared_ptr for Target and weak_ptr in Missile? That allows the shared_ptr to be destroyed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:33:55.720", "Id": "78426", "Score": "0", "body": "Because the approach just _feels_ wrong and needlessly complicated, as explained in the question. std::shared_ptrs are very complicated beasts, because they have to support custom deleters, thread safety and they must always guarantee correct ownership semantics. The proposed ObserverPtr would be actually _designed_ for the case I explained." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:43:30.347", "Id": "78429", "Score": "1", "body": "I won't post this as an answer then, but as a comment: you can use standard shared_ptr and weak_ptr instead of 'reinventing the wheel'. Your ObserverPtr is analogous to a weak_ptr, and your ObserverPtr::Observable is analogous to a shared_ptr." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:48:22.263", "Id": "78430", "Score": "1", "body": "You have edited your post 8 or 9 times. If you edit it more than 10 times it will be [auto-converted to Community Wiki, which may remove people's incentive to answer it](http://meta.stackexchange.com/a/11741/139866): so perhaps stop editing it now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:54:23.540", "Id": "78431", "Score": "0", "body": "@ChrishW In fact what you described is exactly how I got the idea for ObserverPtr. I just disliked being forced to use shared_ptr to own the referred object. And writing this has been a good exercise. Good point on the community wiki conversion, I forgot about that one completely." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T06:41:32.680", "Id": "78479", "Score": "0", "body": "Sounds like you need `std::weak_ptr<>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-26T16:42:44.283", "Id": "186657", "Score": "0", "body": "Actually the solution that might sound surprising to you is not to use objects and smart pointers at all. If you are actually implementing a game, then smart pointers (read: heap allocation of individual objects) may be too slow, anyway. Using handles (like entity id handle from Component Entity System) could be a solution. If you use handles, you can manage the memory in a smart way, for example versioning your objects/entities. The handle would still be \"dangling\", but that can be checked. Of course you might also try to prevent the danglingness by using events, or singals-slots." } ]
[ { "body": "<blockquote>\n<pre><code>Foo *foo = new Foo;\n</code></pre>\n</blockquote>\n\n<p>This isn't safe: an exception later on will leak the object.</p>\n\n<blockquote>\n<pre><code>///////////////////////////////////////////////////////////////////////\n</code></pre>\n</blockquote>\n\n<p>These waste vertical space which makes to harder to read.</p>\n\n<blockquote>\n<pre><code>void resetObserverPtrs()\n</code></pre>\n</blockquote>\n\n<p>This isn't called from anywhere.</p>\n\n<blockquote>\n<pre><code>void reset(const T &amp;observed)\n</code></pre>\n</blockquote>\n\n<p>This isn't called from anywhere; but it is public. Perhaps it should be an assignment <code>operator=</code>.</p>\n\n<p>I'm not sure why you have <code>if(tracker_ != nullptr)</code> in this method: IMO <code>observed.tracker_</code> can never be null (unless <code>observed</code> has been destroyed, in which case it should not have been passed as a parameter to this method).</p>\n\n<blockquote>\n<pre><code>void swap(ObserverPtr &amp;other)\n</code></pre>\n</blockquote>\n\n<p>Maybe use std::swap to implement this method.</p>\n\n<blockquote>\n<pre><code>T *get() const\n</code></pre>\n</blockquote>\n\n<p>Instead of undefined behaviour, <code>if (expired()) return nullptr;</code>.</p>\n\n<hr>\n\n<p>Also, you can use standard shared_ptr and weak_ptr instead of 'reinventing the wheel'. Your ObserverPtr is analogous to a weak_ptr, and your ObserverPtr::Observable is analogous to a shared_ptr.</p>\n\n<hr>\n\n<blockquote>\n <p>However, while <code>Foo *foo = new Foo;</code> is not safe, does it really matter?</p>\n</blockquote>\n\n<p>It's up to you whether it matters: see <a href=\"https://codereview.meta.stackexchange.com/a/1441/34757\">this meta-answer</a> for details.</p>\n\n<blockquote>\n <p>It's just a short usage example</p>\n</blockquote>\n\n<p>Then it's an example of unsafe usage, is all I'm saying. <a href=\"https://codereview.stackexchange.com/help/on-topic\">What questions are on-topic for this site?</a> says, \"Is it actual code from a project rather than pseudo-code or example code?\"</p>\n\n<p>You also said, \"The ObserverPtr implementation should work ... independently of allocation type (stack, heap, gobal)\" and said you don't want to use standard smart pointers: so maybe you're intending to use <code>Foo*</code> in your real code as well as in your example code.</p>\n\n<p>Another problem, which I didn't mention previously, is that because Observable contains a naked <code>Tracker*</code> pointer, you should delete or override the copy constructor and assignment operator for Observable. Deleting those will make it difficult to store Observable instances in standard containers. You can store naked pointers to Observable instances (e.g. <code>std::list&lt;Foo*&gt;</code> though not <code>std::list&lt;Foo&gt;</code>, but naked pointers aren't exception safe.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:39:33.190", "Id": "78440", "Score": "0", "body": "Point taken, the two places where `new Tracker {static_cast<T*>(this), 1}` can be fould should be `new(std::nothrow) Tracker {static_cast<T*>(this), 1}` instead. However, while `Foo *foo = new Foo;` is not safe, does it really matter? It's just a short usage example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:49:54.320", "Id": "78443", "Score": "0", "body": "I agree with the other ones. The reason why there is `reset(const T &observed)` instead of `operator=(const T &observed)` is that I just copied the style of std::shared_ptr where there is the distinction that reset is used for releasing ownership and possibly taking ownership of a previously unmanaged object while operator= is used for releasing ownership and possibly transferring ownership of objects between pointers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T03:01:36.833", "Id": "78445", "Score": "0", "body": "@user1062874 I updated my answer to reply to your question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T03:09:18.133", "Id": "78446", "Score": "0", "body": "\"Point taken, ...\" -- After you create a Foo* instance as a local variable, if any of the next statements throw then the Foo* instance is leaked. That's a reason for using smart pointers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T03:19:15.047", "Id": "78448", "Score": "0", "body": "While the part of the code I have submitted for review is intended to be the implemtation of ObserverPtr, not the usage example, I do agree that I am promoting bad style in the usage example, and I would fix it immediately if I did not have just a couple of edits left before the question gets transferred to the community wiki. Thus I would kindly appreciate if someone with enough rep would fix the two usage examples for me. In any case I will do it myself when I will append my finalized implementation of ObserverPtr to the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T03:25:18.957", "Id": "78449", "Score": "0", "body": "@user1062874 People won't edit the OP after it has been reviewed ([see this link](http://meta.codereview.stackexchange.com/a/1483/34757)), but you're welcome to append the finalized version of the code to the question (without editing the original text of the question)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T03:37:24.917", "Id": "78458", "Score": "0", "body": "Should I post the revised code as an answer instead of appending it to the OP?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T03:45:30.203", "Id": "78462", "Score": "0", "body": "@user1062874 If you want a code review of the revised version, then post it as a separate/new question [as described here](http://meta.codereview.stackexchange.com/a/1066/34757). If you post it as an answer here, or append it to the OP here, it won't be reviewed again." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:05:06.903", "Id": "45051", "ParentId": "45025", "Score": "5" } }, { "body": "<p>Sounds like what you need is a weak_ptr&lt;></p>\n\n<pre><code>#include &lt;memory&gt;\n#include &lt;iostream&gt;\nstruct Foo\n{\n const char *hello() const\n {\n return \"hello world\";\n }\n};\n\nvoid test(std::weak_ptr&lt;Foo&gt;&amp; w)\n{\n std::cout &lt;&lt; (w.expired() ? \"expired\" : w.lock()-&gt;hello()) &lt;&lt; \"\\n\";\n}\n\nint main()\n{\n std::shared_ptr&lt;Foo&gt; foo(new Foo);\n std::weak_ptr&lt;Foo&gt; ptrToFoo(foo);\n\n test(ptrToFoo);\n foo.reset(); // Reset the pointer.\n test(ptrToFoo);\n}\n</code></pre>\n\n<p>Run:</p>\n\n<pre><code>&gt; ./a.out\nhello world\nexpired\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T07:10:22.877", "Id": "78481", "Score": "0", "body": "I am aware that I can use a `std::weak_ptr` to keep track of an object of unknown lifetime (that's the solution I have previously resorted to), but I don't like how I'm then forced to own the object trough a `std::shared_ptr` and call `std::weak_ptr::lock()` every time I dereference the pointer. What is the rationale for not providing operator* and operator-> for weak_ptr? I assume that it is related to concurrency and multithreading?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T07:50:02.027", "Id": "78483", "Score": "0", "body": "If writing my own application specific smart pointer is a bad idea, or just a worse decision than using `std::shared_ptr` and `std::weak_ptr` even when ownership semantics and concurrency/multithreading support are not actually needed and only contribute in the form of additional application complexity and lower performance, I would like to know why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T07:57:08.757", "Id": "78484", "Score": "0", "body": "Writing your own smart pointer is a very bad idea (only useful as an educational exercise). It is extremely easy to get wrong. Even when you get most of it write the corner cases always catch you. Would you write your own vector class? The provided smart pointers are highly tested and very efficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T08:17:12.080", "Id": "78485", "Score": "0", "body": "Fine, I will reconsider sticking with the standard smart pointers. In any case I am still going to complete ObserverPtr as an exercise. For me computer programming is just a hobby, so no worries, there is no chance that I am going to infect some commercial codebase with this abomination." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:18:34.743", "Id": "78524", "Score": "0", "body": "@user1062874 If you don't like calling lock and if your code isn't multi-threaded, perhaps you can define a `Foo* get(weak_ptr<Foo> weak) { shared_ptr<Foo> shared = weak.lock(); return shared.get(); }` function, to get the raw pointer (or null) from a weak_ptr in one function call." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T06:51:13.717", "Id": "45064", "ParentId": "45025", "Score": "1" } } ]
{ "AcceptedAnswerId": "45051", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T21:34:45.883", "Id": "45025", "Score": "5", "Tags": [ "c++", "c++11", "pointers", "smart-pointers" ], "Title": "Proposed solution to dangling pointers: a non-owning smart pointer" }
45025
<p>I am experimenting with streams and lambdas in Java 8. This is my first serious foray using functional programming concepts; I'd like a critique on this code.</p> <p>This code finds the Cartesian product of three sets of <code>int</code>s. My questions/complaints about this snippet are:</p> <ul> <li>Are nested <code>flatMaps</code> really the best (most understandable, most CPU/memory efficient) way to do an arbitrary Cartesian product? Or should I stick to imperative style for Cartesian products?</li> <li>Is there a better way to format nested lambdas (see, e.g., my use of <code>flatMap</code>)?</li> </ul> <p>I just learned about <a href="http://download.java.net/jdk8/docs/api/java/util/stream/Collectors.html" rel="noreferrer">Collectors</a>; those might be what I need. I'm still learning how to best combine these things.</p> <hr> <pre><code>long count = IntStream.rangeClosed(0,9) /* 0 &lt;= A &lt;= 9 */ .parallel() .mapToObj(Integer::valueOf) .flatMap(a -&gt; IntStream.rangeClosed(0,9) /* 0 &lt;= B &lt;= 9 */ .mapToObj(Integer::valueOf) .flatMap(b -&gt; IntStream.rangeClosed(0,9) /* 0 &lt;= C &lt;= 9 */ .mapToObj(c -&gt; (new Product()).A(a).B(b).C(c)) ) ).count(); System.out.println("Enjoy your Cartesian product." + count); </code></pre> <p><strong>UPDATE:</strong> I deliberately omitted boilerplate code and class/method definitions, for brevity. The only important thing about <code>Product</code> is that it stores three <code>int</code>s.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:39:17.333", "Id": "78428", "Score": "1", "body": "What is `Product`... you should probably include that in the review?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T15:40:46.947", "Id": "78521", "Score": "1", "body": "I took the liberty of rolling-back the edit you made because it invalidated parts of the answers that were previously given. Have a look at the [meta post about this exact thing](http://meta.codereview.stackexchange.com/a/1483/31503)" } ]
[ { "body": "<p>Your code is odd in the sense that it is going to a lot of effort to calculate that 10<sup>3</sup> is 1000.</p>\n\n<p>I understand why you are doing it, but I took the liberty of changing the <code>count()</code> terminating function and replacing it with:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\n\n.......\n.forEachOrdered(prod -&gt; sb.append(prod.toString()).append(\"\\n\");\n</code></pre>\n\n<p>This way we can store each result, instead of just counting it.</p>\n\n<p>There are a few things to go through here.</p>\n\n<h2>Product</h2>\n\n<p>This class looks awkward:</p>\n\n<blockquote>\n<pre><code> .mapToObj(c -&gt; (new Product()).A(a).B(b).C(c))\n</code></pre>\n</blockquote>\n\n<p>Why not just have a useful constructor on Product like:</p>\n\n<pre><code> public Product(int a, int b, int c) {\n super();\n this.a = a;\n this.b = b;\n this.c = c;\n }\n</code></pre>\n\n<p>Then, your mapping would look like:</p>\n\n<pre><code> .mapToObj(c -&gt; new Product(a, b, c))\n</code></pre>\n\n<h2>Magic Numbers</h2>\n\n<p>You have 0 and 9 as magic numbers in multiple places. These should be declared as (effective) constants, or calculated somehow. With the 9 value especially, if you want to change the size of the product you have to change it in three places.</p>\n\n<h2>int vs. Integer</h2>\n\n<p>You start off with an <code>IntStream</code>, but then convert it to a <code>Stream&lt;Integer&gt;</code>. Why? If you can leave things as primitives, you should.</p>\n\n<h2>The actual stream</h2>\n\n<p>The most concerning aspect is the stream itself.</p>\n\n<p>The flatMap operation is not doing what I think you think it does....</p>\n\n<p>Let's consider the contents of the stream as it goes through things:</p>\n\n<ol>\n<li>'a' range from 0-9 IntStream</li>\n<li>convert each int to an Integer</li>\n<li>for each Integer, flatMap that Integer</li>\n<li>the flatMap creates an IntStream which it converts to a Stream</li>\n<li>even though we are flatMapping the 'a' value, we are not using the 'a' value in the mapping. All we are really doing is creating a new 'b' value, and who cares that the stream now has the b values streaming through....</li>\n<li>with these 'b' values on the stream, we then flatMap again....</li>\n<li>again, we ignore what the actual 'b' value is, abut we generate a new 'c' value in a third nested stream, and then we combine the 'a' and 'b' values which are 'in scope', with the 'c' value from the stream, and we make a Product.</li>\n</ol>\n\n<p>The point of what I am saying is that you actually are only using the Stream in the most inside IntStream, the 'c' stream. All the other streams are just 'tokens' that you need to count the events you are doing. A for-loop is the right thing for this construct (if it was not for the parallelism). If you include the parallelism, then a fork-join process is right. Not a stream.</p>\n\n<h2>My Attempt</h2>\n\n<p>I am not claiming this is right, or best practice, but consider this attempt to get essentially the same result as you:</p>\n\n<pre><code>/** Append an int to an array after the last array item **/\npublic static final int[] append(int[] base, int val) {\n int[] ret = Arrays.copyOf(base, base.length + 1);\n ret[base.length] = val;\n return ret;\n}\n\n/** Stream an int range and map to an appended array */\nprivate static final Stream&lt;int[]&gt; appendInts(int[] base, int size) {\n return IntStream.rangeClosed(0, size).mapToObj(a -&gt; Cartesian.append(base, a));\n}\n\npublic static void main(String[] args) {\n\n final int last = 9;\n final StringBuilder sb = new StringBuilder();\n IntStream.rangeClosed(0,last) /* 0 &lt;= A &lt;= 9 */\n .parallel()\n .mapToObj(a -&gt; new int[]{a})\n // stream is int[1] array\n .flatMap(ab -&gt; appendInts(ab, last))\n // stream is int[2] array\n .flatMap(abc -&gt; appendInts(abc, last))\n // stream is int[3] array\n .forEachOrdered(res -&gt; sb.append(Arrays.toString(res)).append(\"\\n\"));;\n System.out.println(\"Enjoy your Cartesian product.\" + sb.toString());\n}\n</code></pre>\n\n<h2>Update</h2>\n\n<p>I have rewritten the OP's code to extract the stream preparations. Consider the following code:</p>\n\n<pre><code> // convert two input values to a stream consisting of an arrays of int\n BiFunction&lt;Integer, Integer, Stream&lt;int[]&gt;&gt; stage3 = (a,b) -&gt; {\n return IntStream.rangeClosed(0, last).mapToObj(c -&gt; new int[]{a, b, c});\n };\n\n // convert an input value to a stream consisting of an arrays of int\n Function&lt;Integer, Stream&lt;int[]&gt;&gt; stage2 = a -&gt; {\n Stream&lt;Integer&gt; s = IntStream.rangeClosed(0, last).boxed();\n Stream&lt;int[]&gt; ret = s.flatMap(b -&gt; stage3.apply(a, b));\n return ret;\n };\n\n IntStream.rangeClosed(0,last) /* 0 &lt;= A &lt;= 9 */\n .parallel()\n .boxed()\n .flatMap(a -&gt; stage2.apply(a))\n .map(r -&gt; Arrays.toString(r))\n .forEachOrdered(System.out::println);\n</code></pre>\n\n<p>Which is essentially what the OP's code does.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:20:35.730", "Id": "45052", "ParentId": "45026", "Score": "15" } }, { "body": "<p>I do not have much to add to <a href=\"https://codereview.stackexchange.com/a/45052/32231\">@rofl's answer</a>, but I <strong>do</strong> have another way to show to create Cartesian Products while using streams, which I think might be very interesting aswell.</p>\n\n<h1>Important note</h1>\n\n<p>I have made a mistake while reading the intention of the OP's post. I have confused Cartesian Products with calculating products of the elements of Cartesian Products. I will leave my old answer here as the explanation still holds, and under this answer, I will post the new version of the code, which <em>does</em> do what is expected.</p>\n\n<hr>\n\n<h1>Old answer</h1>\n\n<p>I will also assume that you are collecting the results into a <code>List&lt;Integer&gt;</code>, but you can do anything you want with them of course. Note that <code>Collectors.toList()</code> ensures that the data is ordered, so it is equivalent to printing out in order with <code>forEachOrdered(System.out::println)</code>, however in the collector it creates a list obviously.</p>\n\n<p><strong>First verbose version:</strong></p>\n\n<pre><code>private void printCartesianProductsVerbose() {\n int min = 0;\n int max = 9;\n Supplier&lt;IntStream&gt; streamSupplier = () -&gt; IntStream.rangeClosed(min, max);\n IntBinaryOperator productOperator = (a, b) -&gt; a * b;\n List&lt;Integer&gt; list = streamSupplier.get()\n .flatMap(a -&gt; streamSupplier.get().map(b -&gt; productOperator.applyAsInt(a, b)))\n .flatMap(a -&gt; streamSupplier.get().map(b -&gt; productOperator.applyAsInt(a, b)))\n //Do whatever you want below here\n .boxed()\n .collect(Collectors.toList());\n list.forEach(System.out::println);\n}\n</code></pre>\n\n<p>I will explain what I am doing here, and you should see most of the points as tips to produce better code:</p>\n\n<ol>\n<li>Get rid of the magic numbers, define <code>min</code> and <code>max</code> clearly. Later this might become method input, so you can pass it directly to the <code>rangeClosed()</code> method.</li>\n<li>Create a <code>Supplier&lt;IntStream&gt;</code> for your <code>IntStream.rangeClosed(min, max)</code>, which you would else repeat the whole time. Less chance of mistakes while copying code now as a plus, and easier to change.</li>\n<li>Create a <code>IntBinaryOperator</code> to encapsulate the product operator that happens when calculating <em>Cartesian Products</em>.</li>\n<li><p>Turn the <code>IntStream</code> into a <code>List&lt;Integer&gt;</code>.</p>\n\n<p>4.1. First you need to declare that you want to end up with a list.</p>\n\n<p>4.2. Then you call <code>streamSupplier.get()</code> to get your stream.</p>\n\n<p>4.3. Now the interesting part happens, I flat map the <code>a</code> current integer of the stream, to a new <code>IntStream</code>, note that here I still have access to the <code>a</code> integer.</p>\n\n<p>4.4. Then I apply a mapping to the newly obtained <code>IntStream</code>, and map the <code>b</code> integer to the product of <code>a</code> and <code>b</code>.</p>\n\n<p>4.5. Now the newly obtained <code>IntStream</code> contains the Cartesian Products, and these are via the <code>flatMap()</code> brought back into the original stream.</p>\n\n<p>4.6. Repeat the same <code>flatMap</code> for the Cartesian Product of three integers.</p></li>\n<li><p>Box the ints to Integers, since they are boxed in <code>List&lt;Integer&gt;</code> anyway and it will be easier to write a <code>Collector</code> for a <code>Stream&lt;Integer&gt;</code> than for primitive streams.</p></li>\n<li>Collect them into a <code>List&lt;Integer&gt;</code> via <code>.collect(Collectors.toList())</code>.</li>\n<li>Print the contents of the list.</li>\n</ol>\n\n<p><strong>Generalized version:</strong></p>\n\n<p>The concensus in this version is to generalize everyting as much as possible, such that different functionality can be plugged in at later times. What if you want to make <em>Cartesian Sums</em>, if that even is a thing?</p>\n\n<pre><code>private void printCartesianProducts() {\n int min = 0;\n int max = 9;\n Supplier&lt;IntStream&gt; streamSupplier = () -&gt; IntStream.rangeClosed(min, max).parallel();\n IntBinaryOperator productOperator = (a, b) -&gt; a * b;\n List&lt;Integer&gt; list = createCartesianStream(streamSupplier, productOperator, 3)\n //Do whatever you want below here\n .boxed()\n .collect(Collectors.toList());\n list.forEach(System.out::println);\n}\n\nprivate IntStream createCartesianStream(final Supplier&lt;IntStream&gt; supplier, final IntBinaryOperator binaryOperator, final int count) {\n Objects.requireNonNull(supplier);\n Objects.requireNonNull(binaryOperator);\n if (count &lt; 1) {\n throw new IllegalArgumentException(\"count &lt; 1: count = \" + count);\n }\n IntStream intStream = supplier.get();\n for (int i = 1; i &lt; count; i++) {\n intStream = intStream.flatMap(a -&gt; supplier.get().map(b -&gt; binaryOperator.applyAsInt(a, b)));\n }\n return intStream;\n}\n</code></pre>\n\n<p>This code executes your <code>flatMap</code> a number of times (The first <code>flatMap</code> is essentially one of <code>1</code> to the method used while flat mapping), with every functionality pluggable.</p>\n\n<p><strong>Styling lambdas</strong></p>\n\n<p>Lastly some notes about styling the lambdas, I prefer if every chaining operation is on one line such that it is clearly what the code does. It gets a bit trickier inside flat maps, but even there I prefer keeping it one line as long as it does not get too long.</p>\n\n<hr>\n\n<h1>New answer</h1>\n\n<p>The change to the newer answer is not so big, what I do now is, instead of calculating the answer, I will map the elements to a <code>List&lt;Integer&gt;</code>.</p>\n\n<p><strong>Verbose version</strong>:</p>\n\n<pre><code>private void printCartesianProductsVerbose() {\n int min = 0;\n int max = 9;\n Supplier&lt;Stream&lt;List&lt;Integer&gt;&gt;&gt; streamSupplier = () -&gt; IntStream.rangeClosed(min, max)\n .mapToObj(this::createListAndAdd)\n .parallel();\n BinaryOperator&lt;List&lt;Integer&gt;&gt; addOperator = this::addToList;\n List&lt;List&lt;Integer&gt;&gt; list = streamSupplier.get()\n .flatMap(a -&gt; streamSupplier.get().map(b -&gt; addOperator.apply(a, b)))\n .flatMap(a -&gt; streamSupplier.get().map(b -&gt; addOperator.apply(a, b)))\n //Do whatever you want below here\n .collect(Collectors.toList());\n list.forEach(System.out::println);\n}\n\nprivate &lt;E&gt; List&lt;E&gt; createListAndAdd(final E element) {\n List&lt;E&gt; list = new ArrayList&lt;&gt;();\n list.add(element);\n return list;\n}\n\nprivate &lt;E&gt; List&lt;E&gt; addToList(final List&lt;E&gt; in1, final List&lt;E&gt; in2) {\n List&lt;E&gt; list = new ArrayList&lt;&gt;(in1.size() + in2.size());\n list.addAll(in1);\n list.addAll(in2);\n return list;\n}\n</code></pre>\n\n<p>One notable design choice I made here is to use the type parameter <code>&lt;E&gt;</code> in the methods, instead of the concrete <code>Integer</code> type, such that when changing the type on a later point, I don't need to rewerite those methods.</p>\n\n<p><strong>Generalized version</strong></p>\n\n<pre><code>private void printCartesianProducts() {\n int min = 0;\n int max = 9;\n Supplier&lt;Stream&lt;List&lt;Integer&gt;&gt;&gt; streamSupplier = () -&gt; IntStream.rangeClosed(min, max)\n .mapToObj(this::createListAndAdd)\n .parallel();\n BinaryOperator&lt;List&lt;Integer&gt;&gt; addOperator = this::addToList;\n List&lt;List&lt;Integer&gt;&gt; list = createCartesianStream(streamSupplier, addOperator, 3)\n //Do whatever you want below here\n .collect(Collectors.toList());\n list.forEach(System.out::println);\n}\n\nprivate &lt;E&gt; Stream&lt;List&lt;E&gt;&gt; createCartesianStream(final Supplier&lt;Stream&lt;List&lt;E&gt;&gt;&gt; supplier, final BinaryOperator&lt;List&lt;E&gt;&gt; binaryOperator, final int count) {\n Objects.requireNonNull(supplier);\n Objects.requireNonNull(binaryOperator);\n if (count &lt; 1) {\n throw new IllegalArgumentException(\"count &lt; 1: count = \" + count);\n }\n Stream&lt;List&lt;E&gt;&gt; stream = supplier.get();\n for (int i = 1; i &lt; count; i++) {\n stream = stream.flatMap(a -&gt; supplier.get().map(b -&gt; binaryOperator.apply(a, b)));\n }\n return stream;\n}\n</code></pre>\n\n<p>I believe no more comments need to be added, as the code still does the same as the old answer, but now it does the correct thing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T15:11:14.533", "Id": "45085", "ParentId": "45026", "Score": "11" } }, { "body": "<p>It seems to me that when you asked:</p>\n\n<blockquote>\n <p>Or should I stick to imperative style for Cartesian products?</p>\n</blockquote>\n\n<p>...it was an <em>excellent</em> question--and one that nobody's really tried to answer. What you seem to want to accomplish is apparently roughly equivalent to something like this<sup>1</sup>:</p>\n\n<pre><code>for (int i=0; i&lt;10; i++)\n for (int j=0; j&lt;10; j++)\n for (int k=0; k&lt;10; k++)\n count++;\n // though presumably you'd really want something more like:\n // some_collection.Add(Product(i, j, k));\n</code></pre>\n\n<p>[With the commented out code assuming you add a constructor to <code>Product</code> like @rolfl suggested.]</p>\n\n<p>This is short and simple. Pretty much anybody who knows any 'curly brace' style of language (or nearly anything else with some sort of <code>for</code> loop or a reasonable analog like Fortran's <code>DO</code> loop) can understand it very quickly and easily.</p>\n\n<p>Assuming you're talking about real, production code here (not just exploring new features in Java) I'd have <em>serious</em> reservations about replacing code like this with the code from your question <em>or</em> the code in any of the other answers I've seen.</p>\n\n<p>It's easy to get caught up in cool new features, trying to use them everywhere, whether they really make much sense or not. I don't want to be a wet blanket, ruining the fun of putting new features to use (because believe me, I've been there, and realize it can be a lot of fun) but for real, production code? I'd hate to be the guy who had to explain to his boss what he had gained from my replacing 4 lines of simple code that just about anybody can understand almost without even trying, with 18-20 lines of code that almost nobody can understand without rereading it at least a couple of times--and even at best, they need to know the latest version of Java pretty well to understand it even that quickly.</p>\n\n<p>Bottom line: this doesn't seem to me like a particularly good use of the features. IMO, you're losing more than you gain.</p>\n\n<hr>\n\n<p><sub>\n1. Yes, you're also at least potentially running some of the code in parallel--but for such a trivial computation as this, chances are pretty good that parallel computation gains little or nothing. It'll almost certainly take longer to package the computation up as parallizable tasks, dispatch it to threads, then collect the results, than to just do the computation in a single thread.\n</sub></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T17:16:04.860", "Id": "45149", "ParentId": "45026", "Score": "7" } } ]
{ "AcceptedAnswerId": "45052", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T21:47:25.560", "Id": "45026", "Score": "18", "Tags": [ "java", "functional-programming", "stream", "lambda" ], "Title": "Effective use of multiple streams" }
45026
<p>I have this script that I need to run a tab (jquery). Mainly I need to hide some div and add class (you sure have understood).</p> <p>How should it be written in a more elegant and readable?</p> <pre><code>function fun1(){ $('#tab1 a').addClass('selected'); $('#tab2 a').removeClass('selected'); $('#tab3 a').removeClass('selected'); document.getElementById('div1').style.display='block'; document.getElementById('div2').style.display='none'; document.getElementById('div3').style.display='none'; } function fun2(){ $('#tab1 a').removeClass('selected'); $('#tab2 a').addClass('selected'); $('#tab3 a').removeClass('selected'); document.getElementById('div1').style.display='none'; document.getElementById('div2').style.display='block'; document.getElementById('div3').style.display='none'; } function fun3(){ $('#tab1 a').removeClass('selected'); $('#tab2 a').removeClass('selected'); $('#tab3 a').addClass('selected'); document.getElementById('div1').style.display='none'; document.getElementById('div2').style.display='none'; document.getElementById('div3').style.display='block'; } window.onload = function() { document.getElementById('tab1').onclick=fun1; document.getElementById('tab2').onclick=fun2; document.getElementById('tab3').onclick=fun3; document.getElementById('div1').style.display='block'; document.getElementById('div2').style.display='none'; document.getElementById('div3').style.display='none'; } </code></pre>
[]
[ { "body": "<p>It sure could be written in a more agreeable way ;)</p>\n\n<p>First off, you might want to handle more tabs and divs in the future, so you can gather their <code>id</code>s into an array:</p>\n\n<p>Either 2 arrays : <br>\n<code>var tabs = ['tab1','tab2','tab3'];</code><br>\n<code>var divs = ['div1','div2','div3'];</code></p>\n\n<p>Or maybe 1 array with objects like <code>{ tabId : 'tab1' , divID : 'div1' }</code><br>\nOr maybe you could even just consider tracking how many tabs you have:<br>\n<code>var tabCount = 3;</code></p>\n\n<p>And go from there.</p>\n\n<p>Also, using <code>.onclick</code> is too old skool, consider using <code>https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener</code></p>\n\n<p>Personally, I would probably go for something like this <em>( after renaming the divs and tabs tab0 ,tab1,tab3 and div0,div1, and div2 )</em>:</p>\n\n<pre><code>var tabCount = 3;\n\nfunction handleTabClick()\n{\n //`this` contains the selected tab\n var selectedTabId = this.id;\n //Compare, and contrast\n for( var i = 0 ; i &lt; tabCount ; i++ )\n {\n //Make sure the clicked tab id looks selected \n if( 'tab' + i == selectedTabId )\n {\n $('#' + selectedTabId + ' a').addClass('selected');\n document.getElementById('div'+i).style.display='block';\n }\n else\n {\n $('#' + tab + i + ' a').removeClass('selected'); \n document.getElementById('div'+i).style.display='none';\n }\n }\n}\n\ndocument.addEventListener( \"load\" , function() initializeTabs{\n\n for( var i = 0 ; i &lt; tabCount ; i++ )\n {\n //Get element\n var element = document.getElementById('tab'+i);\n //Add generic even listener\n element.addEventListener( \"click\" , handleTabClick );\n //Only show the first block ( when i is 0, and hence equates false )\n if( i )\n element.style.display='none';\n else\n element.style.display='block'; \n }\n});\n</code></pre>\n\n<p>I did not test this code, but the intent and approach should be clear.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T15:33:38.857", "Id": "45089", "ParentId": "45036", "Score": "3" } }, { "body": "<p>You're hardly using jQuery at all here. You can either get rid of jQuery entirely (as in <a href=\"https://codereview.stackexchange.com/a/45089/14370\">konijn's answer</a>), or you can use it to your advantage. Either way is perfectly acceptable.</p>\n\n<p>Secondly, the logic is basically the same for each tab, it's only the elements that change. What you have now is very repetitive because you basically re-do the logic for each tab. There's no need for this.</p>\n\n<p>And as konijn points out, you're using old school event handling; again you can go with konijn's jQuery-less code, or you can use jQuery to your advantage.</p>\n\n<p>Lastly, instead of having to hard-code your element IDs, it's more flexible to declare the relationship between a tab link and a DIV in HTML. For instance:</p>\n\n<pre><code>&lt;a class=\"tab\" href=\"#div1\"&gt;1st tab&lt;/a&gt;\n&lt;a class=\"tab\" href=\"#div2\"&gt;2nd tab&lt;/a&gt;\n&lt;a class=\"tab\" href=\"#div3\"&gt;3rd tab&lt;/a&gt;\n\n&lt;div id=\"div1\"&gt;...&lt;/div&gt;\n&lt;div id=\"div2\"&gt;...&lt;/div&gt;\n&lt;div id=\"div3\"&gt;...&lt;/div&gt;\n</code></pre>\n\n<p>Note that the <code>href</code> attribute for the links point to a DIV. The nice part is that this works <em>even if the user doesn't have JavaScript enabled</em>; a <code>#someId</code> link will scroll the page to show the element with that ID. It's not the same as having real tabs, but it's as good a substitute as any.</p>\n\n<p>Point is that if you add more tabs, you only have to change the HTML. The JavaScript will \"just work\".</p>\n\n<p>In the code below, I'm using jQuery to put all this together. <a href=\"http://jsfiddle.net/22WWc/\" rel=\"nofollow noreferrer\">Here's a demo</a></p>\n\n<pre><code>function initializeTabs(selector) {\n var tabs = $(selector), // get the tab links\n first;\n\n // helper function to hide a tab's element\n function deselectTab(tab) {\n tab.removeClass(\"selected\").data(\"pane\").hide();\n }\n\n // helper function to show a tab's element\n function selectTab(tab) {\n tab.addClass(\"selected\").data(\"pane\").show();\n }\n\n // get the elements that the tabs should show/hide\n tabs.each(function () {\n var tab = $(this),\n paneId = tab.attr(\"href\");\n tab.data(\"pane\", $(paneId));\n });\n\n // set up the click-event handling\n tabs.on(\"click\", function (event) {\n var target = $(this);\n\n // don't follow the links\n event.preventDefault()\n\n // stop here if the tab's already selected\n if( target.hasClass(\"selected\") ) { return; }\n\n // hide the currently selected tab\n deselectTab(tabs.filter(\".selected\"));\n\n // show the clicked tab\n selectTab(target);\n });\n\n // show the first tab\n first = tabs.eq(0);\n selectTab(first);\n\n // hide the others\n tabs.not(first).each(function () {\n deselectTab($(this));\n });\n}\n\n// onload\n$(function () {\n initializeTabs(\"a.tab\");\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:34:20.707", "Id": "45092", "ParentId": "45036", "Score": "2" } }, { "body": "<p>Thought id add a version in here that simplifies the JavaScript but relies on the html using specific classes.</p>\n\n<p>HTML</p>\n\n<pre><code>&lt;div class=\"tabs-nav\"&gt;\n &lt;a href=\"#\" class=\"item1 selected\"&gt;Item 1&lt;/a&gt;\n &lt;a href=\"#\" class=\"item2\"&gt;Item 2&lt;/a&gt;\n &lt;a href=\"#\" class=\"item3\"&gt;Item 3&lt;/a&gt;\n&lt;/div&gt;\n\n&lt;div class=\"content content-item1\"&gt;&lt;/div&gt;\n&lt;div class=\"content content-item2 hidden\"&gt;&lt;/div&gt;\n&lt;div class=\"content content-item3 hidden\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>JAVASCRIPT</p>\n\n<pre><code>$(function () {\n $('.tabs-nav a').click(function (e) {\n e.preventDefault();\n if (!$(this).hasClass(\"selected\")) {\n $('.tabs-nav a').removeClass(\"selected\");\n $('.content').hide();\n\n $('.content-' + $(this).attr(\"class\")).show();\n $(this).addClass(\"selected\");\n }\n });\n});\n</code></pre>\n\n<p>CSS</p>\n\n<pre><code>.hidden{display:none;}\n.selected{font-weight:bold;}\n</code></pre>\n\n<p>Job done! I am using classes but you could modify the code to use ids if you prefer. throwing it into the mix as an alternative to the 2 suggestions you already have.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:32:03.487", "Id": "45230", "ParentId": "45036", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T22:22:35.627", "Id": "45036", "Score": "5", "Tags": [ "javascript", "jquery", "beginner" ], "Title": "jQuery Tab function" }
45036
<p>I have developed a service to automatically detect whether an app has started. If the user forbid this app to start (could be chosen from a list of apps), a dialog will be shown.</p> <pre><code>public class AppStartReceiver extends Service { private static final int DELAY_IN_MS = 2000; private List&lt;String&gt; forbiddenApps = new ArrayList&lt;String&gt;(); private BroadcastReceiver screenReceiver = null; private Timer timer; private static boolean screenOn = true; @Override public int onStartCommand(Intent intent, int flags, int startId) { //register screen on/off receiver registerScreenReceiver(); if (forbiddenApps.isEmpty()) { DatabaseHelper db = new DatabaseHelper(this); forbiddenApps = db.getAllApps(); } //start listening for app starts listenForAppStarts(); return START_STICKY; } @Override public void onDestroy() { unregisterReceiver(screenReceiver); timer.cancel(); super.onDestroy(); } /** * start listening for apps to start * only foreground apps are being watched */ private void listenForAppStarts() { final ActivityManager actMgr = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { final String foregroundApp = actMgr.getRunningTasks(1).get(0).topActivity.getPackageName(); if (forbiddenApps.contains(foregroundApp)) { //forbidden app detected =&gt; show dialog Intent dialogIntent = new Intent(getBaseContext(), AlertActivity.class); dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(dialogIntent); } // stop if user turns screen off if(!screenOn) { timer.cancel(); } } }, 0, DELAY_IN_MS); } @Override public IBinder onBind(Intent arg0) { return null; } /** * register screen receiver * gets callback from it */ private void registerScreenReceiver() { // create new receiver screenReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { Log.i("ScreenReceiver", "Screen off"); screenOn = false; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { Log.i("ScreenReceiver", "Screen on"); listenForAppStarts(); screenOn = true; } } }; //register receiver IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(screenReceiver, filter); } } </code></pre> <p>I works perfectly, but I don't know how good it is (does it drain too much battery?). Also, I'd like to know if my programming style is ok.</p>
[]
[ { "body": "<ul>\n<li>Code-Style: Good</li>\n<li>Functionality: no problem seen</li>\n<li>Potential Bugs: only one I can see</li>\n<li>Android-Expert-Level: I am not an android expert.</li>\n<li>Android-Basic-Level: Everything looks sane</li>\n</ul>\n\n<p><strong>Bug</strong> (in jest):</p>\n\n<p>People can play 1.9 seconds of angry birds, swap to a different app, and then swap back ;-)</p>\n\n<p><strong>Suggestions</strong>:</p>\n\n<p>There is only one improvement I can suggest. </p>\n\n<blockquote>\n<pre><code> private BroadcastReceiver screenReceiver = null;\n</code></pre>\n</blockquote>\n\n<p>This line is out-of-place. The only place it is used is in your registerScreenReceiver method. You may as well declare it in that method.</p>\n\n<p>I would be tempted actually to pull the declaration out of the method and make it a final in-initialization anonymous instance:</p>\n\n<pre><code> private final BroadcastReceiver screenReceiver = new BroadcastReceiver(){\n @Override\n public void onReceive(Context context, Intent intent) {\n if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {\n Log.i(\"ScreenReceiver\", \"Screen off\");\n screenOn = false;\n } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {\n Log.i(\"ScreenReceiver\", \"Screen on\");\n listenForAppStarts();\n screenOn = true; \n }\n }\n };\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T10:13:21.787", "Id": "78496", "Score": "0", "body": "Thanks :) I'd like to see you playing 1.9 seconds of angry bird ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:34:42.950", "Id": "45048", "ParentId": "45039", "Score": "3" } } ]
{ "AcceptedAnswerId": "45048", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T22:28:43.460", "Id": "45039", "Score": "7", "Tags": [ "java", "android" ], "Title": "Android close running apps" }
45039
<p>Because we have a mix of both icons for core items and .png icons for custom items, I've developed an easy way to theme them (alter the color) all of them easily that will work across all browsers.</p> <p>Prior to this, I tried CSS and SVG options and they just weren't as simple as this option (but probably less overhead of course). I have to call this after load because of course can't start any canvas work until the items actually hit the DOM and they're parsing through via PHP. There's about 50 of these icons max, more like 25 of them to iterate thought on 90% of users.</p> <p>Any suggestions on how to streamline this or possibly simplify it? <strike>Also I would have posted a test (fiddle or bin) but canvas has a strict cross domain policy.</strike></p> <p>Update: Found an image on the jsfiddle shell I can use for an example that adheres to the cross-domain policy.</p> <p>JSFiddle: <a href="http://jsfiddle.net/d3c0y/6BSsy/" rel="nofollow">http://jsfiddle.net/d3c0y/6BSsy/</a></p> <pre><code>function changeColor(imgObject, imgColor) { // create hidden canvas var canvas = document.createElement("canvas"); canvas.width = 40; canvas.height = 40; var ctx = canvas.getContext("2d"); ctx.drawImage(imgObject, 0, 0, 40, 40); var map = ctx.getImageData(0, 0, 40, 40); var imdata = map.data; // convert image to grayscale first var r, g, b, avg; for (var p = 0, len = imdata.length; p &lt; len; p += 4) { r = imdata[p] g = imdata[p + 1]; b = imdata[p + 2]; avg = Math.floor((r + g + b) / 3); imdata[p] = imdata[p + 1] = imdata[p + 2] = avg; } ctx.putImageData(map, 0, 0); // overlay using source-atop to follow transparency ctx.globalCompositeOperation = "source-atop" ctx.globalAlpha = 0.3; ctx.fillStyle = imgColor; ctx.fillRect(0, 0, 40, 40); // replace image source with canvas data return canvas.toDataURL("image/png", 1); } jQuery(window).load(function () { $('.custom-module').each($.proxy(function () { $(this).attr('src', changeColor(this, '#33CC33')); }), this).promise().done(function () { $('.module-li').removeClass('hidden'); }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:22:49.493", "Id": "78438", "Score": "1", "body": "Can you provide a fiddle? So that we can see it in action?" } ]
[ { "body": "<p>Pretty nice overall. You're missing a semi-colon or two, but otherwise it's a nice solution.</p>\n\n<p>The only real criticism I have are the \"magic numbers\" in there, like the 40x40 size that's hardcoded everywhere. Technically, you could derive the canvas dimension from the image, or pass the width/height as arguments. (Incidentally, setting a canvas's size will also clear its contents, which is helpful if there's one shared canvas that needs to be cleared between uses.) In either case, though, you'd have to get rid of the hardcoded \"40\".</p>\n\n<p>Optimization-wise, the only addition I've made is to simply skip pixels with a zero alpha component; if they're transparent anyway, there's no need to bother with them.</p>\n\n<p>Other than that, I've just broken the code into a couple of functions; nothing special (Note, haven't tested this yet.)</p>\n\n<pre><code>var changeIconColor = (function () {\n var canvas = document.createElement(\"canvas\"), // shared instance\n context = canvas.getContext(\"2d\");\n\n // only place the dimensions are hardcoded\n // everything else just references canvas.width/canvas.height\n canvas.width = 40;\n canvas.height = 40;\n\n function desaturate() {\n var imageData = context.getImageData(0, 0, canvas.width, canvas.height),\n pixels = imageData.data,\n i, l, r, g, b, a, average;\n\n for(i = 0, l = pixels.length ; i &lt; l ; i += 4) {\n a = pixels[i + 3];\n if( a === 0 ) { continue; } // skip if pixel is transparent\n\n r = pixels[i];\n g = pixels[i + 1];\n b = pixels[i + 2];\n\n average = (r + g + b) / 3 &gt;&gt;&gt; 0; // quick floor\n pixels[i] = pixels[i + 1] = pixels[i + 2] = average;\n }\n\n context.putImageData(imageData, 0, 0);\n }\n\n function colorize(color) {\n context.globalCompositeOperation = \"source-atop\";\n context.globalAlpha = 0.3; // you may want to make this an argument\n context.fillStyle = color;\n context.fillRect(0, 0, canvas.width, canvas.height);\n // reset\n context.globalCompositeOperation = \"source-over\";\n context.globalAlpha = 1.0;\n }\n\n return function (iconElement, color) {\n context.clearRect(0, 0, canvas.width, canvas.height);\n context.drawImage(iconElement, 0, 0, canvas.width, canvas.height);\n desaturate();\n colorize(color);\n return canvas.toDataURL(\"image/png\", 1);\n };\n}());\n</code></pre>\n\n<p>As for invoking it, I don't think you need the <code>$.proxy</code> and <code>promise</code> stuff. I would think it'd be enough to just do</p>\n\n<pre><code>$('.custom-module').each(function () {\n this.src = changeIconColor(this, '#33CC33');\n});\n$('.module-li').removeClass('hidden');\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T20:40:27.033", "Id": "78646", "Score": "0", "body": "Added a working example [over here](http://jsfiddle.net/d3c0y/6BSsy/) with your changes. Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T00:19:05.420", "Id": "78668", "Score": "0", "body": "@d3c0y Neat, glad it worked" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T05:17:25.320", "Id": "45062", "ParentId": "45041", "Score": "3" } } ]
{ "AcceptedAnswerId": "45062", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T22:38:38.847", "Id": "45041", "Score": "5", "Tags": [ "javascript", "jquery", "image", "canvas" ], "Title": "Utilizing HTML5 Canvas to apply color theme to .png icons" }
45041
<p>I have created a little console tool that simply does commands that you enter.</p> <p>The commands are stored in a txt file. Right now I only got 2 commands: <code>getTime</code> and <code>getCommands</code>.</p> <p>Pretty simple, but I'm not sure I'm doing anything the most optimal way, which is why I am asking here. I was thinking about creating a whole class to get the time but I wasn't sure that would make any sense (as it seems <code>SYSTEMTIME</code> is already a class).</p> <p>Also, I was thinking about the next command I would add is something where you can input "open 'file' ", where file is the program you want to open. I googled a bit and found a function called <code>filefindnext</code> and <code>filefindfirst</code> (to search for the file), but I'm not sure if this is the best way to do it? (I was also thinking about just adding a .txt file with the dir to the predefined files)</p> <p>I hope you can help clear up my code and in general make my code better. I'm still fairly new to programming, so all constructive feedback is appreciated.</p> <p><strong>main.cpp</strong> (just a little test for my command class)</p> <pre><code>int main() { command list; list.setCommandList(); list.printCommands(); while (1) {list.getCommand(); } } </code></pre> <p><strong>commands.h</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; using namespace std; class command { public: command(); ~command(); void printCommands(); string verifyCommand(string); void getCommand(); void executeCommand(string); void setCommandList(); private: std::string userinput_; std::ifstream file; string *commandlist; int cNr; //command number }; </code></pre> <p><strong>commands.cpp</strong></p> <pre><code>#include "commands.h" #include "Time.h" command::command(){ file.open("commands.txt"); cNr = 0; } command::~command() { file.close(); delete[] commandlist; } void command::printCommands() { string line; cout &lt;&lt;"Command list:\n\n"; for (int i = 0;i&lt;cNr;i++) { cout &lt;&lt;commandlist[i] &lt;&lt;endl; } cout &lt;&lt;endl; } void command::setCommandList() { int nrOfLines = 0; string cline; string line; while (getline(file,cline)) { nrOfLines++; } file.clear(); file.seekg(0, file.beg); commandlist = new string[nrOfLines]; while (getline(file,line)) { commandlist[cNr] = line; cNr++; } } string command::verifyCommand(string command) { string line; for (int i = 0;i&lt;cNr;i++) { if (command==commandlist[i]) return command; } return ""; } void command::getCommand() { string userinput; cout &lt;&lt;"Enter command:"&lt;&lt;endl; cin &gt;&gt; userinput; userinput_ = verifyCommand(userinput); if (userinput_ == "") {cout &lt;&lt;"Error, can´t find that command. Please try again"&lt;&lt;endl; getCommand(); } else executeCommand(userinput_); } void command::executeCommand(string com) { if (com == "getTime") { cout &lt;&lt; string( 100, '\n' ); //clear screen SYSTEMTIME t; GetLocalTime(&amp;t); cout&lt;&lt; "H:"&lt;&lt;t.wHour&lt;&lt;" M:"&lt;&lt;t.wMinute&lt;&lt;" S:"&lt;&lt;t.wSecond&lt;&lt;endl; } if (com == "getCommands") { cout &lt;&lt; string( 100, '\n' ); printCommands(); } } </code></pre>
[]
[ { "body": "<ul>\n<li><p>While it is okay to put <code>using namespace std</code> in a local scope (such as a function), it's especially problematic to put it into a header file. By doing this, anyone including it will be forced to have that namespace code exposed globally, and you shouldn't force that on anyone. Although the <code>std</code> namespace is most commonly used, this applies to any of them.</p></li>\n<li><p>You should be opening the file and doing user input in <code>main()</code>, not within the class. You should be <em>receiving</em> data from a client (such as <code>main()</code>) and constructing an object with this data.</p>\n\n<p>Move all of <code>getCommand()</code>'s functionality into <code>main()</code> and have that in your <code>while(1)</code> loop. Here, you'll get the user's command and supply it to the class until the loop ends.</p>\n\n<p>Another misleading thing here: the name <code>getX()</code> usually denotes a <code>public</code> \"getter\" function, which merely returns a data member to the client. It's best to use this name for a function that only does this, which <code>getCommand()</code> does not. As mentioned, have this functionality in <code>main()</code>, not within the class. You should then no longer need this function.</p></li>\n<li><p>Consider allowing the user to provide their own file name:</p>\n\n<pre><code>std::cout &lt;&lt; \"Filename: \";\nstd::string filename;\nstd::getline(std::cin, filename);\n\nstd::ifstream file;\nfile.open(filename.c_str());\n</code></pre>\n\n<p>You should have all of this in <code>main()</code> and no longer have the class manage the creation, opening, and closing of the file. Let the user decide how they want to manage their file. You'll also be able to terminate from <code>main()</code> right away if the file cannot be opened.</p></li>\n<li><p>I'd recommend against having <code>file.close();</code> in the destructor. <code>close()</code> is generally unneeded as the file can close on its own, and might not work as intended here. The destructor, in general, should primarily deallocate memory when needed.</p></li>\n<li><p>I'm not sure why <code>commandlist</code> needs to be a <code>std::string*</code>. This could be problematic as you're having to manage the pointer and its memory yourself, and there are better alternatives to holding this data. In general, raw pointers should be used sparingly in C++.</p>\n\n<p>In <code>setCommandList()</code>, you're allocating an array of <code>std::string</code>s to that member. Why not have an <code>std::vector</code> of <code>std::string</code>s? This will do all the memory management for you, so it's much safer. You will also have access to its class functions, which could be useful.</p>\n\n<pre><code>std::vector&lt;std::string&gt; commandList;\n</code></pre>\n\n<p>This should be in place of the <code>std::string*</code> member, and then you can size it to <code>nrOfLines</code> via <code>resize()</code> when needed. With this, you'll no longer need to <code>new</code> memory nor <code>delete</code> it in the destructor. You won't even need to define your destructor anymore.</p></li>\n<li><p>Error messages, such as the one outputted in <code>getCommand()</code>, should be put into <code>std::cerr</code> instead of <code>std::cout</code>. The latter should just be used for general output.</p></li>\n<li><p>The abbreviation and comment are pointless:</p>\n\n<pre><code>int cNr; //command number\n</code></pre>\n\n<p>Not only is it a very confusing abbreviation, but you cannot expect readers to see this first and then remember it throughout the code. Just rename it to <code>commandNumber</code> (not very long of a name) and remove the comment.</p></li>\n<li><p>A member function that does not modify any of its data members should be <code>const</code>. This also protects against any accidental modifications and communicates to the reader that this function only performs read-only actions.</p>\n\n<p>In addition, any function that receives an argument of a user-defined type (such as <code>std::string</code>) and is not supposed to modify it should be passed by <code>const&amp;</code>. This also prevents any accidental modifications and avoids a needless copy.</p>\n\n<p>These two points apply to <code>verifyCommand()</code>, which is not making any modifications:</p>\n\n<pre><code>verifyCommand(std::string const&amp; command) const {}\n</code></pre></li>\n<li><p>For <code>printCommands()</code>:</p>\n\n<ol>\n<li><p>It should be <code>const</code> as it does not modify any data members (see the above point):</p>\n\n<pre><code>printCommands() const {}\n</code></pre></li>\n<li><p>Leave out the label output and the extra newline. The client shouldn't have to be forced to use them if they don't want them. Just have them done around the function call. </p></li>\n</ol></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:22:08.303", "Id": "78422", "Score": "0", "body": "Alright, thanks for the edit in my post. Will start to work on these things tomorrow, have to read up on a few stuff like vectors first. thanks for the feedback!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:31:48.817", "Id": "78425", "Score": "0", "body": "@Sumsar1812: You're welcome. I don't think I've addressed everything in this question, but I also haven't fully studied it. Hopefully others will contribute as well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:04:32.837", "Id": "45047", "ParentId": "45043", "Score": "11" } } ]
{ "AcceptedAnswerId": "45047", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T23:28:55.587", "Id": "45043", "Score": "11", "Tags": [ "c++", "beginner", "console", "file" ], "Title": "Console command tool" }
45043
<p>This is a sign up function called on form submission. It firstly inserts key user data into the <code>users</code> table. If successful, secondary data is then inputted into respective tables (such as user job titles and user experience). I'm not really sure whether stacking queries 2-5 is the best way to do it, so I would be interested in knowing how this function could be improved and/or made more secure.</p> <pre><code> public function registerFreelancer($firstname, $lastname, $email, $password, $location, $portfolio, $jobtitle, $priceperhour, $experience, $bio, $userType){ global $bcrypt; global $mail; $time = time(); $ip = $_SERVER['REMOTE_ADDR']; $email_code = sha1($email + microtime()); $password = $bcrypt-&gt;genHash($password);// generating a hash using the $bcrypt object $query = $this-&gt;db-&gt;prepare("INSERT INTO " . DB_NAME . ".users (firstname, lastname, email, email_code, password, time_joined, location, portfolio, bio, ip) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "); $query-&gt;bindValue(1, $firstname); $query-&gt;bindValue(2, $lastname); $query-&gt;bindValue(3, $email); $query-&gt;bindValue(4, $email_code); $query-&gt;bindValue(5, $password); $query-&gt;bindValue(6, $time); $query-&gt;bindValue(7, $location); $query-&gt;bindValue(8, $portfolio); $query-&gt;bindValue(9, $bio); $query-&gt;bindValue(10, $ip); try{ $query-&gt;execute(); // Send email code usually here $rows = $query-&gt;rowCount(); if($rows &gt; 0){ $last_user_id = $this-&gt;db-&gt;lastInsertId('user_id'); $query_2 = $this-&gt;db-&gt;prepare("INSERT INTO " . DB_NAME . ".freelancers (freelancer_id, jobtitle, priceperhour) VALUE (?,?,?)"); $query_2-&gt;bindValue(1, $last_user_id); $query_2-&gt;bindValue(2, $jobtitle); $query_2-&gt;bindValue(3, $priceperhour); $query_2-&gt;execute(); $query_3 = $this-&gt;db-&gt;prepare("INSERT INTO " . DB_NAME . ".user_types (user_type_id, user_type) VALUE (?,?)"); $query_3-&gt;bindValue(1, $last_user_id); $query_3-&gt;bindValue(2, $userType); $query_3-&gt;execute(); $query_4 = $this-&gt;db-&gt;prepare("INSERT INTO " . DB_NAME . ".user_experience (experience_id, experience) VALUE (?,?)"); $query_4-&gt;bindValue(1, $last_user_id); $query_4-&gt;bindValue(2, $experience); $query_4-&gt;execute(); if($userType == 'designer') { $query_5 = $this-&gt;db-&gt;prepare("INSERT INTO " . DB_NAME . ".designer_titles (job_title_id, job_title) VALUE (?,?)"); $query_5-&gt;bindValue(1, $last_user_id); $query_5-&gt;bindValue(2, $jobtitle); $query_5-&gt;execute(); } else if ($userType == 'developer') { $query_5 = $this-&gt;db-&gt;prepare("INSERT INTO " . DB_NAME . ".developer_titles (job_title_id, job_title) VALUE (?,?)"); $query_5-&gt;bindValue(1, $last_user_id); $query_5-&gt;bindValue(2, $jobtitle); $query_5-&gt;execute(); } return true; } }catch(PDOException $e){ die($e-&gt;getMessage()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T00:16:56.273", "Id": "78421", "Score": "2", "body": "Just so it's said, your code is pretty intimate with the structure of the DB. Which will end up being annoying later on, particularly if this is running outside of the model/DAL. I'd much rather say `$user = (get a fresh User object); $user->someAttribute = $someValue; ... ; $user->insert();`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T21:32:36.877", "Id": "78545", "Score": "0", "body": "Could you perhaps elaborate on what you mean - I'm fairly new to OOPHP, so it would be good to know what you are talking about in more detail" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-03T19:11:59.957", "Id": "85816", "Score": "0", "body": "I mean that if this code is actually in the signup page, and other code that messes with these records is also in its respective page, then you have a bunch more places to worry about changing if you change anything about users. You'd be better off to take these functions out of their respective pages and group them together in one place (even if they're all just functions in the same file...although a popular option is to put them in a User class). The end result would be one reusable, ideally cohesive library of functions to manipulate users. (Sorry, just saw this.)" } ]
[ { "body": "<ol>\n<li><p>If the second or later query fails you'll have inconsistent data in your database. Consider using atomic <a href=\"http://www.php.net/manual/en/pdo.begintransaction.php\" rel=\"nofollow noreferrer\">transactions</a>.</p></li>\n<li><p><code>$query_2</code>, <code>$query_3</code> are bad names. You could pick something more descriptive, like <code>$usersInsert</code>, <code>$freelancersInsert</code> etc.</p></li>\n<li><blockquote>\n<pre><code>$query = $this-&gt;db-&gt;prepare(\"INSERT INTO \" . DB_NAME . \".users\n (firstname, lastname, email, email_code, password, time_joined, location, portfolio, bio, ip) \n VALUES \n (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n\");\n\n$query-&gt;bindValue(1, $firstname);\n$query-&gt;bindValue(2, $lastname);\n...\n</code></pre>\n</blockquote>\n\n<p>I'd use named binds here. <a href=\"https://stackoverflow.com/q/12344741/843804\">As far as I see they works with INSERT statements too</a>. </p>\n\n<pre><code>$query = $this-&gt;db-&gt;prepare(\"INSERT INTO \" . DB_NAME . \".users\n (firstname, lastname, email, email_code, password, time_joined, location, portfolio, bio, ip) \n VALUES \n (:firstname, :lastname, ...)\n\");\n\n$query-&gt;bindValue(\":firstname\", $firstname);\n$query-&gt;bindValue(\":lastname\", $lastname);\n...\n</code></pre>\n\n<p>It would be less error-prone (harder to mix parameters up) and would be easier to read/follow.</p></li>\n<li><p>Consider <em>Hayley Watson</em>'s comment on the <a href=\"http://hu1.php.net/die\" rel=\"nofollow noreferrer\"><code>die</code> manual page</a>:</p>\n\n<blockquote>\n <p>It is poor design to rely on die() for error handling in a web site because it results in an ugly experience for site users: a broken page and - if they're lucky - an error message that is no help to them at all. As far as they are concerned, when the page breaks, the whole site might as well be broken.</p>\n \n <p>If you ever want the public to use your site, always design it to handle errors in a way that will allow them to continue using it if possible. If it's not possible and the site really is broken, make sure that you find out so that you can fix it. die() by itself won't do either.</p>\n</blockquote>\n\n<p>Furthermore, at least log the error to a log file, otherwise you might be never know if your future users can't even register.</p></li>\n<li><blockquote>\n<pre><code>if($userType == 'designer') {\n $query_5 = $this-&gt;db-&gt;prepare(\"INSERT INTO \" . DB_NAME . \".designer_titles (job_title_id, job_title) VALUE (?,?)\");\n\n $query_5-&gt;bindValue(1, $last_user_id);\n $query_5-&gt;bindValue(2, $jobtitle); \n\n $query_5-&gt;execute();\n\n} else if ($userType == 'developer') {\n $query_5 = $this-&gt;db-&gt;prepare(\"INSERT INTO \" . DB_NAME . \".developer_titles (job_title_id, job_title) VALUE (?,?)\");\n\n $query_5-&gt;bindValue(1, $last_user_id);\n $query_5-&gt;bindValue(2, $jobtitle); \n\n $query_5-&gt;execute();\n}\n</code></pre>\n</blockquote>\n\n<p>Both cases are almost the same. You could create a function for that with a <code>$tableName</code> parameter to remove the duplication.</p>\n\n<p>It can be a sign that you could have another database structure with only one table instead of two:</p>\n\n<pre><code>TABLE titles:\n - role (possible values: developer, designer)\n - job_title_id\n - job_title\n</code></pre></li>\n<li><blockquote>\n<pre><code>if($userType == 'designer') {\n ...\n} else if ($userType == 'developer') {\n ...\n}\n</code></pre>\n</blockquote>\n\n<p>You could be more defensive here, if <code>$userType</code> contains something else (not <code>designer</code> nor <code>developer</code>) and if it's should be considered as a programming (or input validation) error sing it somehow. I'd throw an exception and log it in a catch block. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p></li>\n<li><p>You could save a few indentation level with guard clauses which would be readable. You wouldn't have to read through the whole function to figure out what happens when <code>$rows &gt; 0</code> is false:</p>\n\n<pre><code>$rows = $query-&gt;rowCount();\n\nif($rows &gt; 0){\n return;\n}\n$last_user_id = $this-&gt;db-&gt;lastInsertId('user_id');\n...\n</code></pre>\n\n<p>It might be more unambiguous using <code>return false</code> instead of implicit return here.</p></li>\n<li><p>The comment doesn't say too much, the code is already obvious here:</p>\n\n<blockquote>\n<pre><code>$password = $bcrypt-&gt;genHash($password);// generating a hash using the $bcrypt object\n</code></pre>\n</blockquote>\n\n<p>I'd remove it. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>A lot of parameters is a <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">code smell</a>: <em>Long Parameter List</em>. Their type are the same, it's easy to mix them up. Consider using a <a href=\"http://sourcemaking.com/refactoring/introduce-parameter-object\" rel=\"nofollow noreferrer\">parameter object</a> instead which would contain named fields.</p>\n\n<blockquote>\n<pre><code>public function registerFreelancer($firstname, $lastname, $email, $password, $location, $portfolio, $jobtitle, $priceperhour, $experience, $bio, $userType){\n</code></pre>\n</blockquote>\n\n<p>See: <em>Martin Fowler</em>'s <em>Refactoring: Improving the Design of Existing Code</em> book, <em>Chapter 3. Bad Smells in Code, Long Parameter List</em></p></li>\n<li><p>I've found this kind of formatting is rather hard to maintain:</p>\n\n<blockquote>\n<pre><code>$time = time();\n$ip = $_SERVER['REMOTE_ADDR'];\n$email_code = sha1($email + microtime());\n$password = $bcrypt-&gt;genHash($password);// generating a hash using the $bcrypt object\n</code></pre>\n</blockquote>\n\n<p>If you have a new variable with a longer name you have to modify seven other lines too to keep it nice. It also looks badly on revison control diffs and could cause unnecessary merge conflicts.</p>\n\n<p>From <em>Code Complete, 2nd Edition</em> by <em>Steve McConnell</em>, p758:</p>\n\n<blockquote>\n <p><strong>Do not align right sides of assignment statements</strong></p>\n \n <p>[...]</p>\n \n <p>With the benefit of 10 years’ hindsight, I have found that, \n while this indentation style might look attractive, it becomes\n a headache to maintain the alignment of the equals signs as variable \n names change and code is run through tools that substitute tabs\n for spaces and spaces for tabs. It is also hard to maintain as\n lines are moved among different parts of the program that have \n different levels of indentation.</p>\n</blockquote></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T10:19:33.830", "Id": "78497", "Score": "0", "body": "Wow, this is seriously informative and exactly what I was looking for! Thanks. As an alternative to die(), would you recommend using something like: `echo 'Caught exception: ', $e->getMessage(), \"\\n\";`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T10:35:56.220", "Id": "78500", "Score": "0", "body": "@jshjohnson: I'm happy that you've found it useful. I don't think that the exception message (which I guess contains some database-related message) would be useful for a user but anyway, test it and decide. (And don't forget to log it.) I've just written [another answer here](http://codereview.stackexchange.com/a/45075/7076) about the same topic, check #3." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-07T10:31:40.677", "Id": "81290", "Score": "0", "body": "Just re-reading through this. Could you perhaps elaborate what you mean regarding a parameter object? If I declared a new Freelancers object, how would the function get the data passed to it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-07T20:41:39.040", "Id": "81412", "Score": "0", "body": "@jshjohnson: Huh, good question. Object relational mapping has its issues: http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch. Anyway, I've put another link into the post and here are two ideas: create a [builder](https://en.wikipedia.org/wiki/Builder_pattern); move the `register` method into the `Freelancer` class. In the latter case you might also get a better a API with a builder but it might not worth it. I guess it depend on the size of the project." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-10T18:02:56.283", "Id": "114040", "Score": "0", "body": "As for point 4: Aside from stopping the flow of information (and in particular, error messages) to code that could do something useful with it, `die()` makes it more of a pain -- if not outright impossible -- to run automated tests (like, say, unit tests). I've run into this before; if you're not anticipating such ugliness, an error can cause the whole test suite to just stop dead in its tracks, possibly without even so much as a visible error message or nonzero exit code." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T05:08:21.257", "Id": "45061", "ParentId": "45046", "Score": "7" } } ]
{ "AcceptedAnswerId": "45061", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T23:51:21.837", "Id": "45046", "Score": "10", "Tags": [ "php", "optimization", "php5", "pdo" ], "Title": "PDO sign up function inserting data into multiple tables" }
45046
<p>I have a manager class that will manage an unknown number of objects. I'm currently storing the objects in a <code>NSMutableArray</code> object, and when I need to find one, I iterate through the array comparing pointers.</p> <p>For example, I have an array called <code>managedObjects</code>. I get a delegate method call:</p> <pre><code>- (void)someDelegateMethod:sender withResults:results { for (NSDictionary *managedObjectDict in managedObjects) { if (sender == [managedObjectDict objectForKey:@"DelegatedObject"]) { NSLog(@"%@",[managedObjectDict objectForKey:@"Value"]); break; } } } </code></pre> <p>Now, Objective-C <code>forin</code> loops are handled in batches and are extremely fast... but if I were managing thousands of objects, this could potentially take a bit of time to find the right one.</p> <p>How can I improve this efficiency?</p>
[]
[ { "body": "<p>I'm not an Objective-C guy but, I do know that if you used some sort of hash table structure and could define a hashcode for these objects, that you'd be able to pull them out much faster. </p>\n\n<p>You said at times you \"need to find one\", I would assume you would know enough about it to be able to generate its hashcode and check your table for it in O(1) time. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:47:07.293", "Id": "45055", "ParentId": "45054", "Score": "4" } }, { "body": "<p>A linear scan for a unique value immediately screams to me that <code>managedObjects</code> should be an <code>NSDictionary</code> with <code>NSValue</code> wrappers around <code>Sender*</code>s as the keys.</p>\n\n<p>In other words, when inserting into <code>managedObjects</code> you would do something like <code>[managedObjects setObject:@{@\"Value\": @\"example} forKey:[NSValue valueWithPointer]]</code>.</p>\n\n<p>Then, in your delegate method, you could retrieve it with:</p>\n\n<pre><code>- (void)someDelegateMethod:sender withResults:results {\n NSString* value = [self.managedObjects objectForKey:[NSValue valueForPointer:sender]][@\"Value\"]];\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:47:15.573", "Id": "45056", "ParentId": "45054", "Score": "4" } } ]
{ "AcceptedAnswerId": "45056", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T02:39:46.083", "Id": "45054", "Score": "6", "Tags": [ "optimization", "performance", "object-oriented", "objective-c", "pointers" ], "Title": "How best to keep track of an unknown number of objects?" }
45054
<p>I am writing a D3D9 hook plugin to give back to a community that helped me learn programming. It is a community based on programming and scripting for games.</p> <p>The plugin is supposed to hook d3d9.dll and allow clients to read pixels from the backbuffer. That is the entire extent of the plugin.</p> <p>Thus I have hooked only the <code>EndScene</code> function.</p> <p>I have also looked into the following functions to find their release methods:</p> <ul> <li><code>IDirect3DDevice9::CreateOffscreenPlainSurface</code> <strong>-></strong> <code>IDirect3DSurface9::Release</code></li> <li><code>IDirect3DDevice9::GetRenderTarget</code> <strong>-></strong> <code>IDirect3DSurface9::Release</code></li> <li><code>IDirect3DDevice9::GetRenderTargetData</code> <strong>-></strong> No Release Method</li> <li><code>IDirect3DSurface9::GetDesc</code> <strong>-></strong> No destroy method</li> <li><code>IDirect3DSurface9::GetDC</code> <strong>-></strong> <code>IDirect3DSurface9::ReleaseDC</code></li> </ul> <p>So that ends my research of finding where a "possible" leak might be.</p> <p>Now I have the following code that creates a texture for drawing, draws the texture and immediately frees it. I also have the following for reading the back-buffer into an array provided to my plugin via JNI. This array is guaranteed to be safe and released since it is created in a Java client.</p> <p>All of my Direct-X code is as follows:</p> <p><strong>Definitions &amp; Structures:</strong></p> <pre><code>#define VERTEX_FVF (D3DFVF_XYZRHW | D3DFVF_DIFFUSE) #define VERTEX_FVF_TEX (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1) struct D3DVertex { float X, Y, Z, RHW; unsigned int Colour; float U, V; }; /** Calls the Release function of specified classes: Textures, Devices, etc.. **/ template&lt;typename T&gt; void SafeRelease(T* &amp;ptr) { if (ptr) { ptr-&gt;Release(); ptr = nullptr; } } </code></pre> <p><strong>LoadTexture:</strong></p> <pre><code>/** Creates a texture from a given buffer. Texture must be freed using SafeRelease. **/ void LoadTexture(IDirect3DDevice9* Device, std::uint8_t* buffer, int width, int height, IDirect3DTexture9* &amp;Texture) { Device-&gt;CreateTexture(width, height, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &amp;Texture, 0); D3DLOCKED_RECT rect; Texture-&gt;LockRect(0, &amp;rect, nullptr, D3DLOCK_DISCARD); TexturePixels = static_cast&lt;std::uint8_t*&gt;(rect.pBits); Texture-&gt;UnlockRect(0); memcpy(TexturePixels, &amp;buffer[0], width * height * 4); } </code></pre> <p><strong>DrawTexture:</strong></p> <pre><code>/** Draws a texture on screen using DrawPrimitiveUP. No allocations done. **/ void DrawTexture(IDirect3DDevice9* Device, IDirect3DTexture9* Texture, float X1, float Y1, float X2, float Y2) { float UOffset = 0.5f / (float)(X2 - X1); float VOffset = 0.5f / (float)(Y2 - Y1); D3DVertex Vertices[] = { {X1, Y1, 1.0f, 1.0f, D3DCOLOR_RGBA(0xFF, 0xFF, 0xFF, 0xFF), 0.0f + UOffset, 0.0f + VOffset}, {X2, Y1, 1.0f, 1.0f, D3DCOLOR_RGBA(0xFF, 0xFF, 0xFF, 0xFF), 1.0f + UOffset, 0.0f + VOffset}, {X1, Y2, 1.0f, 1.0f, D3DCOLOR_RGBA(0xFF, 0xFF, 0xFF, 0xFF), 0.0f + UOffset, 1.0f + VOffset}, {X2, Y2, 1.0f, 1.0f, D3DCOLOR_RGBA(0xFF, 0xFF, 0xFF, 0xFF), 1.0f + UOffset, 1.0f + VOffset} }; Device-&gt;SetFVF(VERTEX_FVF_TEX); Device-&gt;SetTexture(0, Texture); Device-&gt;DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, Vertices, sizeof(D3DVertex)); Device-&gt;SetTexture(0, nullptr); } </code></pre> <p><strong>DrawCircle:</strong></p> <pre><code>/** Draws a circle on screen using DrawPrimitiveUP. No allocations done. **/ void DrawCircle(IDirect3DDevice9* Device, float CX, float CY, float Radius, D3DCOLOR Colour) { static const int Resolution = 10; D3DVertex Vertices[Resolution]; for (int I = 0; I &lt; Resolution; ++I) { Vertices[I].X = CX + Radius * std::cos(3.141592654f * (I / (Resolution / 2.0f))); Vertices[I].Y = CY + Radius * std::sin(3.141592654f * (I / (Resolution / 2.0f))); Vertices[I].Z = 0.0f; Vertices[I].RHW = 1.0f; Vertices[I].Colour = Colour; Vertices[I].U = 0.0f; Vertices[I].V = 0.0f; } Device-&gt;SetFVF(VERTEX_FVF_TEX); Device-&gt;DrawPrimitiveUP(D3DPT_TRIANGLEFAN, Resolution - 2, Vertices, sizeof(D3DVertex)); } </code></pre> <p><strong>DrawJavaBuffer:</strong></p> <pre><code>/** Takes a given pixel buffer (SmartGlobal-&gt;dbg) and creates a texture from its pixels and draws it on screen releases the texture immediately as specified by the LoadTexture function. **/ void BltSmartBuffer(IDirect3DDevice9* Device) { if (SmartGlobal != nullptr) { std::uint8_t* Ptr = reinterpret_cast&lt;std::uint8_t*&gt;(SmartGlobal-&gt;dbg); LoadTexture(Device, Ptr, SmartGlobal-&gt;width, SmartGlobal-&gt;height, Texture); //CreateTexture DrawTexture(Device, Texture, 0, 0, SmartGlobal-&gt;width, SmartGlobal-&gt;height); SafeRelease(Texture); //Release Texture } } </code></pre> <p><strong>ReadBackBuffer:</strong></p> <pre><code>/** Reads pixels from the back-buffer into a buffer of size (Width * Height * 4) **/ HRESULT dxReadPixels(IDirect3DDevice9* Device, void* Buffer, HDC&amp; DC, int&amp; Width, int&amp; Height, D3DFORMAT Format) { IDirect3DSurface9* RenderTarget = nullptr; IDirect3DSurface9* DestTarget = nullptr; HRESULT result = Device-&gt;GetRenderTarget(0, &amp;RenderTarget); //Call SafeRelease when finished. if (result == S_OK) { if (Width == 0 || Height == 0 || Format == D3DFMT_UNKNOWN) { D3DSURFACE_DESC descriptor = {}; RenderTarget-&gt;GetDesc(&amp;descriptor); //No release method. Width = descriptor.Width; Height = descriptor.Height; Format = descriptor.Format; } //RenderTarget-&gt;GetDC(&amp;DC); //Call RenderTarget-&gt;ReleaseDC. result = Device-&gt;CreateOffscreenPlainSurface(Width, Height, Format, D3DPOOL_SYSTEMMEM, &amp;DestTarget, nullptr); //No release method :l result = Device-&gt;GetRenderTargetData(RenderTarget, DestTarget); //Call SafeRelease when finished. D3DLOCKED_RECT rect; DestTarget-&gt;LockRect(&amp;rect, 0, D3DLOCK_READONLY); //Locked.. memcpy(Buffer, rect.pBits, Width * Height * 4); DestTarget-&gt;UnlockRect(); //Unlocked.. } SafeRelease(RenderTarget); //Released as promised above SafeRelease(DestTarget); //Released as promised above return result; } </code></pre> <p><strong>EndScene Hook:</strong></p> <pre><code>/** Draws specified texture and reads back-buffer. **/ HRESULT Direct3DDevice9Proxy::EndScene() { HDC hdc = nullptr; if (SmartGlobal &amp;&amp; SmartGlobal-&gt;version) { dxReadPixels(ptr_Direct3DDevice9, SmartGlobal-&gt;img, hdc, SmartGlobal-&gt;width, SmartGlobal-&gt;height); //Read backbuffer into Java buffer using the function above. IDirect3DStateBlock9* block; ptr_Direct3DDevice9-&gt;CreateStateBlock(D3DSBT_ALL, &amp;block); //Release when finished. block-&gt;Capture(); //Reset when finished. if (SmartDebugEnabled) { BltSmartBuffer(ptr_Direct3DDevice9); //Draw the texture using the function above. } int X = -1, Y = -1; SmartGlobal-&gt;getMousePos(X, Y); if (X &gt; -1 &amp;&amp; Y &gt; -1) { ptr_Direct3DDevice9-&gt;SetTexture(0, nullptr); ptr_Direct3DDevice9-&gt;SetPixelShader(nullptr); ptr_Direct3DDevice9-&gt;SetVertexShader(nullptr); DrawCircle(ptr_Direct3DDevice9, X, Y, 2.5f); //Draw a circle using DrawPrimitiveUP using the function above. } block-&gt;Apply(); //Reset as promised. block-&gt;Release(); //Released as promised. } return ptr_Direct3DDevice9-&gt;EndScene(); } </code></pre> <p>I know it seems long but I really need your help tracking down any leaks if they exist. I've tried to speed up the review by adding comments I believe is crucial and I hope they do not distract anyone reviewing the code. I'm having a hard time convincing anyone that there are no leaks. I really hope there aren't any leaks in this code.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T04:13:36.403", "Id": "78464", "Score": "0", "body": "From a code review standpoint, I find it interesting that you feel a need to add these comments. +1 congrats, you pass the 1st post review ;) - note that answerers may review **any** aspect of the code, not just potential leaking issues." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T04:15:39.493", "Id": "78465", "Score": "0", "body": "I wouldn't mind a total review at all. I was mainly just looking for leaks but any review is good as well. It is a bonus for me too. I know, I felt awkward putting the comments as it is a \"review\" site but I thought it'd help explain what I was thinking and doing better. Hopefully it doesn't ruin it or take away/distract reviewers or anything." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T04:19:59.167", "Id": "78466", "Score": "0", "body": "You did well mentioning that you added the comments for the post, I don't think they're hurting anything ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T06:55:01.167", "Id": "78480", "Score": "0", "body": "Wouldn't running a program like Valgrind solve memory leak problems?" } ]
[ { "body": "<p><strong>Coding style</strong>:</p>\n\n<p>This is a list of improvements you can apply to make your code nicer\nin a C++ context:</p>\n\n<ul>\n<li><p>Prefer <code>enum</code>s or numerical constants over macros. <code>VERTEX_FVF</code> and <code>VERTEX_FVF_TEX</code>\nshould either be members of an <code>enum</code> or <code>const unsigned int</code> objects.</p></li>\n<li><p>You did well by using <code>std::uint8_t</code> but you forgot to do the same for\n<code>memcpy</code> in the <code>LoadTexture()</code> function. <code>memcpy</code> for C++ is defined\nin the header <code>&lt;cstring&gt;</code>. So it should be referred to as <a href=\"http://www.cplusplus.com/reference/cstring/memcpy/\"><code>std::memcpy</code></a>.</p></li>\n<li><p>Avoid C-style casts. In most places you've correctly used the C++\ncast operators. There are still a few C casts that should be removed\nfor full consistency. In <code>DrawTexture()</code> there is such an instance.</p></li>\n<li><p>Use more <code>const</code>. Const can also be applied to local variables that\nare meant to be assigned once. This is a conceptual kind of const,\nunlike the one in an explicit numerical constant, which is a compile time\nconstant. In <code>DrawTexture()</code> for example, <code>UOffset</code>, <code>VOffset</code> and <code>Vertices</code>\nare init-once, never change variables. It is a good practice to mark those\nas <code>const</code>.</p></li>\n<li><p>Read-only pointers are <code>const</code>. In <code>LoadTexture()</code>, <code>buffer</code> is a pointer\nto read-only memory in that context. It should then be a <code>const std::uint8_t* buffer</code>.</p></li>\n<li><p>Use more <a href=\"http://www.cplusplus.com/reference/cassert/assert/\">assertions</a>. Most of your functions take pointers that are not\nbeing validated before use. A good rule of thumb when dealing with pointer\nparameters is to at least validate them with an <code>assert(p != nullptr)</code>\nbefore using them. You should apply that to your function parameters of pointer type.</p></li>\n<li><p>In the <code>DrawCircle()</code> function, your value of <code>π</code> is used twice, so it\nshould be made a constant. You can define a local <code>static const float PI</code> in function\nscope for that. Alternatively, you could use the non-standard <code>M_PI</code> constant\nthat is likely to be available on most compilers under the <code>&lt;cmath&gt;</code> header.</p></li>\n<li><p>Most functions presented here are doing no error checking. Almost\nall D3D calls will return you some error code. You are ignoring them most\nof the time. A function like <code>LoadTexture()</code>, for instance, can easily fail\nif the system is low on memory. If you don't care about returning an error\ncode to a higher level of the application, for whatever reasons, you should\nat least check the error code inside the functions and log a message if\nsomething failed. That will give you a hint of where to start looking for\nthe problem at a latter time. You can use <a href=\"http://www.cplusplus.com/reference/iostream/cerr/?kw=cerr\"><code>std::cerr</code></a> for that.</p></li>\n<li><p>The last advice in this list that must be present for a C++ review is\nabout the procedural style of your program. Ideally, you should try to\nmodel some aspects of your C++ program using <em>Object Oriented Programming</em> (OOP).\nYou seem to have a few globals in there, plus all the functions are declared\nin the global scope. The global vars, in special, can be a source of bugs\nand headache. If you could put some effort into making some parts of this code\nmore object-oriented, you could quite possibly get rid of the globals\nand see some increase in the overall code quality and readability.</p></li>\n</ul>\n\n<p><strong>About the memory leaks</strong>:</p>\n\n<p>At a glance, there doesn't seem to be any memory leaks in your code. D3D objects\ndon't throw exceptions, so you should be fine for that. If exceptions\nare introduced at a later time though, that might also introduce memory leaks.</p>\n\n<p>So how would you go about that? With <a href=\"http://en.wikipedia.org/wiki/Smart_pointer\">smart pointers</a>, of course!\nUnfortunately, the smart pointers provided by the standard library are not customizable for used with <a href=\"http://en.wikipedia.org/wiki/Component_Object_Model\">COM</a> objects.</p>\n\n<p>I've never had such a need, but I imagine someone else must have had, since Microsoft makes heavy use of COM, so it is very likely that smart pointer libraries that support COM\nobjects do exist. You should try searching to find out.</p>\n\n<p>In its simples form, however, a basic COM smart pointer could be implemented\nas the following:</p>\n\n<pre><code>template&lt;class T&gt;\nclass COMRefPtr {\n\npublic:\n\n RefPtr(T * object = nullptr)\n : ptr(object) { }\n\n RefPtr(const RefPtr &amp; rhs)\n : ptr(rhs.ptr)\n {\n if (ptr != nullptr)\n {\n ptr-&gt;AddRef();\n }\n }\n\n RefPtr &amp; operator = (T * object)\n {\n if (ptr != object)\n {\n T * tmp = ptr;\n ptr = object;\n if (tmp)\n {\n tmp-&gt;Release();\n }\n }\n return (*this);\n }\n\n RefPtr &amp; operator = (const RefPtr &amp; rhs)\n {\n if (ptr != rhs.ptr)\n {\n T * tmp = ptr;\n ptr = rhs.ptr;\n if (ptr)\n {\n ptr-&gt;AddRef();\n }\n if (tmp)\n {\n tmp-&gt;Release();\n }\n }\n return (*this);\n }\n\n T &amp; operator *()\n {\n assert(ptr != nullptr &amp;&amp; \"Null pointer dereference!\");\n return *ptr;\n }\n\n const T &amp; operator *() const\n {\n assert(ptr != nullptr &amp;&amp; \"Null pointer dereference!\");\n return *ptr;\n }\n\n T * operator-&gt;()\n {\n assert(ptr != nullptr &amp;&amp; \"Null pointer access!\");\n return ptr;\n }\n\n const T * operator-&gt;() const\n {\n assert(ptr != nullptr &amp;&amp; \"Null pointer access!\");\n return ptr;\n }\n\n bool operator!() const\n {\n // Allows a check such as \"if (!ptr) ...\"\n return ptr == nullptr;\n }\n\n // Access the raw pointer without changing the ref count.\n // Use these to interface with functions that take a raw pointer.\n T * get() { return ptr; }\n const T * get() const { return ptr; }\n\n // You will probably also want to provide comparison operators.\n // At least `==` and `!=`.\n\n ~RefPtr()\n {\n // Automatic cleanup.\n if (ptr != nullptr)\n {\n ptr-&gt;Release();\n }\n }\n\nprivate:\n\n T * ptr;\n};\n</code></pre>\n\n<p>That was modified from an older smart pointer implementation I wrote in the past.\nIt should be usable as-is. For more advanced uses however, there are some things that would have to be further added/adjusted. If you are into learning more about writing smart pointers and templates in general, <em>Modern C++ Design</em> by Andrei Alexandrescu is a great book.</p>\n\n<p>Sorry for the late answer.\nHope the project is still alive and the suggestions made can still be of use.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-21T16:08:43.637", "Id": "67456", "ParentId": "45058", "Score": "6" } } ]
{ "AcceptedAnswerId": "67456", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T03:37:00.117", "Id": "45058", "Score": "8", "Tags": [ "c++", "c++11", "memory-management", "graphics" ], "Title": "D3D9 leaks if any?" }
45058
<p>This is a chunk of code I wrote for a job interview at some point - it is a remote key-value storage REST API supporting CRUD operations.</p> <p>Maybe anyone has some feedback on this? It would be very helpful for me.</p> <p>I did not attach the tests, since it might be a little bit too much code. You don't have to review both files - even commenting on just one can be extremely helpful.</p> <h1>remotekvs.py</h1> <pre><code># -*- test-case-name: tests.remotekvs_test.RemoteKVSTest -*- import json import inspect from twisted.internet import reactor from twisted.web.resource import Resource from twisted.web.server import Site from keyvaluestorage import KeyValueStorage class RemoteKVSResource(Resource): """ This is a Twisted Resource object used to serve requests for KeyValueStorage operations. It supports POST, GET, PUT and DELETE request methods and replies in JSON. """ isLeaf = True def __init__(self): self.kvs = KeyValueStorage() def render(self, request): operations = { 'POST': 'create', 'GET': 'read', 'PUT': 'update', 'DELETE': 'delete'} if request.method in operations.keys(): response = { 'success': True} try: operation = getattr(self.kvs, operations[request.method]) args = {k: v[0] if isinstance(v, list) else v for k, v in request.args.items()} result = operation(**(args)) if result is not None: response['result'] = result except (TypeError, KeyValueStorage.KeyAlreadyExistsError, KeyValueStorage.InvalidKeyError), exception: response['success'] = False response['error'] = exception.__class__.__name__ if isinstance(exception, TypeError): response['error_message'] = ( "Valid request parameters: %s." % ( ', '.join(inspect.getargspec(operation)[0][1:]))) else: response['error_message'] = str(exception) else: response = { 'success': False, 'error': 'InvalidRequestMethod', 'error_message': ( "Valid request methods: POST, GET, PUT, DELETE.")} return json.dumps(response) if __name__ == '__main__': # pragma: no cover site = Site(RemoteKVSResource()) reactor.listenTCP(2048, site) reactor.run() </code></pre> <h1>keyvaluestorage.py</h1> <pre><code># -*- test-case-name: tests.keyvaluestorage_test.KeyValueStorageTest -*- class KeyValueStorage(object): """The most basic key-value storage, supports all 4 CRUD operations.""" class KeyAlreadyExistsError(Exception): """Key you are trying to create already exists in the database.""" class InvalidKeyError(Exception): """Key you are trying to access does not exist in the database.""" def __init__(self): self.storage = {} def create(self, key, value): if key in self.storage.keys(): raise self.KeyAlreadyExistsError( ("Key already exists. KeyValueStorage does not allow " "duplicate keys.")) self.storage[key] = value def read(self, key): try: return self.storage[key] except KeyError: raise self.InvalidKeyError( "Key does not exist. You can not read by a nonexistent key.") def update(self, key, value): if key not in self.storage.keys(): raise self.InvalidKeyError( "Key does not exist. You can not update by a nonexistent key.") self.storage[key] = value def delete(self, key): try: del self.storage[key] except KeyError: raise self.InvalidKeyError( "Key does not exist. You can not delete by a nonexistent key.") </code></pre>
[]
[ { "body": "<p>I'd write the error handling this way:</p>\n\n<pre><code>def render(self, request):\n operations = {\n 'POST': 'create',\n 'GET': 'read',\n 'PUT': 'update',\n 'DELETE': 'delete',\n }\n if request.method not in operations:\n response = {\n 'success': False,\n 'error': 'InvalidRequestMethod',\n 'error_message': (\"Valid request methods: %s\" % (', '.join(operations.keys()))),\n }\n request.setResponseCode(http.NOT_ALLOWED)\n else:\n response = {'success': True}\n ...\n return json.dumps(response)\n</code></pre>\n\n<p>Note the changes:</p>\n\n<ul>\n<li>Since the error handler is simpler than the main processing code, put it first to get it out of the way.</li>\n<li><code>if request.method not in operations</code> reads better than <code>if request.method not in operations.keys()</code> and might be slightly more efficient.</li>\n<li>Reuse <code>operations.keys()</code> for the error message.</li>\n<li>Set <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6\" rel=\"nofollow\">HTTP status 405 (\"Method Not Allowed\")</a>. (The constant is in <code>twisted.web.http</code>.)</li>\n</ul>\n\n<p>In <code>KeyValueStorage</code>, I suggest raising the standard <code>KeyError</code> instead of making your own exception classes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T05:17:43.263", "Id": "78577", "Score": "0", "body": "Thank you, I agree with all of the above. The fact that `k in dict.keys()` is O(n), while `k in dict` is O(1) have never crossed my mind." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T00:23:11.497", "Id": "45114", "ParentId": "45060", "Score": "2" } } ]
{ "AcceptedAnswerId": "45114", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T04:29:35.893", "Id": "45060", "Score": "3", "Tags": [ "python", "api", "twisted" ], "Title": "Simple REST API server" }
45060
<p>I am making a website that takes a bunch of dining hall information and puts it all together in a neater (and hopefully more mobile friendly) form. </p> <p>Here is the link: <a href="https://googledrive.com/host/0By7Z_HHj2VhnWmlhbWl4aF8xdFU/nuEats.html" rel="nofollow">https://googledrive.com/host/0By7Z_HHj2VhnWmlhbWl4aF8xdFU/nuEats.html</a></p> <p>It's a little incomplete at the moment, but what it does is the bar up top shows you how much a "meal" is worth at a university convenience store (there is an arrow that is usually there, but it is current gone because it is 2:21 AM, which is after closing time).</p> <p>Also, there are links to dining halls and their menus. My first question is: I don't know a lot about HTML and CSS best practices. </p> <p>I have tried to keep everything nice and neat, but I was wondering if someone could just browse through my code and see </p> <ul> <li>Is the code efficient </li> <li>Is the code clear and concise?</li> </ul> <p>The second point is especially important to me because I don't want anything to be ambiguous or hard to understand in my code, since I inevitably will have to pass it down.</p> <p><strong>HTML</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;title&gt;nuEats&lt;/title&gt; &lt;!-- Bootstrap core CSS --&gt; &lt;link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"/&gt; &lt;!-- User-fed CSS --&gt; &lt;link rel="stylesheet" href="nuEats.css" type="text/css"&gt; &lt;!-- Bootstrap responsive CSS --&gt; &lt;link rel="stylesheet" href="css/bootstrap-theme.min.css" type="text/css"/&gt; &lt;/head&gt; &lt;body onload="onCreate()"&gt; &lt;!-- Navigation Bar --&gt; &lt;div class="navbar navbar-inverse navbar-static-top"&gt; &lt;div class="navbar-inner"&gt; &lt;div class="container"&gt; &lt;a class="navbar-brand" href="#"&gt;nuEats&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Clock --&gt; &lt;div class="container"&gt; &lt;div id="clock"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- Equivalency Meal Exchange Rate Timeline --&gt; &lt;div class="container"&gt; &lt;div id="rate-bars-label"&gt;Equivalency Meal Exchange Rate:&lt;/div&gt; &lt;div class="rate-bars-container" id="rate-bars-container"&gt;&lt;/div&gt; &lt;div id="arrow"&gt;&lt;img src="arrow.png"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- Info Panels for Each Dining Hall --&gt; &lt;div class="container"&gt; &lt;div class="panel-group" id="accordion"&gt; &lt;!-- 1835 Hinman --&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading"&gt; &lt;h4 class="panel-title"&gt; 1835 Hinman &lt;a href="https://m-nucuisine.sodexomyway.com/images/Hinman3_tcm238-12915.htm"&gt; &lt;div class="menu"&gt;Menu&lt;/div&gt; &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;div id="collapseOne" class="panel-collapse collapse in"&gt; &lt;div id="hinman" class="panel-body"&gt; &lt;!-- This is where body text goes --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Allison --&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading"&gt; &lt;h4 class="panel-title"&gt; Allison &lt;a href="https://m-nucuisine.sodexomyway.com/images/Allison3_tcm238-9944.htm"&gt; &lt;div class="menu"&gt;Menu&lt;/div&gt; &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Elder --&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading"&gt; &lt;h4 class="panel-title"&gt; Elder &lt;a href="https://m-nucuisine.sodexomyway.com/images/Elder3_tcm238-12911.htm"&gt; &lt;div class="menu"&gt;Menu&lt;/div&gt; &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Plex East --&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading"&gt; &lt;h4 class="panel-title"&gt; Plex East &lt;a href="https://m-nucuisine.sodexomyway.com/images/Foster_East3_tcm238-12913.htm"&gt; &lt;div class="menu"&gt;Menu&lt;/div&gt; &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Plex West --&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading"&gt; &lt;h4 class="panel-title"&gt; Plex West &lt;a href="https://m-nucuisine.sodexomyway.com/images/Foster_West3_tcm238-12914.htm"&gt; &lt;div class="menu"&gt;Menu&lt;/div&gt; &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Sargent --&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading"&gt; &lt;h4 class="panel-title"&gt; Sargent &lt;a href="https://m-nucuisine.sodexomyway.com/images/Sargent3_tcm238-12910.htm"&gt; &lt;div class="menu"&gt;Menu&lt;/div&gt; &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Willard --&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading"&gt; &lt;h4 class="panel-title"&gt; Willard &lt;a href="https://m-nucuisine.sodexomyway.com/images/Willard3_tcm238-12912.htm"&gt; &lt;div class="menu"&gt;Menu&lt;/div&gt; &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;!-- Bootstrap Core Javascript --&gt; &lt;script src="jquery-1.10.1.min.js"&gt;&lt;/script&gt; &lt;!-- Change this back to the link when you publish!!! --&gt; &lt;script src="js/bootstrap.js"&gt;&lt;/script&gt; &lt;!-- User Javascript --&gt; &lt;script src="nuEats.js" type="text/javascript"&gt;&lt;/script&gt; &lt;html&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>#clock { font-size: 1em; } /* Control the label FONT above the timeline bars */ #rate-bars-label { margin-top: 5px; margin-bottom: 20px; font-size: 1em; font-weight: bold; } /* Format each equivalency-rate bar as a group */ .rate-bars { height: 1em; float: left; } /* Set each bar's color individually; add more CSS if you add more time blocks */ /* LIGHT GREEN */ #block0 { background-color: #40d351; } /* MEDIUM GREEN */ #block1 { background-color: #2e973a; } /* DARK GREEN */ #block2 { background-color: #216C2A; } /* MEDIUM GREEN */ #block3 { background-color: #2e973a; } /* Control the FONT surrounding the timeline bars */ .timeText { margin-top: -1.5em; margin-left: 5px; /* Some space makes it look better */ font-size: 0.75em; font-weight: bold; } .timeText-right { margin-top: -3.0em; font-size: 0.75em; font-weight: bold; float: right; } .priceText { margin-left: 5px; color: white; font-size: 0.75em; } /* Formatting concerning the "Menu" button */ .menu { font-weight: bold; float: right; } .menu:hover { text-decoration: underline; } </code></pre> <p><strong>JavaScript</strong></p> <pre><code>function onCreate() { // Consider this to be the "main" function of sorts document.getElementById("clock").innerHTML = createClock(); // Create a clock setInterval(function() { document.getElementById("clock").innerHTML = createClock(); }, 500); // Update it every half-second // Dynamically create equivalency-rate bars from array data // Time Equivalency Rate var EqRates = [ [7, 30, "5.00"], [10, 45, "7.00"], [16, 45, "9.00"], [19, 30, "7.00"], [26, 00, "N/A" ] ]; // 2:00 AM, the NEXT day! createEqRateBars(EqRates); // Set the position of an arrow pointing to the correct time block setArrowPosition(EqRates); setInterval(function() { setArrowPosition(EqRates); }, 1000); // Update it every second $(window).resize(function() { setArrowPosition(EqRates); }); // Update it upon window resize } /* * Create a clock, with special formatting */ function createClock() { // Date format is "Sunday, January 1st, 12:00:00 AM" var today = new Date(); var day = returnDay(today.getDay()); // Convert day integer to string (i.e. Monday, Tuesday, Wednesday...) var o = returnMonth(today.getMonth()); // Convert month integer to string (i.e. January, February, March...) var d = formatDate(today.getDate()); // Add suffix to date (i.e. 1st, 2nd, 4th...) var h = today.getHours(); var m = formatTime(today.getMinutes()); // If minutes or seconds is single digit, add zero before var s = formatTime(today.getSeconds()); var AMPM = getAMPM(h); h = h % 12; // Controls the final output of the clock's text return (day).bold() + ", " + o + " " + d + ", " + h + ":" + m + ":" + s + " " + AMPM; } // A series of helper functions function returnDay(day) { return ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][day]; } function returnMonth(month) { return ["January","February","March","April","May","June","July","August","September","October","November","December"][month]; } function formatDate(date) { digit = date % 10; if (digit == 1) { return date + "st"; } else if (digit == 2) { return date + "nd"; } else if (digit == 3) { return date + "rd"; } else { return date + "th"; } } // Add zeros before numbers where necessary function formatTime(i) { if (i &lt; 10) { i = "0" + i; } return i; } // Given an hour, determine if it is AM or PM function getAMPM(hour) { return ["AM","PM"][(((hour % 24) &gt;= 12) &amp; 1)]; } /* * Procedurally create equivalency rate exchange bars */ function createEqRateBars(EqRates) { // EqRates is a "3-dimensional" array of time slots and corresponding equivalency rates var rows = EqRates.length; var columns = EqRates[0].length; // Use the total length of all blocks to figure out what proportion each individual block takes up var startMin = timeInMin(EqRates[0][0], EqRates[0][1]); // Converts hours and minutes to just minutes for easy math var endMin = timeInMin(EqRates[rows - 1][0], EqRates[rows - 1][1]); var totalMin = endMin - startMin; // For each time block, create a div that represents that block graphically as a horizontal bar for (var i = 0; i &lt; rows - 1; i++) { // Set up variables that specify the horizontal bar's name and width, then add it var name = "block" + i; var blockMin = timeInMin(EqRates[i + 1][0], EqRates[i + 1][1]) - timeInMin(EqRates[i][0], EqRates[i][1]); var blockWidth = (blockMin / totalMin) * 100 + "%"; jQuery('&lt;div/&gt;', { id: name, class: "rate-bars", css: { width: blockWidth, } }).appendTo('#rate-bars-container'); // Format time information, then display it ABOVE the bar var hour = EqRates[i][0] % 12; // 12-hour time var minute = formatTime(EqRates[i][1]); // Add '0' before minute if minute &lt; 10 var AMPM = getAMPM(EqRates[i][0]); // Is it AM or PM? jQuery('&lt;div/&gt;', { class: 'timeText', text: hour + ":" + minute + " " + AMPM }).appendTo("#" + name); // Pull price information, then display it ON the bar var price = EqRates[i][2]; jQuery('&lt;div/&gt;', { class: 'priceText', text: '$' + price }).appendTo("#" + name); } // Do something special to pull closing time and put it ABOVE the bar and flush right var hour = EqRates[rows-1][0] % 12; // 12-hour time var minute = formatTime(EqRates[rows-1][1]); // Add '0' before minute if minute &lt; 10 var AMPM = getAMPM(EqRates[rows - 1][0]); // Is it AM or PM? jQuery('&lt;div/&gt;', { class: 'timeText-right', text: hour + ":" + minute + " " + AMPM }).appendTo("#" + name); // Just to keep thing simple, we'll make it a subclass of the last horizontal bar } /* * Set arrow location depending on equivalency meal value */ function setArrowPosition(EqRates) { // EqRates is a "3-dimensional" array of time slots and corresponding equivalency rates var rows = EqRates.length; // Get some time information var today = new Date(); var currentMin = dateInMin(today); // Current time in minutes from midnight var openMin = timeInMin(EqRates[0][0], EqRates[0][1]); // 7:30 AM - same format var closeMin = timeInMin(EqRates[rows - 1][0], EqRates[rows - 1][1]); // 2:00 AM the NEXT DAY - same format var DAY_IN_MINUTES = 24*60; // Will be useful later on for subtracting // If it is after 7:30 AM OR before 2:00 AM on the SAME DAY, show the arrow, otherwise hide it if (currentMin &gt;= openMin || currentMin &lt; closeMin - DAY_IN_MINUTES) { /* Place the "current time" arrow as such: * 1) Subtract currentMin by openMin so the arrow is at 0(%) displacement at 7:30 AM * 2) Divide by (closeMin - openMin), the minutes from open to close time, so that at close time, the arrow is at 100(%) displacement * 3) There is 5px of offset from the width of the arrow, convert that to a (%) and subtract it * 4) Multiply by 100 so we have an actual percent * 5) Set this absolute number to the left-margin shift */ var timelinePercent = [(currentMin - openMin)/(closeMin - openMin) - (5/$("#rate-bars-container").width())] * 100; $("#arrow").css("margin-left", timelinePercent + "%"); } else { $("#arrow").hide(); } } // Easy ways to return times as minutes function dateInMin(dateObject) { return dateObject.getHours() * 60 + dateObject.getMinutes(); } function timeInMin(hours, minutes) { return hours * 60 + minutes; } </code></pre> <p>Furthermore, I want to have the bar for each dining hall glow green or red depending on whether or not the dining hall is open and show what kind of meal (breakfast, lunch, dinner, etc.) it is currently serving. I plan to pull this information from a tab-delimited table in a text file. Can anyone recommend a best/better way to do this? I was thinking either Javascript or PHP, but I don't really like PHP, both because I don't know it yet and because I believe it will spaghettify my code.</p>
[]
[ { "body": "<p>From a once over,</p>\n\n<p><strong>DRY (Dont' Repeat Yourself)</strong></p>\n\n<ul>\n<li><p>You have a number of these blocks that seem all copy pasted:</p>\n\n<pre><code>&lt;!-- Sargent --&gt;\n&lt;div class=\"panel panel-default\"&gt;\n &lt;div class=\"panel-heading\"&gt;\n &lt;h4 class=\"panel-title\"&gt;\n Sargent\n &lt;a href=\"https://m-nucuisine.sodexomyway.com/images/Sargent3_tcm238-12910.htm\"&gt;\n &lt;div class=\"menu\"&gt;Menu&lt;/div&gt;\n &lt;/a&gt;\n &lt;/h4&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre></li>\n</ul>\n\n<p>You could consider having a JavaScript array holding just the restaurant names and links and then building the HTML with templating. Furthermore I am not sure why you need an h4 in a div in a div, you should be able to style the top div in such a manner that the HTML would look like </p>\n\n<pre><code> &lt;!-- Sargent --&gt;\n &lt;div class=\"panel panel-default awesomerestaurantclass\"&gt;\n Sargent\n &lt;a href=\"https://m-nucuisine.sodexomyway.com/images/Sargent3_tcm238-12910.htm\"&gt;\n &lt;div class=\"menu\"&gt;Menu&lt;/div&gt;\n &lt;/a&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p><strong>Style</strong></p>\n\n<ul>\n<li>Don't skip the newlines in <code>returnDay</code> and <code>returnMonth</code></li>\n<li><p><code>formatTime</code> could use a ternary, <code>return (i &lt; 10) ? (\"0\" + i) : i;</code></p></li>\n<li><p><code>createEqRateBars</code> is mixing logic/calculation and creation of UI elements, you should split that out in 2 functions. It looks messy and too tightly coupled now.</p></li>\n</ul>\n\n<p><strong>Functionality</strong></p>\n\n<ul>\n<li>It seems like your code in <code>formatDate</code> will return <code>11st</code> and <code>13rd</code>, that seems wrong</li>\n</ul>\n\n<p><strong>All in all</strong></p>\n\n<p>Time/date handling is a pain in any language, and I think you pulled it off pretty well. I probably would have encapsulated <code>EqRates</code> into an object with helper functions to make the code a little more readable, but other than that I would not maintaining code like this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T01:27:18.100", "Id": "79822", "Score": "0", "body": "Thanks for taking the time to do this. One question... Is it bad to use a javascript array to hold data like that? Would it be netter to store it in another way, and if so, what would that be?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T21:57:33.957", "Id": "79902", "Score": "0", "body": "Since the concept of times and names of months/days is unlikely to change, I think you are taking the right approach." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:58:50.313", "Id": "45309", "ParentId": "45067", "Score": "3" } } ]
{ "AcceptedAnswerId": "45309", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T07:30:45.070", "Id": "45067", "Score": "5", "Tags": [ "javascript", "jquery", "html", "css", "twitter-bootstrap" ], "Title": "Cleaning up a dining hall...website" }
45067
<p>Is there a more efficient way to write this? Seems redundant to me:</p> <pre><code> var leaves = $(".leaf"); var trees = $(".tree"); $(".my-class").on("click", function (e) { if ($(e.target).hasClass("leaf")) { trees.each(function() { $(this).attr("tabIndex", -1); }); leaves.each(function() { $(this).attr("tabIndex", 1); }); } else { trees.each(function() { $(this).attr("tabIndex", 1); }); leaves.each(function() { $(this).attr("tabIndex", -1); }); } }); </code></pre>
[]
[ { "body": "<p><a href=\"http://api.jquery.com/attr/#attr2\" rel=\"nofollow\"><code>.attr()</code></a> can work on all jQuery matched elements at once.</p>\n\n<p>Assuming that performance isn't a concern, I think that the clearest way would be to \"reset\" all nodes to have a <code>tabIndex</code> of <code>-1</code> first.</p>\n\n<pre><code>var leaves = $(\".leaf\");\nvar trees = $(\".tree\");\n\n$(\".my-class\").on(\"click\", function(e) {\n leaves.add(trees).attr(\"tabIndex\", -1);\n\n var selected = $(e.target).hasClass(\"leaf\") ? leaves : trees;\n selected.attr(\"tabIndex\", 1);\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T04:27:42.387", "Id": "78701", "Score": "0", "body": "Apologies. I made a typo --the correction is above. The conditionals are actually different." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T08:08:39.170", "Id": "45070", "ParentId": "45068", "Score": "3" } }, { "body": "<pre><code>if ($(e.target).hasClass(\"leaf\")) {\n // do x\n} else {\n // do x but in a different way\n}\n</code></pre>\n\n<p>This part makes it harder to maintain. If you change one you must change the other.</p>\n\n<pre><code>$(this).attr(\"tabIndex\", -1);\n</code></pre>\n\n<p>You do not need jQuery for this. Try <code>this.setAttribute(\"tabIndex\", -1)</code> or even <code>this.tabIndex = -1</code>.</p>\n\n<p>Also, I see some problems with this code:</p>\n\n<ol>\n<li>Why are you checking the event's target in <code>$().on(\"click\")</code>? Would the event's target not be <code>this</code>? Maybe you should change it to <code>$(\".leaf.my-class, .tree.my-class\")</code>?</li>\n<li>What if a user clicks on an element besides <code>.leaf</code> or <code>.tree</code>? The code suggests that you expect one or the other. Should <code>$(\".my-class\")</code> be changed to <code>$(\".leaf, .tree\")</code>?</li>\n<li>What if you add leaves? You will need to update <code>leaves</code> and <code>trees</code> if new leaves/trees are created.</li>\n</ol>\n\n<p>Here is my proposed solution...</p>\n\n<pre><code>var $leaves = $(\".leaf\"), $trees = $(\".tree\"), tabIndexLeaves = -1, tabIndexTrees = 1;\n$(\".my-class\").on(\"click\", function (e) {\n var isLeaf = $(e.target).hasClass(\"leaf\");\n if ((isLeaf &amp;&amp; tabIndexLeaves !== 1) || (!isLeaf &amp;&amp; tabIndexLeaves === -1)) {\n // Invert the tabIndex\n tabIndexLeaves = -tabIndexLeaves;\n tabIndexTrees = -tabIndexTrees;\n // Update all the leaves' and trees' tabIndexes\n $leaves.attr(\"tabIndex\", \"\" + tabIndexLeaves);\n $trees.attr(\"tabIndex\", \"\" + tabIndexTrees);\n }\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T15:47:32.700", "Id": "45757", "ParentId": "45068", "Score": "0" } } ]
{ "AcceptedAnswerId": "45070", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T07:39:20.870", "Id": "45068", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Setting TabIndex efficiently" }
45068
<p>I have some animations happening after some delay calls the code to animate. It works fine, but the code to call the functions is not nice.</p> <pre><code> double delayInSeconds = 0.2; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.1 * NSEC_PER_SEC); dispatch_time_t popTime2 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.2 * NSEC_PER_SEC); dispatch_time_t popTime3 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.3 * NSEC_PER_SEC); dispatch_time_t popTime4 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.4 * NSEC_PER_SEC); dispatch_time_t popTime5 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.5 * NSEC_PER_SEC); dispatch_time_t popTime6 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.6 * NSEC_PER_SEC); dispatch_time_t popTime7 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.7 * NSEC_PER_SEC); dispatch_time_t popTime8 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.8 * NSEC_PER_SEC); if (self.menuType == kRacingMenu) { self.menuAnimationSequence = @[@0, @1, @3, @2, @4]; //animation sequence! dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:0]; }); dispatch_after(popTime2, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:1]; }); dispatch_after(popTime3, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:2]; }); dispatch_after(popTime4, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:4]; }); dispatch_after(popTime5, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:3]; }); }else if (self.menuType == kLoginMenu) { self.menuAnimationSequence = @[@0, @1, @3, @2]; //animation sequence! dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:0]; }); dispatch_after(popTime2, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:1]; }); dispatch_after(popTime3, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:2]; }); dispatch_after(popTime4, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:3]; }); } else { [self animateWithCoreAnimaGenerallyWithIndex:1]; dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:0]; }); dispatch_after(popTime2, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:2]; }); dispatch_after(popTime3, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:4]; }); dispatch_after(popTime4, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:3]; }); dispatch_after(popTime5, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:5]; }); dispatch_after(popTime6, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:7]; }); dispatch_after(popTime7, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:6]; }); dispatch_after(popTime8, dispatch_get_main_queue(), ^(void){ [self animateWithCoreAnimaGenerallyWithIndex:8]; }); } </code></pre> <p>How best to abstract this timer? And the calls to start the animation?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:42:16.993", "Id": "78527", "Score": "0", "body": "`animateWithCoreAnimaGenerallyWithIndex:`? Find & replace error or your own method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:49:21.607", "Id": "78530", "Score": "0", "body": "@Flambino, Hi thanks, didn't understand your question, I got no error, was this the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T18:38:57.663", "Id": "78541", "Score": "0", "body": "It looks like you can accomplish a lot of this with a for loop and an incremented delay variable passed to a `UIView` animation block." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T00:38:57.647", "Id": "78558", "Score": "0", "body": "What I meant was that `animateWithCoreAnimaGenerallyWithIndex:` doesn't sound like a real method name. I mean, \"AnimaGenerally\"? It just seemed like it might be a mistake. But if you have a method that's called that, then OK - it's just a really strange method name." } ]
[ { "body": "<p>Anything that you're using as a constant should be marked as such. </p>\n\n<pre><code>double const delayInSeconds = 0.2f;\n</code></pre>\n\n<hr>\n\n<p>Now then, we know in Objective-C, we have <code>NSArray</code> and its mutable cousin, and they can only hold objects. But also remember, Objective-C is a superset of C. We can use a C-Style array.</p>\n\n<pre><code>int const POPTIME_COUNT = 8;\n\ndispatch_time_t poptime[POPTIME_COUNT];\n</code></pre>\n\n<p>And then fill this an array with a loop...</p>\n\n<pre><code>for (int i = 0; i &lt; POPTIME_COUNT; ++i) {\n double totalDelay = delayInSeconds + ((i + 1) * 0.1 * NSEC_PER_SEC) \n poptime[i] = dispatch_time(DISPATCH_TIME_NOW, totalDelay);\n}\n</code></pre>\n\n<hr>\n\n<p>Firing off the animations is done just as easily in a loop:</p>\n\n<pre><code>for (int i = 0; i &lt; NUM_ANIMATIONS; ++i) {\n dispatch_after(poptime[i], dispatch_get_main_queue()), ^(void){\n [self animateWithCoreAnimaGenerallyWithIndex:i];\n }];\n}\n</code></pre>\n\n<p>Where <code>NUM_ANIMATIONS</code> is the number of animations you need to fire off (it's different in each branch).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T01:20:49.937", "Id": "45119", "ParentId": "45084", "Score": "3" } } ]
{ "AcceptedAnswerId": "45119", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T13:36:49.727", "Id": "45084", "Score": "2", "Tags": [ "objective-c", "ios", "animation" ], "Title": "Best way to refactor this loop of animations with delay?" }
45084
<h1>Description</h1> <p>This is my code for the <a href="https://codereview.meta.stackexchange.com/questions/1471/weekend-challenge-reboot">Weekend Challenge Reboot</a> - Tic Tac Toe Ultimate.</p> <p>The game can be played here: <a href="http://www.zomis.net/ttt" rel="nofollow noreferrer">http://www.zomis.net/ttt</a> (along with some other variations that are also use the same code base, but with other 'controllers').</p> <p>This question contains the game model and a 'controller' for the TicTacToe Ultimate game.</p> <p>The classic TTT is 3*3. TTT Ultimate is a 3*3 grid of classic TTTs, so 3*3 * 3*3. As usual I wanted this code to be flexible, so technically it should be possible to extend it to a TTTUltimatePlus which would be a 3*3 grid of TTTUltimate games, or 3*3 * 3*3 * 3*3. I have not done a controller for TTTUltimatePlus yet, but the <code>TTBase</code> system would support it. When I started this project, I did not expect myself to make it work with Reversi (a.k.a. Othello), or Quantum Tic-Tac-Toe but well... when I realized how I could structure this I thought "Why not?".</p> <p>My first code, having a <code>TTUltimateGame</code>, <code>TTBoard</code> and a <code>TTField</code> class had a lot of code duplication which I wanted to avoid. This made me want to make this code. The <code>TTBase</code> class is the most important one, to support any number of recursiveness (by making a TTTUltimatePlus for example) I made it as a <em>recursive</em> class. Each clickable field is a TTBase, each area containing the fields is a TTBase, and the outermost game itself is a TTBase.</p> <h3>Class Summary (695 lines in 12 files, making a total of 18218 bytes)</h3> <ul> <li>HasSub.java: Interface indicating that a class contains smaller parts, 'subs' (a small field is a sub to a 3x3 area for example).</li> <li>TicFactory.java: Interface for creating TTBase objects.</li> <li>TicUtils.java: Utility methods, including code to create the Win Conditions for a TTBase.</li> <li>TTBase.java: Class that can contain more TTBases in a rectangular grid. Can be won and played by players.</li> <li>TTController.java: Abstract class for determining which TTBases that can be played and for playing at them.</li> <li>TTFactories.java: Code to instanciate variations of TTBases.</li> <li>TTMNKParameters.java: Parameters for creating a TTBase. Determines the size of the board and the number of consecutive fields that must be won by the same player.</li> <li>TTMoveListener.java: Interface for when a move has been made</li> <li>TTPlayer.java: An enum for players; X or O, and none, or both.</li> <li>TTUltimateController.java: Provides a TTController for TTT Ultimate.</li> <li>TTWinCondition.java: A rule for determining if a board is won by checking a number of fields. A classic TTT board for example has 8 win conditions: 3 rows, 3 columns and 2 diagonals.</li> <li>Winnable.java: Interface for something that can be won by a TTPlayer.</li> </ul> <h1>Code</h1> <p>This code can also be downloaded from <a href="https://github.com/Zomis/UltimateTTT" rel="nofollow noreferrer">GitHub</a></p> <p><strong>HasSub.java:</strong> (15 lines, 369 bytes)</p> <pre><code>/** * Interface for classes that can contain other objects, 'subs', in a rectangular way * * @param &lt;T&gt; Type of sub */ public interface HasSub&lt;T&gt; extends Winnable { T getSub(int x, int y); Iterable&lt;TTWinCondition&gt; getWinConds(); int getSizeX(); int getSizeY(); int getConsecutiveRequired(); boolean hasSubs(); } </code></pre> <p><strong>TicFactory.java:</strong> (5 lines, 117 bytes)</p> <pre><code>public interface TicFactory { TTBase construct(TTBase parent, int x, int y); } </code></pre> <p><strong>TicUtils.java:</strong> (140 lines, 4211 bytes)</p> <pre><code>public class TicUtils { /** * Get which board a tile will send the opponent to (in a TTTUltimate context) * * @param tile The tile to be played * @return The board which the tile directs to */ public static TTBase getDestinationBoard(TTBase tile) { TTBase parent = tile.getParent(); if (parent == null) return null; TTBase grandpa = parent.getParent(); if (grandpa == null) return null; return grandpa.getSub(tile.getX(), tile.getY()); } /** * Find the win conditions which contains a specific field * * @param field The field to look for * @param board Where to look for win conditions * @return A collection which only contains win conditions which contains the field */ public static &lt;E extends Winnable&gt; Collection&lt;TTWinCondition&gt; getWinCondsWith(E field, HasSub&lt;E&gt; board) { Collection&lt;TTWinCondition&gt; coll = new ArrayList&lt;&gt;(); for (TTWinCondition cond : board.getWinConds()) { if (cond.hasWinnable(field)) coll.add(cond); } return coll; } /** * Get all smaller tiles/boards in a board * * @param board Board to scan * @return Collection of all smaller tiles/boards contained in board. */ public static &lt;T&gt; Collection&lt;T&gt; getAllSubs(HasSub&lt;T&gt; board) { List&lt;T&gt; list = new ArrayList&lt;&gt;(); int sizeX = board.getSizeX(); int sizeY = board.getSizeY(); for (int x = 0; x &lt; sizeX; x++) { for (int y = 0; y &lt; sizeY; y++) { list.add(board.getSub(x, y)); } } return list; } /** * Recursively scan for smaller subs * * @param game The outermost object to scan * @return A collection containing all fields within the specified 'game' which do not have any subs */ public static Collection&lt;TTBase&gt; getAllSmallestFields(TTBase game) { Collection&lt;TTBase&gt; all = new ArrayList&lt;&gt;(); for (TTBase sub : TicUtils.getAllSubs(game)) { if (sub.hasSubs()) all.addAll(getAllSmallestFields(sub)); else all.add(sub); } return all; } /** * Create win conditions * * @param board The board to create win conditions for * @return A list of all WinConditions that was created */ public static List&lt;TTWinCondition&gt; setupWins(final HasSub&lt;? extends Winnable&gt; board) { if (!board.hasSubs()) { ArrayList&lt;TTWinCondition&gt; list = new ArrayList&lt;&gt;(); list.add(new TTWinCondition(board)); return list; } int consecutive = board.getConsecutiveRequired(); List&lt;TTWinCondition&gt; conds = new ArrayList&lt;&gt;(); // Scan columns for a winner for (int xx = 0; xx &lt; board.getSizeX(); xx++) { newWin(conds, consecutive, loopAdd(board, xx, 0, 0, 1)); } // Scan rows for a winner for (int yy = 0; yy &lt; board.getSizeY(); yy++) { newWin(conds, consecutive, loopAdd(board, 0, yy, 1, 0)); } // Scan diagonals for a winner: Bottom-right for (int yy = 0; yy &lt; board.getSizeY(); yy++) { newWin(conds, consecutive, loopAdd(board, 0, yy, 1, 1)); } for (int xx = 1; xx &lt; board.getSizeX(); xx++) { newWin(conds, consecutive, loopAdd(board, xx, 0, 1, 1)); } // Scan diagonals for a winner: Bottom-left for (int xx = 0; xx &lt; board.getSizeY(); xx++) { newWin(conds, consecutive, loopAdd(board, xx, 0, -1, 1)); } for (int yy = 1; yy &lt; board.getSizeY(); yy++) { newWin(conds, consecutive, loopAdd(board, board.getSizeX() - 1, yy, -1, 1)); } return conds; } private static void newWin(List&lt;TTWinCondition&gt; conds, int consecutive, List&lt;Winnable&gt; winnables) { if (winnables.size() &gt;= consecutive) // shorter win conditions doesn't need to be added as they will never be able to win conds.add(new TTWinCondition(winnables, consecutive)); } private static List&lt;Winnable&gt; loopAdd(HasSub&lt;? extends Winnable&gt; board, int xx, int yy, int dx, int dy) { List&lt;Winnable&gt; winnables = new ArrayList&lt;&gt;(); Winnable tile; do { tile = board.getSub(xx, yy); xx += dx; yy += dy; if (tile != null) winnables.add(tile); } while (tile != null); return winnables; } } </code></pre> <p><strong>TTBase.java:</strong> (149 lines, 3623 bytes)</p> <pre><code>public class TTBase implements Winnable, HasSub&lt;TTBase&gt; { // Container private final TTBase[][] subs; private final TTMNKParameters mnkParams; private final List&lt;TTWinCondition&gt; winConditions; // Winnable private final TTBase parent; private final int x; private final int y; private TTPlayer playedBy = TTPlayer.NONE; public TTBase(TTBase parent, TTMNKParameters parameters, TicFactory factory) { this(parent, 0, 0, parameters, factory); } public TTBase(TTBase parent, int x, int y, TTMNKParameters parameters, TicFactory factory) { this.parent = parent; this.mnkParams = parameters; this.x = x; this.y = y; this.subs = new TTBase[parameters.getWidth()][parameters.getHeight()]; for (int xx = 0; xx &lt; parameters.getWidth(); xx++) { for (int yy = 0; yy &lt; parameters.getHeight(); yy++) { this.subs[xx][yy] = factory.construct(this, xx, yy); } } this.winConditions = Collections.unmodifiableList(TicUtils.setupWins(this)); } public void determineWinner() { TTPlayer winner = TTPlayer.NONE; for (TTWinCondition cond : this.winConditions) { winner = winner.or(cond.determineWinnerNew()); } this.playedBy = winner; } @Override public TTBase getSub(int x, int y) { if (!hasSubs() &amp;&amp; x == 0 &amp;&amp; y == 0) return this; if (x &lt; 0 || y &lt; 0) return null; if (x &gt;= getSizeX() || y &gt;= getSizeY()) return null; return subs[x][y]; } @Override public List&lt;TTWinCondition&gt; getWinConds() { return winConditions; } @Override public TTPlayer getWonBy() { return this.playedBy; } @Override public int getSizeX() { return this.mnkParams.getWidth(); } @Override public int getSizeY() { return this.mnkParams.getHeight(); } @Override public int getConsecutiveRequired() { return this.mnkParams.getConsecutiveRequired(); } public TTMNKParameters getMNKParameters() { return this.mnkParams; } public TTBase getParent() { return parent; } public int getX() { return x; } public int getY() { return y; } public boolean isWon() { return playedBy != TTPlayer.NONE; } public void setPlayedBy(TTPlayer playedBy) { if (playedBy == null &amp;&amp; this.hasSubs() &amp;&amp; parent != null) new Exception().printStackTrace(); this.playedBy = playedBy; } public boolean hasSubs() { return getSizeX() != 0 &amp;&amp; getSizeY() != 0; } @Override public String toString() { return "{Pos " + x + ", " + y + "; Size " + getSizeX() + ", " + getSizeY() + "; Played by " + getWonBy() + ". Parent is " + parent + "}"; } public void reset() { this.setPlayedBy(TTPlayer.NONE); for (int xx = 0; xx &lt; getSizeX(); xx++) { for (int yy = 0; yy &lt; getSizeY(); yy++) { this.getSub(xx, yy).reset(); } } } public int getGlobalX() { if (parent == null) return 0; if (parent.getParent() == null) return x; return parent.getX() * parent.getParent().getSizeX() + this.x; } public int getGlobalY() { if (parent == null) return 0; if (parent.getParent() == null) return y; return parent.getY() * parent.getParent().getSizeY() + this.y; } public TTBase getSmallestTile(int x, int y) { int subX = x / getSizeX(); int subY = y / getSizeY(); TTBase board = getSub(subX, subY); if (board == null) throw new NullPointerException("No such smallest tile found: " + x + ", " + y); return board.getSub(x - subX*getSizeX(), y - subY*getSizeY()); } } </code></pre> <p><strong>TTController.java:</strong> (110 lines, 2867 bytes)</p> <pre><code>public abstract class TTController { protected final TTBase game; protected TTPlayer currentPlayer = TTPlayer.X; private TTMoveListener moveListener; private StringBuilder history; public TTController(TTBase board) { this.game = board; this.history = new StringBuilder(); } public abstract boolean isAllowedPlay(TTBase tile); public final boolean play(TTBase tile) { if (tile == null) throw new IllegalArgumentException("Tile to play at cannot be null."); if (!isAllowedPlay(tile)) { System.out.println("Warning: Move was not made. Unable to play at " + tile); return false; } TTBase playedTile = tile; if (!this.performPlay(tile)) return false; this.addToHistory(tile); if (this.moveListener != null) this.moveListener.onMove(playedTile); return true; } private void addToHistory(TTBase tile) { if (history.length() &gt; 0) history.append(","); history.append(Integer.toString(tile.getGlobalX(), Character.MAX_RADIX)); history.append(Integer.toString(tile.getGlobalY(), Character.MAX_RADIX)); } protected abstract boolean performPlay(TTBase tile); public boolean play(int x, int y) { return this.play(game.getSmallestTile(x, y)); } public TTPlayer getCurrentPlayer() { return currentPlayer; } protected void nextPlayer() { currentPlayer = currentPlayer.next(); } public TTBase getGame() { return game; } public boolean isGameOver() { return game.isWon(); } public TTPlayer getWonBy() { return game.getWonBy(); } public void setOnMoveListener(TTMoveListener moveListener) { this.moveListener = moveListener; } public void makeMoves(String history) throws IllegalStateException, IllegalArgumentException { for (String move : history.split(",")) { if (move.isEmpty()) continue; if (move.length() != 2) throw new IllegalArgumentException("Unexcepted move length. " + move); int x = Integer.parseInt(String.valueOf(move.charAt(0)), Character.MAX_RADIX); int y = Integer.parseInt(String.valueOf(move.charAt(1)), Character.MAX_RADIX); TTBase tile = game.getSmallestTile(x, y); if (!this.play(tile)) throw new IllegalStateException("Unable to make a move at " + x + ", " + y + ": " + tile); } } public String saveHistory() { return this.history.toString(); } public void reset() { this.currentPlayer = TTPlayer.X; this.history = new StringBuilder(); this.game.reset(); this.onReset(); } protected abstract void onReset(); public String getViewFor(TTBase tile) { return tile.isWon() ? tile.getWonBy().toString() : ""; } } </code></pre> <p><strong>TTFactories.java:</strong> (52 lines, 1616 bytes)</p> <pre><code>public class TTFactories { private static final TTMNKParameters mnkEmpty = new TTMNKParameters(0, 0, 0); private static final TicFactory lastFactory = new TicFactory() { @Override public TTBase construct(TTBase parent, int x, int y) { return new TTBase(parent, x, y, mnkEmpty, null); } }; private static final TicFactory areaFactory = new TicFactory() { @Override public TTBase construct(TTBase parent, int x, int y) { return new TTBase(parent, x, y, parent.getMNKParameters(), lastFactory); } }; public static class Factory implements TicFactory { private final TTMNKParameters mnk; private final TicFactory next; public Factory(TTMNKParameters mnk, TicFactory nextFactory) { this.mnk = mnk; this.next = nextFactory; } @Override public TTBase construct(TTBase parent, int x, int y) { return new TTBase(parent, x, y, mnk, next); } } public TTBase classicMNK(int width, int height, int consecutive) { return new TTBase(null, new TTMNKParameters(width, height, consecutive), lastFactory); } public TTBase classicMNK(int mnk) { return classicMNK(mnk, mnk, mnk); } public TTBase ultimate(int mnk) { return ultimate(mnk, mnk, mnk); } public TTBase ultimate(int width, int height, int consecutive) { return new TTBase(null, new TTMNKParameters(width, height, consecutive), areaFactory); } public TTBase ultimate() { return ultimate(3); } public TTBase othello(int size) { return new TTBase(null, new TTMNKParameters(size, size, size + 1), lastFactory); } } </code></pre> <p><strong>TTMNKParameters.java:</strong> (27 lines, 533 bytes)</p> <pre><code>public class TTMNKParameters { private final int width; private final int height; private final int consecutiveRequired; public TTMNKParameters(int width, int height, int consecutiveRequired) { this.width = width; this.height = height; this.consecutiveRequired = consecutiveRequired; } public int getConsecutiveRequired() { return consecutiveRequired; } public int getHeight() { return height; } public int getWidth() { return width; } } </code></pre> <p><strong>TTMoveListener.java:</strong> (5 lines, 104 bytes)</p> <pre><code>public interface TTMoveListener { void onMove(TTBase playedAt); } </code></pre> <p><strong>TTPlayer.java:</strong> (54 lines, 1273 bytes)</p> <pre><code>public enum TTPlayer { NONE, X, O, XO; public TTPlayer next() { if (!isExactlyOnePlayer()) throw new UnsupportedOperationException("Only possible to call .next() on a real player but it was called on " + this); return this == X ? O : X; } /** * Determine if this player is (also) another player.&lt;br&gt; * This is the same as &lt;code&gt;this.and(other) == other&lt;/code&gt; * * @param other * @return */ public boolean is(TTPlayer other) { return this.and(other) == other; } public TTPlayer and(TTPlayer other) { if (this == NONE || other == NONE || other == null) return NONE; if (isExactlyOnePlayer() &amp;&amp; other.isExactlyOnePlayer()) return this == other ? this : NONE; if (this == XO) return other; return other.and(this); } public boolean isExactlyOnePlayer() { return this == X || this == O; } public static boolean isExactlyOnePlayer(TTPlayer winner) { return winner != null &amp;&amp; winner.isExactlyOnePlayer(); } public TTPlayer or(TTPlayer other) { if (this == NONE || other == null) return other; if (other == NONE) return this; if (this == XO) return this; if (this != other) return XO; return this; } } </code></pre> <p><strong>TTUltimateController.java:</strong> (53 lines, 1386 bytes)</p> <pre><code>public class TTUltimateController extends TTController { // TODO: Try making it even more Ultimate by adding one more dimension, and use Map&lt;TTBase, TTBase&gt; activeBoards. Just for fun. private TTBase activeBoard = null; public TTUltimateController(TTBase board) { super(board); } @Override public boolean isAllowedPlay(TTBase tile) { TTBase area = tile.getParent(); if (area == null) return false; TTBase game = tile.getParent().getParent(); if (!tile.getWonBy().equals(TTPlayer.NONE)) return false; if (area.getWonBy().isExactlyOnePlayer()) return false; if (game.isWon()) return false; return activeBoard == null || activeBoard == area || activeBoard.getWonBy() != TTPlayer.NONE; } @Override public boolean performPlay(TTBase tile) { tile.setPlayedBy(currentPlayer); activeBoard = TicUtils.getDestinationBoard(tile); nextPlayer(); // Check for win condition on tile and if there is a win, cascade to it's parents do { tile.determineWinner(); tile = tile.isWon() ? tile.getParent() : null; } while (tile != null); return true; } @Override protected void onReset() { this.activeBoard = null; } } </code></pre> <p><strong>TTWinCondition.java:</strong> (78 lines, 2026 bytes)</p> <pre><code>public class TTWinCondition implements Iterable&lt;Winnable&gt; { private final List&lt;Winnable&gt; winnables; private final int consecutive; public TTWinCondition(Winnable... winnables) { this(Arrays.asList(winnables)); } public TTWinCondition(List&lt;? extends Winnable&gt; winnables) { this(winnables, winnables.size()); } public TTWinCondition(List&lt;? extends Winnable&gt; winnables, int consecutive) { if (winnables.isEmpty()) throw new IllegalArgumentException("Can't have an empty win condition!"); this.winnables = Collections.unmodifiableList(new ArrayList&lt;Winnable&gt;(winnables)); this.consecutive = consecutive; } public int neededForWin(TTPlayer player) { return winnables.size() - hasCurrently(player); } public boolean isWinnable(TTPlayer byPlayer) { return hasCurrently(byPlayer.next()) == 0; } public int hasCurrently(TTPlayer player) { int i = 0; for (Winnable winnable : winnables) { if (winnable.getWonBy().and(player) == player) i++; } return i; } public TTPlayer determineWinnerNew() { TTPlayer winner = TTPlayer.NONE; int[] consecutivePlayers = new int[TTPlayer.values().length]; for (Winnable winnable : winnables) { TTPlayer current = winnable.getWonBy(); for (TTPlayer pl : TTPlayer.values()) { int i = pl.ordinal(); if (pl.and(current) == pl) { consecutivePlayers[i]++; } else consecutivePlayers[i] = 0; if (consecutivePlayers[i] &gt;= this.consecutive) { winner = winner.or(pl); } } } return winner; } public boolean hasWinnable(Winnable field) { return winnables.contains(field); } public int size() { return winnables.size(); } @Override public Iterator&lt;Winnable&gt; iterator() { return new ArrayList&lt;Winnable&gt;(this.winnables).iterator(); } } </code></pre> <p><strong>Winnable.java:</strong> (7 lines, 93 bytes)</p> <pre><code>public interface Winnable { TTPlayer getWonBy(); } </code></pre> <h1>Usage / Test</h1> <p>You can play the game on <a href="http://www.zomis.net/ttt" rel="nofollow noreferrer">http://www.zomis.net/ttt</a> . The GUI checks with the controller if a field can be played or not and uses the methods provided by the controller to make a move on a field. The GUI is written using GWT (Google Web Toolkit) which compiles my Java code to JavaScript and obfuscates it for me.</p> <h1>Questions</h1> <p>Things I am quite proud of includes the <code>TTWinCondition</code> class, especially the way TTWinConditions is created.</p> <p>I am also quite proud of the <code>TTPlayer</code> enum and how it includes both NONE and XO (both), and it's <code>and</code> and <code>or</code> methods.</p> <p>Things I am not so proud of includes the <code>TTBase</code> class. It is the best thing I could come up with though (and it is probably the most unique way of all the challenge implementations). I really couldn't come up with a more flexible way that would support any number of recursiveness, and at the same time removing code duplication.</p> <p>This project uses Java 7. It also needs to support GWT so I cannot use <code>String.format</code>.</p> <p>I'd mostly like comments about how I have designed these classes and interfaces. And if anyone knows a better way to do things than what I have done here, I'd love to hear them.</p> <p>You may not agree with my naming of classes to start with <code>TT</code>, but I do this to make it easier for me to find my TTT-specific classes when using Eclipse's Ctrl + Shift + T keyboard shortcut.</p>
[]
[ { "body": "<p>There is not much to criticize in your code.... and there is a lot of code to go though.</p>\n\n<p>Mostly really neat, and, it takes a while to 'grok' it, but it comes together OK.</p>\n\n<p>Here's a laundry-list of small items (there are no big Items I can see):</p>\n\n<ul>\n<li><p>In TTUtils:</p>\n\n<ul>\n<li><code>getWinCondsWith</code> is a method that is never called from anywhere</li>\n<li><code>getAllSmallestFields</code> should be called <code>getAllSmallestSubs</code> to match other methods.</li>\n</ul></li>\n<li><p>In TTBase:</p>\n\n<ul>\n<li><p>Unmodifiable in constructor:</p>\n\n<blockquote>\n<pre><code>this.winConditions = Collections.unmodifiableList(TicUtils.setupWins(this));\n</code></pre>\n</blockquote>\n\n<p>I would expect the unmodifiable constraint to be set in <code>setupWins()</code>, in other words it should return an unmodifyable list rather than having that imposed outside the call.</p></li>\n<li><p>in <code>setPlayedBy()</code> you have:</p>\n\n<blockquote>\n<pre><code>if (playedBy == null &amp;&amp; this.hasSubs() &amp;&amp; parent != null)\n new Exception().printStackTrace();\n</code></pre>\n</blockquote>\n\n<p>No Braces is against Java code-style</p>\n\n<p>You are printing a stack trace, but continuing to set the value <code>null</code> anyway.</p>\n\n<p>This would be a good location for an <code>assert</code>.</p></li>\n</ul></li>\n<li><p>TTFactories</p>\n\n<ul>\n<li>all the private-static-final fields should be ALL_UPPERCASE per the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\">Java Guidelines</a></li>\n</ul></li>\n<li><p>TTPlayer</p>\n\n<ul>\n<li><p><a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#15395\">un-braced 1-liner if statements again</a>:</p></li>\n<li><p>or - if <code>this==NONE</code> and <code>other == null</code>, then why return null instead of NONE?</p>\n\n<blockquote>\n<pre><code> public TTPlayer or(TTPlayer other) {\n if (this == NONE || other == null)\n return other;\n if (other == NONE)\n return this;\n if (this == XO)\n return this;\n if (this != other)\n return XO;\n return this;\n }\n</code></pre>\n</blockquote></li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T04:20:53.590", "Id": "45125", "ParentId": "45086", "Score": "12" } }, { "body": "<p><em>More than four years later...</em> I discovered a bug in the code below:</p>\n\n<pre><code>// Scan diagonals for a winner: Bottom-left\nfor (int xx = 0; xx &lt; board.getSizeY(); xx++) {\n newWin(conds, consecutive, loopAdd(board, xx, 0, -1, 1));\n}\nfor (int yy = 1; yy &lt; board.getSizeY(); yy++) {\n newWin(conds, consecutive, loopAdd(board, board.getSizeX() - 1, yy, -1, 1));\n}\n</code></pre>\n\n<p>When you mix <code>x</code> and <code>y</code> on the same line, it's usually an indication that you are doing something wrong. Your code can be used in any <a href=\"https://en.wikipedia.org/wiki/M,n,k-game\" rel=\"noreferrer\">MNK-game</a> which is nice, but this code will not check for a winning condition in this case for a 7,6,4 game (Connect Four):</p>\n\n<pre><code>0000000\n0000000\n0000X00\n000XO00\n00XOO00\n0XOOX00\n</code></pre>\n\n<p>Because the last bottom-left scan is missing because of <code>getSizeY()</code> being one less than <code>getSizeX()</code>, correct would be:</p>\n\n<pre><code>for (int xx = 0; xx &lt; board.getSizeX(); xx++) {\n</code></pre>\n\n<p>(Seems like <a href=\"https://codereview.stackexchange.com/a/179676/31562\">I have a thing for finding bugs four years later</a>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-13T22:34:08.920", "Id": "192016", "ParentId": "45086", "Score": "5" } }, { "body": "<p><em>Almost six years later...</em> I discovered a bug in the code below:</p>\n\n<pre><code>@Override\npublic boolean isAllowedPlay(TTBase tile) {\n TTBase area = tile.getParent();\n if (area == null)\n return false;\n TTBase game = tile.getParent().getParent();\n\n if (!tile.getWonBy().equals(TTPlayer.NONE))\n return false;\n if (area.getWonBy().isExactlyOnePlayer())\n return false;\n if (game.isWon())\n return false;\n\n return activeBoard == null || activeBoard == area || activeBoard.getWonBy() != TTPlayer.NONE;\n}\n</code></pre>\n\n<p>Now let's say that we have this map:</p>\n\n<pre><code>__O __X XOX\n_O_ _OO XOX\nO_X X_O OXO\n\n__O X_O O_X\nX_O OX_ O_X\nO_O OXX OXO\n\nX_X O__ ___\nX_X XOO XXX\nXXO OXO OXX\n</code></pre>\n\n<p>Looking at the \"bigger picture\" the areas won are</p>\n\n<pre><code>O__\nOXO\nXOX\n</code></pre>\n\n<p>Say that the last move was the 'X' in \"__X\" on the first row. This leads to the <code>activeBoard</code> being the area in the top right. This area is not won by anyone, but the whole area is full. So it should somehow be considered as a draw. The statement <code>activeBoard.getWonBy() != TTPlayer.NONE</code> will return false in this case, which leads to no current tile is allowed to play at. The game is stuck.</p>\n\n<p>The solution: Support draws.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T16:00:12.943", "Id": "235022", "ParentId": "45086", "Score": "2" } } ]
{ "AcceptedAnswerId": "45125", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T15:23:32.000", "Id": "45086", "Score": "18", "Tags": [ "java", "game", "tic-tac-toe", "community-challenge" ], "Title": "Recursive and flexible approach to Tic-Tac-Toe" }
45086
<p>This code is starting to be used within several of my projects, and therefore I thought it's time to get it reviewed.</p> <h1>Description</h1> <p>The most common application for this code is that there is a computer opponent in a game which needs to make a decision based on some parameters. A list of all possible decisions that can be made is created/retrieved somehow (Note that for Real-Time Strategy games this could be a list such as <code>Build A</code>, <code>Build B</code>, <code>Attack C</code>, <code>Explore D</code>, etc). To make the decision, each option is given score from several sources, called <strong><code>Scorers</code></strong>. Each AI is configured to use a set of Scorers with a weight applied to each scorer.</p> <p>Below is some pictures for how this is currently used within my <a href="http://www.minesweeperflags.net/play" rel="nofollow noreferrer">Minesweeper Flags game</a> (That is Minesweeper in turn-based 2-player mode where the objective is to take the mines and not avoid them). On each possible field to make a move on, there is a number determining the "rank", 1 is the among the best possible moves, 2 is among the second best, and so on (the number of possible ranks depends on the situation and the scorers that is applied)</p> <p>The map that will be scored:</p> <p><img src="https://i.stack.imgur.com/v9CNo.png" alt="The Map that will be scored"></p> <p>Rank of fields after having scores applied by "AI HardPlus":</p> <p><img src="https://i.stack.imgur.com/Bh3LY.png" alt="AI HardPlus scoring"></p> <p>Rank of fields after having scores applied by "AI Nightmare":</p> <p><img src="https://i.stack.imgur.com/8jNx0.png" alt="AI Nightmare scoring"></p> <p>Rank of fields after having scores applied by "AI Loser": (has a preference for fields with low mine probability)</p> <p><img src="https://i.stack.imgur.com/uUdKw.png" alt="AI Loser scoring"></p> <h3>Class Summary (740 lines in 13 files, making a total of 21944 bytes)</h3> <ul> <li>AbstractScorer: Abstract class for a normal scorer</li> <li>FieldScore: Stores score information for a single field</li> <li>FieldScoreProducer: A class that, given a score configuration, can produce FieldScores.</li> <li>FieldScores: Stores FieldScore objects for several fields</li> <li>PostScorer: Abstract class for applying score to fields when all AbstractScorers have finished scoring</li> <li>PreScorer: Interface responsible for analyzing things if needed before the AbstractScorers begin scoring</li> <li>ScoreConfig: Score configuration</li> <li>ScoreConfigFactory: Factory class for creating <code>ScoreConfig</code></li> <li>ScoreParameters: Interface for allowing scorers to access analyze data and the parameters sent for scoring</li> <li>Scorer: Marker interface for classes that are responsible for applying score, i.e. Scorers and PostScorers</li> <li>ScoreSet: A <code>Map&lt;AbstractScorer, Double&gt;</code> for keeping track of the weights that should be applied to the scorers</li> <li>ScoreStrategy: Interface for providing the list of fields that should be scored</li> <li>ScoreTools.java: Just a couple of utility methods</li> </ul> <p>This code can also be downloaded from <a href="https://github.com/Zomis/AIScorers" rel="nofollow noreferrer">its repository on GitHub</a>.</p> <p><strong>AbstractScorer.java:</strong> (31 lines, 993 bytes)</p> <pre><code>/** * Scorer that is responsible to give score to fields * * @param &lt;P&gt; Score parameter type * @param &lt;F&gt; The type to apply scores to */ public abstract class AbstractScorer&lt;P, F&gt; implements Scorer { /** * Determine if this scorer should apply scores to the fields under the given circumstances. * * @param scores Score parameters and analyzes for the scoring * @return True to work with the parameters, false to exclude this scorer entirely from the current scoring process */ public boolean workWith(ScoreParameters&lt;P&gt; scores) { return true; } /** * Determine the score for the given field and parameters. * @param field Field to score * @param scores Parameters and analyzes for the scoring * @return The score to give to the field */ public abstract double getScoreFor(F field, ScoreParameters&lt;P&gt; scores); @Override public String toString() { return this.getClass().getSimpleName(); } } </code></pre> <p><strong>FieldScore.java:</strong> (99 lines, 2434 bytes)</p> <pre><code>/** * Score container for a specific field. * * @param &lt;F&gt; The type to apply scores to. */ public class FieldScore&lt;F&gt; implements Comparable&lt;FieldScore&lt;F&gt;&gt; { private int rank; private double score; private final F field; private final Map&lt;Scorer, Double&gt; specificScorers; private double normalized; public FieldScore(F field) { this(field, false); } /** * * @param field Field to score * @param detailed If true, details about how much score is given from each scorer will be saved */ public FieldScore(F field, boolean detailed) { this.field = field; this.specificScorers = detailed ? new HashMap&lt;Scorer, Double&gt;() : null; } void addScore(AbstractScorer&lt;?, F&gt; scorer, double score, double weight) { double add = score * weight; this.saveScore(scorer, add); } private void saveScore(Scorer scorer, double score) { this.score += score; if (scorer != null &amp;&amp; specificScorers != null) { this.specificScorers.put(scorer, score); } } void setRank(int rank) { this.rank = rank; } void setNormalized(double normalized) { this.normalized = normalized; } @Override public int compareTo(FieldScore&lt;F&gt; other) { return Double.compare(this.score, other.score); } public double getScore() { return this.score; } /** * Get the field represented by this {@link FieldScore} * @return The field that this object contains score for */ public F getField() { return this.field; } void giveExtraScore(PostScorer&lt;?, F&gt; scorer, double bonus) { this.saveScore(scorer, bonus); } /** * Get this field's rank. * @return The rank score of this field, where 1 is the best rank */ public int getRank() { return rank; } /** * Get this field's normalized score * @return Normalized score, from 0 to 1. */ public double getNormalized() { return this.normalized; } /** * Get detailed information about which scorer gave what score to this field * @return Detailed information, or null if this field did not save details */ public Map&lt;Scorer, Double&gt; getScoreMap() { return this.specificScorers == null ? null : new HashMap&lt;Scorer, Double&gt;(this.specificScorers); } @Override public String toString() { return "(" + this.field + " score " + this.score + ")"; } } </code></pre> <p><strong>FieldScoreProducer.java:</strong> (68 lines, 1887 bytes)</p> <pre><code>/** * * * @param &lt;P&gt; Score parameter type * @param &lt;F&gt; The type to apply scores to */ public class FieldScoreProducer&lt;P, F&gt; { private final ScoreConfig&lt;P, F&gt; config; private boolean detailed; private final ScoreStrategy&lt;P, F&gt; scoreStrategy; public FieldScoreProducer(ScoreConfig&lt;P, F&gt; config, ScoreStrategy&lt;P, F&gt; strat) { this.config = config; this.scoreStrategy = strat; } public FieldScores&lt;P, F&gt; score(P params, Map&lt;Class&lt;?&gt;, Object&gt; analyzes) { FieldScores&lt;P, F&gt; scores = new FieldScores&lt;P, F&gt;(params, config, scoreStrategy); scores.setAnalyzes(analyzes); scores.setDetailed(this.detailed); scores.determineActiveScorers(); scores.calculateScores(); scores.rankScores(); scores.postHandle(); for (PreScorer&lt;P&gt; prescore : config.getPreScorers()) { prescore.onScoringComplete(); } return scores; } public boolean isDetailed() { return detailed; } /** * Set whether or not each FieldScore should contain detailed information about how much score the field got from all different scorers (including post scorers) * @param detailed True if detailed, false otherwise. */ public void setDetailed(boolean detailed) { this.detailed = detailed; } public Map&lt;Class&lt;?&gt;, Object&gt; analyze(P param) { Map&lt;Class&lt;?&gt;, Object&gt; analyze = new HashMap&lt;Class&lt;?&gt;, Object&gt;(); for (PreScorer&lt;P&gt; preScorers : this.config.getPreScorers()) { Object data = preScorers.analyze(param); if (data == null) continue; // avoid NullPointerException analyze.put(data.getClass(), data); } return analyze; } public ScoreConfig&lt;P, F&gt; getConfig() { return this.config; } public FieldScores&lt;P, F&gt; analyzeAndScore(P params) { return this.score(params, this.analyze(params)); } } </code></pre> <p><strong>FieldScores.java:</strong> (184 lines, 5823 bytes)</p> <pre><code>/** * Class containing scores, information about ranks, analyzes, and which score configuration that was used. * * @param &lt;P&gt; Score parameter type * @param &lt;F&gt; The type to apply scores to */ public class FieldScores&lt;P, F&gt; implements ScoreParameters&lt;P&gt; { private final ScoreConfig&lt;P, F&gt; config; private final Map&lt;F, FieldScore&lt;F&gt;&gt; scores = new HashMap&lt;F, FieldScore&lt;F&gt;&gt;(); private final P params; private final ScoreStrategy&lt;P, F&gt; scoreStrategy; private List&lt;AbstractScorer&lt;P, F&gt;&gt; activeScorers; private List&lt;List&lt;FieldScore&lt;F&gt;&gt;&gt; rankedScores; private Map&lt;Class&lt;?&gt;, Object&gt; analyzes; private boolean detailed; @SuppressWarnings("unchecked") public &lt;E&gt; E getAnalyze(Class&lt;E&gt; clazz) { E value = (E) this.analyzes.get(clazz); if (value == null) throw new NullPointerException("Analyze " + clazz + " not found. Did you forget to add a PreScorer using ScoreConfigFactory.withPreScorer?"); return value; } @Override public Map&lt;Class&lt;?&gt;, Object&gt; getAnalyzes() { return new HashMap&lt;Class&lt;?&gt;, Object&gt;(this.analyzes); } FieldScores(P params, ScoreConfig&lt;P, F&gt; config, ScoreStrategy&lt;P, F&gt; strat) { this.params = params; this.config = config; this.scoreStrategy = strat; } @Override public ScoreStrategy&lt;P, F&gt; getScoreStrategy() { return scoreStrategy; } /** * Call each {@link AbstractScorer}'s workWith method to determine if that scorer is currently applicable */ void determineActiveScorers() { activeScorers = new ArrayList&lt;AbstractScorer&lt;P, F&gt;&gt;(); for (AbstractScorer&lt;P, F&gt; scorer : config.getScorers().keySet()) { if (scorer.workWith(this)) { activeScorers.add(scorer); } } } /** * Process the {@link AbstractScorer}s to let them add their score for each field. Uses the {@link ScoreStrategy} associated with this object to determine which fields should be scored. */ void calculateScores() { for (F field : this.scoreStrategy.getFieldsToScore(params)) { if (!this.scoreStrategy.canScoreField(this, field)) continue; FieldScore&lt;F&gt; fscore = new FieldScore&lt;F&gt;(field, detailed); for (AbstractScorer&lt;P, F&gt; scorer : activeScorers) { double computedScore = scorer.getScoreFor(field, this); double weight = config.getScorers().get(scorer); fscore.addScore(scorer, computedScore, weight); } scores.put(field, fscore); } } /** * Call {@link PostScorer}s to let them do their job, after the main scorers have been processed. */ void postHandle() { for (PostScorer&lt;P, F&gt; post : this.config.getPostScorers()) { post.handle(this); this.rankScores(); // Because post-scorers might change the result, re-rank the scores to always have proper numbers. } } @Override public P getParameters() { return this.params; } /** * Get a List of all the ranks. Each rank is a list of all the {@link FieldScore} objects in that rank * @return A list of all the ranks, where the first item in the list is the best rank */ public List&lt;List&lt;FieldScore&lt;F&gt;&gt;&gt; getRankedScores() { return rankedScores; } /** * @return A {@link HashMap} copy of the scores that are contained in this object */ public Map&lt;F, FieldScore&lt;F&gt;&gt; getScores() { return new HashMap&lt;F, FieldScore&lt;F&gt;&gt;(this.scores); } /** * Get the {@link FieldScore} object for a specific field. * @param field Field to get data for * @return FieldScore for the specified field. */ public FieldScore&lt;F&gt; getScoreFor(F field) { return scores.get(field); } /** * (Re-)calculates rankings for all the fields, and also calculates a normalization of their score */ public void rankScores() { SortedSet&lt;Entry&lt;F, FieldScore&lt;F&gt;&gt;&gt; sorted = ScoreTools.entriesSortedByValues(this.scores, true); rankedScores = new LinkedList&lt;List&lt;FieldScore&lt;F&gt;&gt;&gt;(); if (sorted.isEmpty()) return; double minScore = sorted.last().getValue().getScore(); double maxScore = sorted.first().getValue().getScore(); double lastScore = maxScore + 1; int rank = 0; List&lt;FieldScore&lt;F&gt;&gt; currentRank = new LinkedList&lt;FieldScore&lt;F&gt;&gt;(); for (Entry&lt;F, FieldScore&lt;F&gt;&gt; score : sorted) { if (lastScore != score.getValue().getScore()) { lastScore = score.getValue().getScore(); rank++; currentRank = new LinkedList&lt;FieldScore&lt;F&gt;&gt;(); rankedScores.add(currentRank); } score.getValue().setRank(rank); double normalized = ScoreTools.normalized(score.getValue().getScore(), minScore, maxScore - minScore); score.getValue().setNormalized(normalized); currentRank.add(score.getValue()); } } /** * Get all {@link FieldScore} objects for a specific rank * @param rank From 1 to getRankLength() * @return A list of all FieldScores for the specified rank */ public List&lt;FieldScore&lt;F&gt;&gt; getRank(int rank) { if (rankedScores.isEmpty()) return null; return rankedScores.get(rank - 1); } /** * Get the number of ranks * @return The number of ranks */ public int getRankCount() { return rankedScores.size(); } /** * @return The score configuration that was used to calculate these field scores. */ public ScoreConfig&lt;P, F&gt; getConfig() { return this.config; } void setAnalyzes(Map&lt;Class&lt;?&gt;, Object&gt; analyzes) { this.analyzes = new HashMap&lt;Class&lt;?&gt;, Object&gt;(analyzes); } /** * @param detailed True to store detailed information about which scorer gives which score to which field. False otherwise */ public void setDetailed(boolean detailed) { this.detailed = detailed; } } </code></pre> <p><strong>PostScorer.java:</strong> (53 lines, 1779 bytes)</p> <pre><code>/** * A scorer that can apply/modify scores after the regular {@link AbstractScorer}s have done their job. * * @param &lt;P&gt; Score parameter type * @param &lt;F&gt; The type to apply scores to */ public abstract class PostScorer&lt;P, F&gt; implements Scorer { @Override public String toString() { return "Post-" + this.getClass().getSimpleName(); } /** * Optionally apply any scores to the given {@link FieldScores} object. * @param scores The collection of scores to work on. */ public abstract void handle(FieldScores&lt;P, F&gt; scores); /** * Add score to a field * @param fscore {@link FieldScore} container for the field * @param score Score to give */ protected void addScore(FieldScore&lt;F&gt; fscore, double score) { if (fscore == null) throw new NullPointerException("FieldScore was null."); fscore.giveExtraScore(this, score); } /** * Add score to a field * @param scores {@link FieldScores} object containing the field * @param field Field to apply score for * @param score Score to apply */ protected void addScore(FieldScores&lt;P, F&gt; scores, F field, double score) { FieldScore&lt;F&gt; fscore = scores.getScoreFor(field); this.addScore(fscore, score); } /** * Set score to an exact value for a field * @param scores {@link FieldScores} object containing the field * @param field Field to apply score for * @param score Score to apply */ protected void setScore(FieldScores&lt;P, F&gt; scores, F field, double score) { FieldScore&lt;F&gt; fscore = scores.getScoreFor(field); if (fscore == null) throw new NullPointerException("Field " + field + " does not have any matching FieldScore."); fscore.giveExtraScore(this, score - fscore.getScore()); } } </code></pre> <p><strong>PreScorer.java:</strong> (18 lines, 549 bytes)</p> <pre><code>/** * Interface for performing analyze work before scorers start scoring. * @param &lt;P&gt; Score parameter type */ public interface PreScorer&lt;P&gt; { /** * Perform analyze and return result of analyze * @param params The score parameters * @return The object that can be retrieved by the scorers */ Object analyze(P params); /** * Method that can be used to clean-up variables and resources. Called when a {@link FieldScores} object has been fully completed. */ void onScoringComplete(); } </code></pre> <p><strong>ScoreConfig.java:</strong> (43 lines, 1255 bytes)</p> <pre><code>/** * Score Configuration containing instances of {@link PreScorer}, {@link PostScorer} and {@link AbstractScorer} * * @param &lt;P&gt; Score parameter type * @param &lt;F&gt; The type to apply scores to */ public class ScoreConfig&lt;P, F&gt; { private final ScoreSet&lt;P, F&gt; scorers; private final List&lt;PostScorer&lt;P, F&gt;&gt; postScorers; private final List&lt;PreScorer&lt;P&gt;&gt; preScorers; public ScoreConfig(ScoreConfig&lt;P, F&gt; copy) { this(copy.preScorers, copy.postScorers, copy.scorers); } public ScoreConfig(List&lt;PreScorer&lt;P&gt;&gt; preScorers, List&lt;PostScorer&lt;P, F&gt;&gt; postScorers, ScoreSet&lt;P, F&gt; scorers) { this.postScorers = new ArrayList&lt;PostScorer&lt;P,F&gt;&gt;(postScorers); this.preScorers = new ArrayList&lt;PreScorer&lt;P&gt;&gt;(preScorers); this.scorers = new ScoreSet&lt;P, F&gt;(scorers); } public List&lt;PostScorer&lt;P, F&gt;&gt; getPostScorers() { return postScorers; } public ScoreSet&lt;P, F&gt; getScorers() { return scorers; } public List&lt;PreScorer&lt;P&gt;&gt; getPreScorers() { return preScorers; } @Override public String toString() { return "Scorers:{PreScorer: " + preScorers + ", PostScorer: " + postScorers + ", Scorers: " + scorers + "}"; } } </code></pre> <p><strong>ScoreConfigFactory.java:</strong> (124 lines, 3601 bytes)</p> <pre><code>/** * Factory class for creating a {@link ScoreConfig} * * @param &lt;P&gt; Score parameter type * @param &lt;F&gt; The type to apply scores to */ public class ScoreConfigFactory&lt;P, F&gt; { private ScoreSet&lt;P, F&gt; scoreSet; private final List&lt;PostScorer&lt;P, F&gt;&gt; postScorers; private final List&lt;PreScorer&lt;P&gt;&gt; preScorers; public static &lt;Params, Field&gt; ScoreConfigFactory&lt;Params, Field&gt; newInstance() { return new ScoreConfigFactory&lt;Params, Field&gt;(); } public ScoreConfigFactory() { this.scoreSet = new ScoreSet&lt;P, F&gt;(); this.postScorers = new LinkedList&lt;PostScorer&lt;P, F&gt;&gt;(); this.preScorers = new LinkedList&lt;PreScorer&lt;P&gt;&gt;(); } public ScoreConfigFactory&lt;P, F&gt; withScoreConfig(ScoreConfig&lt;P, F&gt; config) { ScoreConfigFactory&lt;P, F&gt; result = this; for (PreScorer&lt;P&gt; pre : config.getPreScorers()) { if (!preScorers.contains(pre)) result = withPreScorer(pre); } for (PostScorer&lt;P, F&gt; post : config.getPostScorers()) { if (!postScorers.contains(post)) result = withPost(post); } for (Entry&lt;AbstractScorer&lt;P, F&gt;, Double&gt; scorer : config.getScorers().entrySet()) { AbstractScorer&lt;P, F&gt; key = scorer.getKey(); double value = scorer.getValue(); if (!scoreSet.containsKey(key)) result = withScorer(key, value); else { scoreSet.put(key, value + scoreSet.get(key)); } } return result; } public ScoreConfigFactory&lt;P, F&gt; copy() { ScoreConfigFactory&lt;P, F&gt; newInstance = new ScoreConfigFactory&lt;P, F&gt;(); return newInstance.withScoreConfig(this.build()); } /** * Add a scorer to this factory * @param scorer Scorer to add * @return This factory */ public ScoreConfigFactory&lt;P, F&gt; withScorer(AbstractScorer&lt;P, F&gt; scorer) { scoreSet.put(scorer, 1.0); return this; } /** * Add a scorer with the specified weight to this factory. * @param scorer Scorer to add * @param weight Weight that should be applied to the scorer * @return This factory */ public ScoreConfigFactory&lt;P, F&gt; withScorer(AbstractScorer&lt;P, F&gt; scorer, double weight) { scoreSet.put(scorer, weight); return this; } /** * Multiply all current {@link AbstractScorer}s in this factory's {@link ScoreSet} weights by a factor * @param value Factor to multiply with * @return This factory */ public ScoreConfigFactory&lt;P, F&gt; multiplyAll(double value) { ScoreSet&lt;P, F&gt; oldScoreSet = scoreSet; scoreSet = new ScoreSet&lt;P, F&gt;(); for (Map.Entry&lt;AbstractScorer&lt;P, F&gt;, Double&gt; ee : oldScoreSet.entrySet()) { scoreSet.put(ee.getKey(), ee.getValue() * value); } return this; } /** * Add a {@link PostScorer} to this factory. * @param post PostScorer to add * @return This factory */ public ScoreConfigFactory&lt;P, F&gt; withPost(PostScorer&lt;P, F&gt; post) { postScorers.add(post); return this; } /** * Create a {@link ScoreConfig} from this factory. * @return A {@link ScoreConfig} for the {@link PreScorer}s, {@link PostScorer} and {@link AbstractScorer}s that has been added to this factory. */ public ScoreConfig&lt;P, F&gt; build() { return new ScoreConfig&lt;P, F&gt;(this.preScorers, this.postScorers, this.scoreSet); } /** * Add a {@link PreScorer} to this factory * @param analyzer PreScorer to add * @return This factory */ public ScoreConfigFactory&lt;P, F&gt; withPreScorer(PreScorer&lt;P&gt; analyzer) { this.preScorers.add(analyzer); return this; } } </code></pre> <p><strong>ScoreParameters.java:</strong> (24 lines, 627 bytes)</p> <pre><code>/** * Interface for retrieving analyzes and parameters that are used for scoring * @param &lt;P&gt; Score parameter type */ public interface ScoreParameters&lt;P&gt; { /** * @param clazz The class to get the analyze for * @return The analyze for the specified class, or null if none was found */ &lt;E&gt; E getAnalyze(Class&lt;E&gt; clazz); /** * @return Parameter object that are used in the scoring */ P getParameters(); /** * @return All available analyze objects */ Map&lt;Class&lt;?&gt;, Object&gt; getAnalyzes(); ScoreStrategy&lt;P, ?&gt; getScoreStrategy(); } </code></pre> <p><strong>Scorer.java:</strong> (6 lines, 178 bytes)</p> <pre><code>/** * Marker for classes that are a part of scoring things, i.e. {@link PostScorer} and {@link AbstractScorer}. */ public interface Scorer { } </code></pre> <p><strong>ScoreSet.java:</strong> (19 lines, 471 bytes)</p> <pre><code>/** * Map of {@link AbstractScorer}s and the weight that should be applied to them. * * @param &lt;P&gt; Score parameter type * @param &lt;F&gt; The type to apply scores to */ public class ScoreSet&lt;P, F&gt; extends LinkedHashMap&lt;AbstractScorer&lt;P, F&gt;, Double&gt; { private static final long serialVersionUID = 5924233965213820945L; ScoreSet() { } ScoreSet(ScoreSet&lt;P, F&gt; copy) { super(copy); } } </code></pre> <p><strong>ScoreStrategy.java:</strong> (24 lines, 964 bytes)</p> <pre><code>/** * Responsible for determining which fields to score with the specified params * @param &lt;P&gt; Score parameter type * @param &lt;F&gt; The type to apply scores to */ public interface ScoreStrategy&lt;P, F&gt; { /** * Determine the collection of fields to score given the specified params * @param params Parameter for the scoring * @return A collection of fields which to score */ Collection&lt;F&gt; getFieldsToScore(P params); /** * Determine whether or not scoring of a particular field should be done, allowing {@link PreScorer}s from the analyze to be taken into consideration. * @param parameters Parameters, including analyze objects created by {@link PreScorer}s. * @param field The field to score or not to score, that is the question. * @return True to score field, false to skip scoring of it. */ boolean canScoreField(ScoreParameters&lt;P&gt; parameters, F field); } </code></pre> <p><strong>ScoreTools.java:</strong> (50 lines, 1571 bytes)</p> <pre><code>/** * Contains methods for common use among scoring classes */ public class ScoreTools { /** * Normalize a value to the range 0..1 (inclusive) * @param value Value to normalize * @param min The minimum of all values * @param range The range of the values (max - min) * @return */ public static double normalized(double value, double min, double range) { if (range == 0.0) return 0; return ((value - min) / range); } public static &lt;K, V extends Comparable&lt;? super V&gt;&gt; SortedSet&lt;Map.Entry&lt;K, V&gt;&gt; entriesSortedByValues(Map&lt;K, V&gt; map, final boolean descending) { SortedSet&lt;Map.Entry&lt;K, V&gt;&gt; sortedEntries = new TreeSet&lt;Map.Entry&lt;K, V&gt;&gt;( new Comparator&lt;Map.Entry&lt;K, V&gt;&gt;() { @Override public int compare(Map.Entry&lt;K, V&gt; e1, Map.Entry&lt;K, V&gt; e2) { int res; if (descending) res = e1.getValue().compareTo(e2.getValue()); else res = e2.getValue().compareTo(e1.getValue()); return res != 0 ? -res : 1; // Special fix to preserve items with equal values } } ); sortedEntries.addAll(map.entrySet()); return sortedEntries; } private static Random staticRandom = new Random(); public static &lt;E&gt; E getRandom(List&lt;E&gt; list, Random random) { if (list.isEmpty()) return null; if (random == null) random = staticRandom; return list.get(random.nextInt(list.size())); } } </code></pre> <h1>Usage / Test</h1> <p>An example of how this code can be used is included on GitHub. See the <code>test.net.zomis.aiscores.ttt.TTMain</code> class for an example of how to use this system in a simple Tic-Tac-Toe game.</p> <p>You can also see the system in action in my <a href="http://www.zomis.net/ttt/TTTWeb.html?highlight&amp;autolight" rel="nofollow noreferrer">TicTacToe Ultimate application</a>. The numbers and colors on the fields show how good the field is according to the scoring that has been applied (green is good, and high numbers is good).</p> <h1>Questions</h1> <p>I'd like to know how well-implemented this code is and how well it is designed. I'd also like to know if there's a cleaner way to solve the getAnalyze-business, as there needs to be a "many-to-many" relationship between an analyze and the scorers.</p> <p>I am not <em>primarily</em> looking for comments about my formatting and naming, I'm quite happy with those. I am using Java 6 because I need to support Android. I also need to support GWT which makes <code>String.format</code> impossible.</p> <p>Besides just being able to make decisions for bots, it is also possible to use with <a href="http://en.wikipedia.org/wiki/Genetic_algorithm" rel="nofollow noreferrer">Genetic Algorithms</a> and it's possible to apply score to the way another player plays and from this determining how similar a player plays to the AI. I also have some ideas for how to use this system in the future.</p> <p>There are more code related to this system (for example, a method to analyze + score + return the field(s) that gets the highest score) available on GitHub, but it is not intended to be reviewed (if you want to review it, let me know and I'll post a question about it).</p> <p>A related questions about the system itself is available at <a href="https://cs.stackexchange.com/questions/21981/a-scoring-approach-to-computer-opponents-that-needs-balancing">the Computer Science Stack Exchange site</a>.</p>
[]
[ { "body": "<h3>AbstractScorer</h3>\n\n<ul>\n<li><p>Are you sure you need the precision of double for scoring? I only ask because I recently had reason to down-convert a system to float because it had many millions of scorable items and the memory saving ended up being significant.</p></li>\n<li><p><code>toString()</code> It is best practice to put a toString on each and every class you implement. The toString method is there to communicate with yourself (when debugging) and other programmers who unfortunately may need to devour your stack traces. There is no benefit in having a toString on an abstract class. Your toString, giving just the class's simple name, is even worst than the default <code>Object.toString()</code></p></li>\n</ul>\n\n<h3>FieldScore</h3>\n\n<ul>\n<li>This is an accumulator for the score attached to a field. It could potentially contain multiple scores. I am disappointed that it is not thread-safe. First impression is that it would be a useful optimization to have the fields all scored by different scorers at the same time. This would not be possible with the current <code>FieldScore</code>.</li>\n</ul>\n\n<h3>FieldScoreProducer</h3>\n\n<ul>\n<li><p>Some documentation here would be nice. I am not certain 'producer' is the way I would describe the class, but then I am not sure what I would recommend instead.</p></li>\n<li><p>The <code>analyze()</code> method has Generics with <code>Object</code> type. This should be resolved with an additional Generic type on the class. Object is a poor declaration, and it indicates a lack of structure.</p></li>\n<li><p><code>detailed</code> is odd. I can't see why it is not a final field. The <code>setDetailed</code> should be replaced with a flag on the constructor.</p></li>\n</ul>\n\n<h3>FieldScores</h3>\n\n<ul>\n<li><p>It is customary to put the Constructors before the methods of the class... (and after static declarations and methods). You have some regular methods before the Constructor.</p></li>\n<li><p><code>private final Map&lt;F, FieldScore&lt;F&gt;&gt; scores</code> is a problem. The key of the map is of type <code>F</code>, but there is no indication as to what that <code>F</code> class is. As a result, you have no idea of whether <code>F</code> implements <code>hashCode()</code> and <code>equals()</code> in a way that is compatible with the Map contract. I would recommend that you declare that class as an <code>IdentityHashMap</code> just in case.</p></li>\n</ul>\n\n<p>-<code>detailed</code> I don't like that it is not final. Also, you have a <code>setDetailed()</code> method but no <code>isDetailed()</code>. It should be set as part of the constructor as a final.</p>\n\n<ul>\n<li><p>you have the word <code>analyzes</code> in various forms throughout the code. I think the right word is <code>analyzers</code>.</p></li>\n<li><p><code>getAnalyzes()</code> should wrap the return value in the more lightweight <code>Collections.unmodifiableMap(....)</code> rather than creating a new <code>HashMap</code></p></li>\n<li><p><code>getScores()</code> ditto</p></li>\n</ul>\n\n<h3>PostScorer</h3>\n\n<ul>\n<li>again with the <code>toString()</code> on an abstract class.</li>\n</ul>\n\n<h3>PreScorer</h3>\n\n<ul>\n<li><p><code>PostScorer is an abstract class, but</code>PreScorer` is an interface. I would expect them to be mirrors of each other, but they are not.</p></li>\n<li><p>The method <code>onScoringComplete</code> should be something like <code>onPreScoringComplete</code>, right?</p></li>\n<li><p>Analyze should be returning some generic type, not <code>Object</code>.</p></li>\n<li><p>I would expect the methods on <code>PreScorer</code> and <code>PostScorer</code> to be similar to each other, but they are not... at all.</p></li>\n<li><p>Again, I would expect a more complicated <code>&lt;P, F&gt;</code> signature on the <code>PreScorer</code>... without it, is it doing something wrong?</p></li>\n</ul>\n\n<h3>ScoreConfig</h3>\n\n<ul>\n<li>In all other methods you have been careful to return copies of the stored structures, but in this class you return the basic values. Should the methods use <code>Collections.unmodifiableMap(....)</code> or <code>new HashMap(....)</code> instead?</li>\n</ul>\n\n<h3>ScoreConfigFactory</h3>\n\n<ul>\n<li>Why have a factory class and method if the constructors are public anyway?</li>\n</ul>\n\n<h3>ScoreSet</h3>\n\n<ul>\n<li><p>Since when does this make sense?</p>\n\n<blockquote>\n<pre><code>public class ScoreSet&lt;P, F&gt; extends LinkedHashMap&lt;AbstractScorer&lt;P, F&gt;, Double&gt;\n</code></pre>\n</blockquote>\n\n<p>???? ;-)</p></li>\n</ul>\n\n<h3>ScoreTools</h3>\n\n<ul>\n<li><p>The method <code>entriesSortedByValues</code> creates an anonymous Comparator. Comparators are thread-safe and re-entran, and, as a result, it is just a waste of time to create one each time the method is called. Something like:</p>\n\n<pre><code>private static final ASCENDING_VALUE_COMPARATOR = new Comparator&lt;Map.Entry&lt;K, V&gt;&gt;() {\n @Override\n public int compare(Map.Entry&lt;K, V&gt; e1, Map.Entry&lt;K, V&gt; e2) {\n int res;\n e1.getValue().compareTo(e2.getValue());\n else res = e2.getValue().compareTo(e1.getValue());\n return res != 0 ? -res : 1; // Special fix to preserve items with equal values\n }\n}\n</code></pre></li>\n<li><p>While in the process of doing that last one above, it appeared to me that the comparators are the wrong way around in there:</p>\n\n<blockquote>\n<pre><code>if (descending) res = e1.getValue().compareTo(e2.getValue());\nelse res = e2.getValue().compareTo(e1.getValue());\n</code></pre>\n</blockquote></li>\n<li><p>This line is highly suspicious... <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html#compare%28T,%20T%29\" rel=\"nofollow noreferrer\">this makes the comparator non-transitive</a>. With a comparator, <code>compare(a, b)</code> should be the same sign as <code>-compare(b,a)</code>, but, in your case, if <code>a.equals(b)</code>, then your code will return 1 in both cases.</p>\n\n<blockquote>\n<pre><code>return res != 0 ? -res : 1; // Special fix to preserve items with equal values\n</code></pre>\n</blockquote>\n\n<p>Your code will likely fail with <a href=\"https://stackoverflow.com/a/11441813/1305253\">“Comparison method violates its general contract!”</a></p></li>\n<li><p><code>getRandom</code> again makes it hard to move to mult-threaded. Consider using <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadLocalRandom.html\" rel=\"nofollow noreferrer\"><code>java.util.concurrent.ThreadLocalRandom</code></a></p></li>\n</ul>\n\n<h2>Conclusion</h2>\n\n<p>Currently it appears that is works, but there is some missing details when it comes to being a multi-threaded application. I see a number of benefits in that direction.</p>\n\n<p>The code is good, and hangs together 'quite well. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-29T06:15:50.140", "Id": "180360", "Score": "0", "body": "I disagree with proposing `IdentityHashMap`. Either the key implements `equals` correctly and then normal `HashMap` is fine. Or they inherit `Object::equals` and then `HashMap` works like `IdentityHashMap` and that's also fine, since omitting `equals` is like saying that the default is fine. Or it's broken or that's a different story. +++ IMHO `IdentityHashMap` should be used only when you *really want to ignore* potentially existing `equals`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T04:06:42.770", "Id": "45366", "ParentId": "45088", "Score": "13" } }, { "body": "<p>I was started to review the code a few days ago and it seems that <em>rolfl</em> was faster. Anyway, some other thoughts including things which are in the github repository.</p>\n\n<ol>\n<li><p>Build system: It took a while to load the project into Eclipse. There is no <code>.project</code> file nor <code>pom.xml</code> for Maven nor anything else. I suggest you using a build tool, Maven and Gradle are quite popular nowadays. It would help other developers a lot as it could start the application for them (or at least create a jar which can be started an usual <code>java -jar</code> command.)</p></li>\n<li><p>It was confusing that the <code>test</code> directory contains examples. I would expect unit test there. See also: <a href=\"https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html\">Maven's Standard Directory Layout</a> - a lot of developers familiar with that.</p></li>\n<li><p><code>AbstractScorer</code> could be an interface. Just for a <code>toString</code> and a simple method which <code>return true</code> is rather an abuse of inheritance.</p></li>\n<li><p>I'd consider a <code>null</code> check here:</p>\n\n<blockquote>\n<pre><code>public FieldScore(final F field, final boolean detailed) {\n this.field = field;\n</code></pre>\n</blockquote></li>\n<li><p><code>FieldScores.detailed</code>: I would consider moving this responsibility to another class (probably with a decorator pattern). The flag arguments smells a little bit:</p>\n\n<p><em>Clean Code</em> by <em>Robert C. Martin</em>, Flag Arguments, p41:</p>\n\n<blockquote>\n <p>Flag arguments are ugly. Passing a boolean into a function is a \n truly terrible practice. It immediately complicates the signature \n of the method, loudly proclaiming that this function does more than\n one thing. It does one thing if the flag is true and another if the \n flag is false!</p>\n</blockquote></li>\n<li><p>This reminds me temporal coupling:</p>\n\n<blockquote>\n<pre><code>FieldScores&lt;P, F&gt; scores = new FieldScores&lt;P, F&gt;(params, config, scoreStrategy);\nscores.setAnalyzes(analyzes);\nscores.determineActiveScorers();\nscores.calculateScores();\nscores.rankScores();\nscores.postHandle();\n</code></pre>\n</blockquote>\n\n<p><em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G31: Hidden Temporal Couplings</em></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T17:44:02.687", "Id": "79418", "Score": "1", "body": "What do you suggest the `test` directory should be called instead? Would `examples` be a better name?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T17:44:39.513", "Id": "79419", "Score": "1", "body": "Many thanks for your review, I will take your comments into consideration! *ashamed that I forgot to add `.project` to git*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T18:25:35.707", "Id": "79423", "Score": "0", "body": "@SimonAndréForsberg: Yes, I'd go with `examples`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T17:32:41.727", "Id": "45528", "ParentId": "45088", "Score": "9" } }, { "body": "<p>For now, I comment on one part only, which is IMHO dangerous enough to deserve it:</p>\n<h2>ScoreTools</h2>\n<pre><code>public static &lt;K, V extends Comparable&lt;? super V&gt;&gt; SortedSet&lt;Map.Entry&lt;K, V&gt;&gt; entriesSortedByValues(Map&lt;K, V&gt; map, final boolean descending) {\n SortedSet&lt;Map.Entry&lt;K, V&gt;&gt; sortedEntries = new TreeSet&lt;Map.Entry&lt;K, V&gt;&gt;(\n new Comparator&lt;Map.Entry&lt;K, V&gt;&gt;() {\n @Override\n public int compare(Map.Entry&lt;K, V&gt; e1, Map.Entry&lt;K, V&gt; e2) {\n int res;\n if (descending) res = e1.getValue().compareTo(e2.getValue());\n else res = e2.getValue().compareTo(e1.getValue());\n return res != 0 ? -res : 1; // Special fix to preserve items with equal values\n }\n }\n );\n sortedEntries.addAll(map.entrySet());\n return sortedEntries;\n}\n</code></pre>\n<p>Your special fix can easily lead to a map unable to find anything. As rolfl already noted, your <code>Comparator</code> is non-transitive. But it's not antisymmetric and it's not reflexive either. So you're violating every single point of the contract.</p>\n<p>Assuming it works now, it can break anytime. Without <code>e.compare(e)</code> returning non zero, there's no way to find an entry, except by using <code>==</code>, which is an optimization probably included in the current <code>TreeMap</code> version.</p>\n<p>When you want such a preserving <code>Comparator</code>, you can do better:</p>\n<pre><code>int res;\nif (descending) res = e1.getValue().compareTo(e2.getValue());\nelse res = e2.getValue().compareTo(e1.getValue());\nif (res != 0 || e1.equals(e2)) {\n return res;\n}\n</code></pre>\n<p>This ensures reflexivity. Now, we don't care about the result, but need something like transitivity and antisymmetry. We use what we have</p>\n<pre><code>res = Integer.compare(e1.getKey().hashCode(), e2.getKey().hashCode());\nif (res != 0 || e1.equals(e2)) {\n return res;\n}\n</code></pre>\n<p>The chances we come that far are low, but non-zero.</p>\n<pre><code>res = Integer.compare(e1.getValue().hashCode(), e2.getValue().hashCode());\nif (res != 0 || e1.equals(e2)) {\n return res;\n}\n</code></pre>\n<p>Now, we have nothing more to compare. Bad luck. You could decide that it's improbable enough and losing some entries is allowed. You could use your ugly hack now. You could also go the hard route like</p>\n<pre><code>if (!uniqueIdMap.contains(e1)) {\n uniqueIdMap.put(e1, uniqueIdMap.size());\n}\nif (!uniqueIdMap.contains(e2)) {\n uniqueIdMap.put(e2, uniqueIdMap.size());\n}\nreturn uniqueIdMap.get(e1) - uniqueIdMap.get(e2);\n</code></pre>\n<p>using a</p>\n<pre><code>private Map&lt;Map.Entry&lt;K, V&gt;, Integer&gt; uniqueIdMap;\n</code></pre>\n<p>You don't need to be concerned with performance here, as the chances of double hash collision are pretty low. You may want to use a <code>WeakHashMap</code> to avoid memory leaks or <code>ConcurentHashMap</code> with <code>putIfAbsent</code>. You may want to create it lazily as chances it gets needed are low.</p>\n<p>In case your objects don't care about <code>equals</code>, you can use <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Ordering.html#arbitrary()\" rel=\"nofollow noreferrer\">Guava <code>Ordering#arbitrary</code></a> which is such a tie-breaker (and replaces all my lengthy code above).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-29T07:07:01.160", "Id": "98430", "ParentId": "45088", "Score": "2" } } ]
{ "AcceptedAnswerId": "45366", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T15:31:53.533", "Id": "45088", "Score": "26", "Tags": [ "java", "game", "ai" ], "Title": "A scoring approach to computer opponents" }
45088
<p>Can I get some pointers, critiques and/or comments on the following model? (p.s. performance seems great... tested all methods up to 10,000 records)</p> <pre><code>&lt;?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class o7th_Model extends CI_Model { private $msg; private $last_id; private $full_qry_count; public function __construct(){ parent::__construct(); $this-&gt;load-&gt;database(); $this-&gt;load-&gt;library('form_validation'); $this-&gt;load-&gt;library('pagination'); } // Setup a list assoc array to return /* * USAGE - the only array parameter required is the 'table_name' self::qlist(array('select'=&gt;'FIELDS', --- should be a comma seperate string of field names 'where'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need 'or_where'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need 'where_in'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array 'or_where_in'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array 'where_not_in'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array 'or_where_not_in'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array 'like'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE', 'wildcard'=&gt;'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional 'or_like'array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE', 'wildcard'=&gt;'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional 'not_like'array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE', 'wildcard'=&gt;'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional 'or_not_like'array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE', 'wildcard'=&gt;'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional 'group_by'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need 'distinct'=&gt;'TRUE/FALSE/NULL', --- TRUE enables SELECT DISTINCT, FALSE/NULL doesnt bother adding it 'having'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need 'or_having'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need 'order_by'=&gt;array(array('field'=&gt;'FIELD_NAME', 'direction'=&gt;'ASC/DESC'),), --- can have as many of these field/direction arrays as you need, direction is optional 'limit'=&gt;array(array('limit'=&gt;'NUMBER_TO_LIMIT_RESULTS', 'offset'=&gt;'NUMBER_TO_LIMIT_RESULTS')), 'join'=&gt;array(array('table'=&gt;'TABLE_NAME_TO_JOIN', 'on'=&gt;'EX: a.field1 = b.field2', 'direction'=&gt;'left/right/outer/inner/left outer/right outer'),), --- can have as many of these table/on/direction arrays as you need 'pagination'=&gt;array('per_page'=&gt;'', 'page_num'=&gt;''), --- do not use this with limit... you will get undesirable results 'table_name'=&gt;'TABLE_NAME')); --- REQUIRED!!! */ public function qlist(){ $tArgs = func_get_args(); $tbl = self::prepArgs(1, $tArgs); $qry = $this-&gt;db-&gt;get($tbl); if($qry){ $rs = $qry-&gt;result_array(); $this-&gt;full_qry_count = count($rs); if(array_key_exists('pagination', $tArgs[0])){ $rs = array_slice($rs, $tArgs[0]['pagination']['page_num'], $tArgs[0]['pagination']['per_page']); } }else{ $rs = null; } return $rs; } // setup a return assoc array details record, only returns 1 record /* * USAGE - the only array parameter required is the 'table_name' self::qdetails(array('select'=&gt;'FIELDS', --- should be a comma seperate string of field names 'where'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need 'or_where'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need 'where_in'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array 'or_where_in'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array 'where_not_in'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array 'or_where_not_in'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array 'like'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE', 'wildcard'=&gt;'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional 'or_like'array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE', 'wildcard'=&gt;'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional 'not_like'array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE', 'wildcard'=&gt;'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional 'or_not_like'array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE', 'wildcard'=&gt;'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional 'group_by'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need 'distinct'=&gt;'TRUE/FALSE/NULL', --- TRUE enables SELECT DISTINCT, FALSE/NULL doesnt bother adding it 'having'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need 'or_having'=&gt;array(array('field'=&gt;'FIELD_NAME', 'value'=&gt;'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need 'order_by'=&gt;array(array('field'=&gt;'FIELD_NAME', 'direction'=&gt;'ASC/DESC'),), --- can have as many of these field/direction arrays as you need, direction is optional 'limit'=&gt;array(array('limit'=&gt;'NUMBER_TO_LIMIT_RESULTS', 'offset'=&gt;'NUMBER_TO_LIMIT_RESULTS')), 'join'=&gt;array(array('table'=&gt;'TABLE_NAME_TO_JOIN', 'on'=&gt;'EX: a.field1 = b.field2', 'direction'=&gt;'left/right/outer/inner/left outer/right outer'),), --- can have as many of these table/on/direction arrays as you need 'table_name'=&gt;'TABLE_NAME')); --- REQUIRED!!! */ public function qdetails(){ $tbl = self::prepArgs(1, func_get_args()); $qry = $this-&gt;db-&gt;get($tbl); return ($qry) ? $qry-&gt;row_array() : null; } public function qinsert(){ return self::prepArgs(2, func_get_args()); } public function qedit(){ return self::prepArgs(3, func_get_args()); } // setup db delete, return BOOLEAN public function qdelete(){ $tbl = self::prepArgs(4, func_get_args()); $this-&gt;db-&gt;delete('Storage_Users'); if($this-&gt;db-&gt;affected_rows() &gt; 0){ return TRUE; }else{ $this-&gt;msg = 'There was an issue removing that record.&lt;br /&gt;' . $this-&gt;db-&gt;_error_message(); return FALSE; } } // get the last inserted id - only valid on inserts public function last_insert_id(){ return $this-&gt;last_id; } // return a message if any of the returns above are invalid/false/errored out public function message(){ return $this-&gt;msg; } // return a number of records based on the query run/ only valid on the selects public function fullrecordcount(){ return $this-&gt;full_qry_count; } // return the pagination links public function paginator($base_url, $per_page, $total_rows, $num_links, $uri_segment, $aclass = null){ $config['base_url'] = $base_url; $config['per_page'] = $per_page; $config['total_rows'] = $total_rows; $config['num_links'] = $num_links; $config['first_link'] = '&lt;span class="fa fa-angle-double-left page_num"&gt;&lt;/span&gt;'; $config['last_link'] = '&lt;span class="fa fa-angle-double-right page_num"&gt;&lt;/span&gt;'; $config['cur_tag_open'] = '&lt;span class="page_num bold"&gt;'; $config['cur_tag_close'] = '&lt;/span&gt;'; $config['next_link'] = '&lt;span class="fa fa-angle-right page_num"&gt;&lt;/span&gt;'; $config['prev_link'] = '&lt;span class="fa fa-angle-left page_num"&gt;&lt;/span&gt;'; $config['uri_segment'] = $uri_segment; $config['num_tag_open'] = '&lt;span class="page_num"&gt;'; $config['num_tag_close'] = '&lt;/span&gt;'; if($aclass != null){ $config['anchor_class'] = 'class="' . $aclass . '" '; } $this-&gt;pagination-&gt;initialize($config); return $this-&gt;pagination-&gt;create_links(); } // setup all possible arguments for all of the above, return name of the table from the arguments private function prepArgs($which, $args){ if($args){ try{ switch($which){ case 1: // select return self::setupSelect($args); break; case 2: // insert return self::setupInsert($args); break; case 3: // update return self::setupEdit($args); break; case 4: // delete return self::setupDelete($args); break; } }catch(Exception $ex){ $this-&gt;$msg .= $ex-&gt;getMessage(); } }else{ $this-&gt;$msg .= 'You have not passed in any arguments to your query, please have a look over your code.'; } } // setup our edit private function setupEdit($args){ // where clause(s) if(array_key_exists('where', $args[0])){ $w = $args[0]['where']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;where($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // or_where clause(s) if(array_key_exists('or_where', $args[0])){ $w = $args[0]['or_where']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;or_where($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // where_in clause(s) if(array_key_exists('where_in', $args[0])){ $w = $args[0]['where_in']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;where_in($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // or_where_in clause(s) if(array_key_exists('or_where_in', $args[0])){ $w = $args[0]['or_where_in']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;or_where_in($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // where_not_in clause(s) if(array_key_exists('where_not_in', $args[0])){ $w = $args[0]['where_not_in']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;where_not_in($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // or_where_not_in clause(s) if(array_key_exists('or_where_not_in', $args[0])){ $w = $args[0]['or_where_not_in']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;or_where_not_in($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // like clause(s) if(array_key_exists('like', $args[0])){ $l = $args[0]['like']; $lCt = count($l); for($ll = 0; $ll &lt; $lCt; ++$ll){ if($l[$ll]['value']){ $this-&gt;db-&gt;like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null); } } unset($l); } // or_like clause(s) if(array_key_exists('or_like', $args[0])){ $l = $args[0]['or_like']; $lCt = count($l); for($ll = 0; $ll &lt; $lCt; ++$ll){ if($l[$ll]['value']){ $this-&gt;db-&gt;or_like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null); } } unset($l); } // not_like clause(s) if(array_key_exists('not_like', $args[0])){ $l = $args[0]['not_like']; $lCt = count($l); for($ll = 0; $ll &lt; $lCt; ++$ll){ if($l[$ll]['value']){ $this-&gt;db-&gt;not_like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null); } } unset($l); } // or_not_like clause(s) if(array_key_exists('or_not_like', $args[0])){ $l = $args[0]['or_not_like']; $lCt = count($l); for($ll = 0; $ll &lt; $lCt; ++$ll){ if($l[$ll]['value']){ $this-&gt;db-&gt;or_not_like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null); } } unset($l); } // group_by clause(s) if(array_key_exists('group_by', $args[0])){ $g = $args[0]['group_by']; $gCt = count($g); for($gg = 0; $gg &lt; $gCt; ++$gg){ if($g[$gg]['value']){ $this-&gt;db-&gt;group_by($g[$gg]['field'], $g[$gg]['value']); } } unset($g); } // having clause(s) if(array_key_exists('having', $args[0])){ $h = $args[0]['having']; $hCt = count($h); for($hh = 0; $hh &lt; $hCt; ++$hh){ if($h[$hh]['value']){ $this-&gt;db-&gt;having($h[$hh]['field'], $h[$hh]['value']); } } unset($h); } // or_having clause(s) if(array_key_exists('or_having', $args[0])){ $h = $args[0]['or_having']; $hCt = count($h); for($hh = 0; $hh &lt; $hCt; ++$hh){ if($h[$hh]['value']){ $this-&gt;db-&gt;or_having($h[$hh]['field'], $h[$hh]['value']); } } unset($h); } // join clause(s) if(array_key_exists('join', $args[0])){ $j = $args[0]['join']; $jCt = count($j); for($jj = 0; $jj &lt; $jCt; ++$jj){ $this-&gt;db-&gt;join($j[$jj]['table'], $j[$jj]['on'], $j[$jj]['direction']); } unset($j); } $data = array(); $tname = ''; $valid = TRUE; // array of data to insert: required if(array_key_exists('update', $args[0])){ $data = $args[0]['update']; }else{ $valid = FALSE; $this-&gt;$msg .= 'You need to specify field/value pairs of data to update.'; } // table name: required if(array_key_exists('table_name', $args[0])){ $tname = $args[0]['table_name']; }else{ $valid = FALSE; $this-&gt;$msg .= 'You need to specify a table name to update.'; } // setup our validations if(array_key_exists('validations', $args[0])){ $v = $args[0]['validations']; $vCt = count($v); for($vv = 0; $vv &lt; $vCt; ++$vv){ $this-&gt;form_validation-&gt;set_rules($v[$vv]['field'], $v[$vv]['label'], $v[$vv]['validation']); } if ($this-&gt;form_validation-&gt;run() === FALSE){ $valid = FALSE; $this-&gt;$msg .= validation_errors(); } } if($valid){ $this-&gt;db-&gt;update($tname, $data); $a = ($this-&gt;db-&gt;affected_rows() &gt; 0); if(!$a){ $this-&gt;$msg .= $this-&gt;db-&gt;_error_message(); return FALSE; }else{ return TRUE; } }else{ return $valid; } } // setup our delete private function setupDelete($args){ // where clause(s) if(array_key_exists('where', $args[0])){ $w = $args[0]['where']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;where($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // or_where clause(s) if(array_key_exists('or_where', $args[0])){ $w = $args[0]['or_where']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;or_where($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // where_in clause(s) if(array_key_exists('where_in', $args[0])){ $w = $args[0]['where_in']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;where_in($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // or_where_in clause(s) if(array_key_exists('or_where_in', $args[0])){ $w = $args[0]['or_where_in']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;or_where_in($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // where_not_in clause(s) if(array_key_exists('where_not_in', $args[0])){ $w = $args[0]['where_not_in']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;where_not_in($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // or_where_not_in clause(s) if(array_key_exists('or_where_not_in', $args[0])){ $w = $args[0]['or_where_not_in']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;or_where_not_in($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // like clause(s) if(array_key_exists('like', $args[0])){ $l = $args[0]['like']; $lCt = count($l); for($ll = 0; $ll &lt; $lCt; ++$ll){ if($l[$ll]['value']){ $this-&gt;db-&gt;like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null); } } unset($l); } // or_like clause(s) if(array_key_exists('or_like', $args[0])){ $l = $args[0]['or_like']; $lCt = count($l); for($ll = 0; $ll &lt; $lCt; ++$ll){ if($l[$ll]['value']){ $this-&gt;db-&gt;or_like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null); } } unset($l); } // not_like clause(s) if(array_key_exists('not_like', $args[0])){ $l = $args[0]['not_like']; $lCt = count($l); for($ll = 0; $ll &lt; $lCt; ++$ll){ if($l[$ll]['value']){ $this-&gt;db-&gt;not_like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null); } } unset($l); } // or_not_like clause(s) if(array_key_exists('or_not_like', $args[0])){ $l = $args[0]['or_not_like']; $lCt = count($l); for($ll = 0; $ll &lt; $lCt; ++$ll){ if($l[$ll]['value']){ $this-&gt;db-&gt;or_not_like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null); } } unset($l); } // group_by clause(s) if(array_key_exists('group_by', $args[0])){ $g = $args[0]['group_by']; $gCt = count($g); for($gg = 0; $gg &lt; $gCt; ++$gg){ if($g[$gg]['value']){ $this-&gt;db-&gt;group_by($g[$gg]['field'], $g[$gg]['value']); } } unset($g); } // having clause(s) if(array_key_exists('having', $args[0])){ $h = $args[0]['having']; $hCt = count($h); for($hh = 0; $hh &lt; $hCt; ++$hh){ if($h[$hh]['value']){ $this-&gt;db-&gt;having($h[$hh]['field'], $h[$hh]['value']); } } unset($h); } // or_having clause(s) if(array_key_exists('or_having', $args[0])){ $h = $args[0]['or_having']; $hCt = count($h); for($hh = 0; $hh &lt; $hCt; ++$hh){ if($h[$hh]['value']){ $this-&gt;db-&gt;or_having($h[$hh]['field'], $h[$hh]['value']); } } unset($h); } // join clause(s) if(array_key_exists('join', $args[0])){ $j = $args[0]['join']; $jCt = count($j); for($jj = 0; $jj &lt; $jCt; ++$jj){ $this-&gt;db-&gt;join($j[$jj]['table'], $j[$jj]['on'], $j[$jj]['direction']); } unset($j); } // table name: required if(array_key_exists('table_name', $args[0])){ return $args[0]['table_name']; } } // setup(and run) our insert private function setupInsert($args){ $data = array(); $tname = ''; $valid = TRUE; // array of data to insert: required if(array_key_exists('insert', $args[0])){ $data = $args[0]['insert']; }else{ $valid = FALSE; $this-&gt;$msg .= 'You need to specify field/value pairs of data to insert.'; } // table name: required if(array_key_exists('table_name', $args[0])){ $tname = $args[0]['table_name']; }else{ $valid = FALSE; $this-&gt;$msg .= 'You need to specify a table name to insert data into.'; } // setup our validations if(array_key_exists('validations', $args[0])){ $v = $args[0]['validations']; $vCt = count($v); for($vv = 0; $vv &lt; $vCt; ++$vv){ $this-&gt;form_validation-&gt;set_rules($v[$vv]['field'], $v[$vv]['label'], $v[$vv]['validation']); } if ($this-&gt;form_validation-&gt;run() === FALSE){ $valid = FALSE; $this-&gt;$msg .= validation_errors(); } } if($valid){ $this-&gt;db-&gt;insert($tname, $data); $a = ($this-&gt;db-&gt;affected_rows() &gt; 0); if(!$a){ $this-&gt;$msg .= $this-&gt;db-&gt;_error_message(); return FALSE; }else{ $this-&gt;last_id = $this-&gt;db-&gt;insert_id(); return TRUE; } }else{ return $valid; } } // setup our select private function setupSelect($args){ // select field names if(array_key_exists('select', $args[0])){ $this-&gt;db-&gt;select($args[0]['select']); } // where clause(s) if(array_key_exists('where', $args[0])){ $w = $args[0]['where']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;where($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // or_where clause(s) if(array_key_exists('or_where', $args[0])){ $w = $args[0]['or_where']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;or_where($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // where_in clause(s) if(array_key_exists('where_in', $args[0])){ $w = $args[0]['where_in']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;where_in($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // or_where_in clause(s) if(array_key_exists('or_where_in', $args[0])){ $w = $args[0]['or_where_in']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;or_where_in($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // where_not_in clause(s) if(array_key_exists('where_not_in', $args[0])){ $w = $args[0]['where_not_in']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;where_not_in($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // or_where_not_in clause(s) if(array_key_exists('or_where_not_in', $args[0])){ $w = $args[0]['or_where_not_in']; $wCt = count($w); for($ww = 0; $ww &lt; $wCt; ++$ww){ if($w[$ww]['value']){ $this-&gt;db-&gt;or_where_not_in($w[$ww]['field'], $w[$ww]['value']); } } unset($w); } // like clause(s) if(array_key_exists('like', $args[0])){ $l = $args[0]['like']; $lCt = count($l); for($ll = 0; $ll &lt; $lCt; ++$ll){ if($l[$ll]['value']){ $this-&gt;db-&gt;like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null); } } unset($l); } // or_like clause(s) if(array_key_exists('or_like', $args[0])){ $l = $args[0]['or_like']; $lCt = count($l); for($ll = 0; $ll &lt; $lCt; ++$ll){ if($l[$ll]['value']){ $this-&gt;db-&gt;or_like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null); } } unset($l); } // not_like clause(s) if(array_key_exists('not_like', $args[0])){ $l = $args[0]['not_like']; $lCt = count($l); for($ll = 0; $ll &lt; $lCt; ++$ll){ if($l[$ll]['value']){ $this-&gt;db-&gt;not_like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null); } } unset($l); } // or_not_like clause(s) if(array_key_exists('or_not_like', $args[0])){ $l = $args[0]['or_not_like']; $lCt = count($l); for($ll = 0; $ll &lt; $lCt; ++$ll){ if($l[$ll]['value']){ $this-&gt;db-&gt;or_not_like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null); } } unset($l); } // group_by clause(s) if(array_key_exists('group_by', $args[0])){ $g = $args[0]['group_by']; $gCt = count($g); for($gg = 0; $gg &lt; $gCt; ++$gg){ if($g[$gg]['value']){ $this-&gt;db-&gt;group_by($g[$gg]['field'], $g[$gg]['value']); } } unset($g); } // distinct flag if(array_key_exists('distinct', $args[0]) &amp;&amp; $args[0]['distinct'] === TRUE){ $this-&gt;db-&gt;distinct(); } // having clause(s) if(array_key_exists('having', $args[0])){ $h = $args[0]['having']; $hCt = count($h); for($hh = 0; $hh &lt; $hCt; ++$hh){ if($h[$hh]['value']){ $this-&gt;db-&gt;having($h[$hh]['field'], $h[$hh]['value']); } } unset($h); } // or_having clause(s) if(array_key_exists('or_having', $args[0])){ $h = $args[0]['or_having']; $hCt = count($h); for($hh = 0; $hh &lt; $hCt; ++$hh){ if($h[$hh]['value']){ $this-&gt;db-&gt;or_having($h[$hh]['field'], $h[$hh]['value']); } } unset($h); } // order_by clause(s) if(array_key_exists('order_by', $args[0])){ $o = $args[0]['order_by']; $oCt = count($o); for($oo = 0; $oo &lt; $oCt; ++$oo){ if($o[$oo]['direction']){ $this-&gt;db-&gt;order_by($o[$oo]['field'], $o[$oo]['direction']); }else{ $this-&gt;db-&gt;order_by($o[$oo]['field']); } } unset($o); } // join clause(s) if(array_key_exists('join', $args[0])){ $j = $args[0]['join']; $jCt = count($j); for($jj = 0; $jj &lt; $jCt; ++$jj){ $this-&gt;db-&gt;join($j[$jj]['table'], $j[$jj]['on'], $j[$jj]['direction']); } unset($j); } // limit if(array_key_exists('limit', $args[0])){ $this-&gt;db-&gt;limit($args[0]['limit']['limit'], $args[0]['limit']['offset']); } // table name: required if(array_key_exists('table_name', $args[0])){ return $args[0]['table_name']; } } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T18:50:09.397", "Id": "78815", "Score": "0", "body": "With that much code, could you add a description of what the code is doing ? It could help to know at first glance what your code is about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T19:01:41.013", "Id": "78817", "Score": "0", "body": "making a easier to use wrapper" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T15:07:57.643", "Id": "78956", "Score": "0", "body": "please do not edit code in a already answered question. If you want to include changes made after including answers, please add a new section or ask a new question. [more information and reasoning](http://meta.codereview.stackexchange.com/questions/1482/can-i-edit-my-own-question-to-include-suggested-changes-from-answers)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T14:26:13.863", "Id": "79169", "Score": "0", "body": "Please turn **on** notices and warnings (`error_reporting(-1)`), you're calling non-static methods statically all over the place. Don't. Also, if you want code to be reviewed, please follow the (coding-style conventions)[http://www.php-fig.org] your framework subscribes to. It makes the reviewer's life easier not having to get accustomed to your indentation-style. Oh, and 10,000 records is all fine and dandy, but I'd test my code up to 10,000,000 records before making _any_ assumptions as far as performance goes. I'd also use apache benchmark (`ab -c 100 -n 10000`)" } ]
[ { "body": "<p>This Function can be shorter.</p>\n<blockquote>\n<pre><code>public function qdelete(){\n $tbl = self::prepArgs(4, func_get_args());\n $this-&gt;db-&gt;delete('Storage_Users');\n if($this-&gt;db-&gt;affected_rows() &gt; 0){\n return TRUE;\n }else{\n $this-&gt;msg = 'There was an issue removing that record.&lt;br /&gt;' . $this-&gt;db-&gt;_error_message();\n return FALSE;\n }\n}\n</code></pre>\n</blockquote>\n<p>If you write it like this</p>\n<pre><code>public function qdelete(){\n $tbl = self::prepArgs(4, func_get_args());\n $this-&gt;db-&gt;delete('Storage_Users');\n if($this-&gt;db-&gt;affected_rows() &lt;= 0){\n $this-&gt;msg = 'There was an issue removing that record.&lt;br /&gt;' . $this-&gt;db-&gt;_error_message();\n return FALSE;\n }\n return TRUE;\n}\n</code></pre>\n<p>this probably just seems like a code golf, but this is really straight to the point, and doesn't clutter your code with else statements.</p>\n<hr />\n<p>This little bit of Code has some extra's in it that you don't need as well.</p>\n<blockquote>\n<pre><code> if($valid){\n $this-&gt;db-&gt;update($tname, $data);\n $a = ($this-&gt;db-&gt;affected_rows() &gt; 0);\n if(!$a){\n $this-&gt;$msg .= $this-&gt;db-&gt;_error_message();\n return FALSE;\n }else{\n return TRUE;\n }\n }else{\n return $valid; \n }\n</code></pre>\n</blockquote>\n<p>When you enter the outside if statement, it's valid then you have the nested if statement. if <code>!$a</code> then it will return a message otherwise it is true. you could just write it like this</p>\n<pre><code> if($valid){\n $this-&gt;db-&gt;update($tname, $data);\n if(!($this-&gt;db-&gt;affected_rows() &gt; 0)){\n $this-&gt;$msg .= $this-&gt;db-&gt;_error_message();\n return FALSE;\n }\n return TRUE;\n } else {\n return $valid;\n }\n</code></pre>\n<p>this way you don't have to declare an extra variable, the variable isn't used for anything else here and just uses resources in being declared.</p>\n<hr />\n<p><strong>Function <code>SetupEdits</code></strong></p>\n<p>ugh!</p>\n<p>what is <code>$w</code>? Why is <code>$w</code> <code>unset</code> inside the if statement, the scope should destroy it when focus leaves the if statement. if you did need to <code>unset</code> these variables then you should unset the others as well <code>$wCt</code></p>\n<p>It really looks to me like you need to break these if statements into separate functions, that function is just too big and ugly looking.</p>\n<p><em>talking about the <code>if then</code> statements in the functions</em></p>\n<p>I noticed that you use them over and over again. it kind of looks like you weren't sure how to structure the functions. like whether to put action stuff together or the components together. you can actually put the components together first, in a function, and then create the functions the way you have them with the other functions being called inside of them. it will make all of them look a lot cleaner, and probably reduce some of the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T22:25:32.237", "Id": "78845", "Score": "0", "body": "not only is the first point arguably bad advice, you also switched two lines so that you `return` before you can set `$this->msg`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T22:45:16.810", "Id": "78848", "Score": "0", "body": "you say arguably, do you mean that some would say it is bad where some would say it is good? or would everyone have mixed feelings? @amon" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T12:01:56.687", "Id": "78917", "Score": "0", "body": "Why break them up into seperate functions? Because of the re-use of some of them?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T12:35:56.993", "Id": "78921", "Score": "0", "body": "@o7thWebDesign, yes. I noticed that you use them over and over again. it kind of looks like you weren't sure how to structure the functions. like whether to put action stuff together or the components together. you can actually put the components together first, in a function, and then create the functions the way you have them with the other functions being called inside of them. it will make all of them look a lot cleaner, and probably reduce some of the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:36:41.683", "Id": "78948", "Score": "0", "body": "@Malachi `talking about the if then statements in the functions` not sure what you mean about the paragraph under this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:40:04.983", "Id": "78950", "Score": "0", "body": "you need to be able to nest functions. some of those if statements are used in multiple places to return the same information inside of a function. turn those into functions as well, and then you can use that function inside of the bigger function, in other words `encapsulation`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T22:11:58.760", "Id": "45262", "ParentId": "45090", "Score": "5" } }, { "body": "<p>By using a framework like CodeIgniter, which has a database abstraction layer, your application will benefit from model-view-controller separation and avoid SQL injection bugs. That automatically makes your application better than the average PHP code. That's a good start.</p>\n\n<hr>\n\n<p>I'll lead with a trivial observation first. In PHP library code, such as this file, <strong>omit the trailing <code>?&gt;</code>.</strong> Why? It's allowable to have the opening <code>&lt;?php</code> tag unmatched. It is easy to end up with a <kbd>Carriage return</kbd> and/or <kbd>Newline</kbd> at the end of the file, which the PHP interpreter will immediately print as output, since it's a templating language. Once the HTTP body starts, any subsequent code will not be able to manipulate HTTP headers: you can't issue cookies, set cache control headers, or set the HTTP status code without getting an error.</p>\n\n<p>The heart of your code appears to be <code>prepArgs($which, $args)</code>, which in turn calls <code>setupSelect($args)</code>, <code>setupInsert($args)</code>, <code>setupEdit($args)</code>, or <code>setupDelete($args)</code> based on the value of <code>$which</code>. The use of 1/2/3/4 for <code>$which</code> had me initially puzzled: why does <code>qdetails()</code> need to prep 1 argument, while <code>qinsert()</code> needs 2 arguments, and <code>qedit()</code> needs 3? Instead of magic numbers, please <strong><a href=\"http://php.net/define\" rel=\"nofollow\"><code>define()</code> some constants</a>.</strong></p>\n\n<p>The choice of <strong>the name <code>setupEdit()</code> is odd.</strong> <code>SELECT</code>, <code>INSERT</code>, and <code>DELETE</code> are all SQL commands; <code>EDIT</code> is not. I could understand if you consistently used \"application-layer\" terminology such as \"list\", \"add\", \"delete\", and \"edit\". However, given the names of the existing three other functions, it should just be <code>setupUpdate()</code>.</p>\n\n<p>The behaviour of <code>prepArgs(1, …)</code> and <code>prepArgs(4, …)</code> is <strong>inconsistent</strong> with <code>prepArgs(2, …)</code> and <code>prepArgs(3, …)</code>. With 1 and 4, it really just prepares the arguments, but does not call <code>$this-&gt;db-&gt;get()</code> or <code>$this-&gt;db-&gt;delete()</code>. With 2 and 3, it actually <em>does</em> call <code>$this-&gt;db-&gt;insert()</code> and <code>$this-&gt;db-&gt;update()</code>. That seems like a source of confusion and eventual bugs.</p>\n\n<p>The <code>paginator()</code> member and <code>$this-&gt;pagination</code> seem to be independent of everything else in the class. I think that <strong>paginating is a responsibility of the controller,</strong> not the model. The <code>$config</code> that you build in the <code>paginator()</code> method is definitely presentation-layer code, not database-layer code.</p>\n\n<hr>\n\n<p>What has me most concerned is that <strong>the bulk of <code>setupSelect()</code>, <code>setupEdit()</code>, and <code>setupDelete()</code> are identical repeated code.</strong> At a minimum, the common clauses <code>'where'</code>, <code>'or_where'</code>, <code>'where_in'</code>, <code>'or_where_in'</code>, <code>'where_not_in'</code>, <code>'or_where_not_in'</code>, <code>'like'</code>, <code>'or_like'</code>, <code>'not_like'</code>, <code>'or_not_like'</code>, <code>'group_by'</code>, <code>'having'</code>, <code>'or_having'</code>, and <code>'join'</code> should be in a private helper function that all of them call.</p>\n\n<p>Even <em>after</em> factoring out the common code into a helper function, it's <strong><em>still</em> a lot of almost-repeated code!</strong> Unfortunately, PHP does not let you call member methods of <code>$this-&gt;db</code> dynamically using reflection, so it probably can't be reduced much further.</p>\n\n<p>At this point, I have to ask: what do you gain for these 760 lines of code (including blank lines and comments)? Mostly, it seems to provide an alternate syntax for expressing your SQL clauses as arrays rather than sequential method calls. Perhaps you need that for your application, but at first glance, I'm skeptical of the cost-benefit balance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T12:16:07.087", "Id": "79868", "Score": "0", "body": "thank you for all this. I had already refactored most of it taking the commons out and into its own private helper. Im not real concerned with naming conventions ;) this wuld b alot differner in c# ;) for the most part the paging is in there for the limits on the queries. and the point of this is to prevent havin to type $this->db stuff fo every single model i may need to write out :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T06:09:10.480", "Id": "45730", "ParentId": "45090", "Score": "2" } } ]
{ "AcceptedAnswerId": "45262", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T15:54:30.650", "Id": "45090", "Score": "6", "Tags": [ "php", "php5", "codeigniter" ], "Title": "CodeIgniter Model I built" }
45090
<p>My design goal was to try and make a "clean" and well-designed Tic-Tac-Toe game but also to try and use concepts and programming constructs that I'm new to. </p> <p>I'm planning to implement an "AI Player" class later on. I know that Tic-Tac-Toe is a solved game so there are more effective approaches for AI logic but I've never programmed an AI before so my idea is to at runtime generate a "database" of all possible gamestates, and then have the AI rank each "intermediate gamestate" by the amount of positive outcomes (that is where the AI wins) - negative outcomes when it decides where to place its marker. Would this be a good idea and would it work at all?</p> <p>Both positive and negative feedback is welcome.</p> <p><strong>Game.cs</strong></p> <pre><code>public partial class Game : Form { #region Fields &amp; Properties internal static VisualCell[,] vGrid; internal static Player[] players; #endregion #region Constructors public Game() { InitializeComponent(); } #endregion #region Instanced Methods private void Game_Load(object sender, EventArgs e) { players = new Player[2]; players[0] = new Player(); // Set to human player or AI player players[1] = new Player(); // Always human GameRound.Complete += ShowCompletionDialog; GenerateGridBtns(); Task roundTask = Task.Factory.StartNew(() =&gt; new GameRound().Start()); } private void ShowCompletionDialog(OutcomeType gameOutcome) { long pID = (long)gameOutcome + 1; string WonText = "Player " + pID + " won!"; if (gameOutcome == OutcomeType.Draw) { //*HACK*: If the marker is empty it means that the passed player was a dummy and game was a draw WonText = "The game ended in a draw!"; } DialogResult dialogResult = MessageBox.Show("Play again?", WonText, MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { RestartGame(); // TODO: Add a bunch of resets here... } else if (dialogResult == DialogResult.No) { //do something else } } private void GenerateGridBtns() { vGrid = new VisualCell[3, 3]; for (int x = 0; x &lt; 3; x++) { for (int y = 0; y &lt; 3; y++) { vGrid[x, y] = new VisualCell() { AutoSize = true, Location = new Point(x*110, y*110), Size = new Size(124, 124), Enabled = false, Font = new Font(Font.FontFamily, 40), CellPos = new Tuple&lt;int,int&gt;(x, y) }; Controls.Add(vGrid[x, y]); } } } private void RestartGame() { for (int x = 0; x &lt; 3; x++) { for (int y = 0; y &lt; 3; y++) { vGrid[x, y].Invoke(new Action(() =&gt; vGrid[x, y].Text = String.Empty)); vGrid[x, y].Invoke(new Action(() =&gt; vGrid[x, y].Enabled = false)); } } var round = new GameRound(); Task roundTask = Task.Factory.StartNew(() =&gt; round.Start()); } #endregion } </code></pre> <p><strong>VCell.cs</strong></p> <pre><code>class VisualCell : Button { #region Fields &amp; Properties public Tuple&lt;int, int&gt; CellPos { get; set; } protected override bool ShowFocusCues { get { return false; } } #endregion #region Constructors public VisualCell(): base() { this.SetStyle(ControlStyles.Selectable, false); } #endregion } </code></pre> <p><strong>Cell.cs</strong></p> <pre><code>class Cell { #region Properties &amp; Fields private Mark markType = Mark.Empty; /* Have to use old way of defining properties here unfortunately due to lack of support for, default values in auto-implemented properties. */ public Mark MarkType { get { return markType; } set { //Only allow the type of the cell to change if it it's empty if (MarkType == Mark.Empty) { markType = value; } } } #endregion #region Constructors public Cell() { MarkType = Mark.Empty; } #endregion } </code></pre> <p><strong>Grid.cs</strong></p> <pre><code>enum OutcomeType { None = -1, CrossWin, NoughtWin, Draw } class Grid { const int MAX_CELLS = 3; #region Properties &amp; Fields public Cell[,] cells { get; set; } public OutcomeType Outcome { get; private set; } #endregion #region Constructors public Grid() { Outcome = OutcomeType.None; cells = new Cell[MAX_CELLS, MAX_CELLS]; for (int x = 0; x &lt; MAX_CELLS; x++) { for (int y = 0; y &lt; MAX_CELLS; y++) { cells[x, y] = new Cell(); } } } #endregion #region Instanced Methods public bool CheckOutcome(Tuple&lt;int, int&gt; coords, Player player) { //Check for draws first if (cells.GetEmptyCells().Length == 0) { Outcome = OutcomeType.Draw; return true; } //Now check for player wins var corners = new Tuple&lt;int, int&gt;[] { Tuple.Create(0,0), Tuple.Create(2,0), Tuple.Create(0,2), Tuple.Create(2,2) }; var sides = new Tuple&lt;int, int&gt;[] { Tuple.Create(1,0), Tuple.Create(0,1), Tuple.Create(1,2), Tuple.Create(2,1) }; var middle = new Tuple&lt;int, int&gt;(1,1); var checkDiagonals = false; //If the cell is at the corner or the middle we have to check for diagonal wins too if (corners.Any(e =&gt; e.Equals(coords)) || middle.Equals(coords)) { checkDiagonals = true; } if (player.PlayerWon(cells[coords.Item1, coords.Item2], this, checkDiagonals)) { switch (player.marker) { case Mark.Cross: Outcome = OutcomeType.CrossWin; break; case Mark.Nought: Outcome = OutcomeType.NoughtWin; break; } return true; } //If execution reaches this point then no one has won, return false return false; } #endregion } </code></pre> <p><strong>Player.cs</strong></p> <pre><code>class Player { #region Fields &amp; Properties private static int ctr; private static Game form; public Mark marker; public readonly int ID; public int Score { get; set; } #endregion #region Constructors public Player() { ID = ctr++; if (ID == 0) { // X is the starting player marker = Mark.Cross; } else { marker = Mark.Nought; } } #endregion #region Instanced Methods public virtual Tuple&lt;int, int&gt; GetPlayerChoice(Grid grid, Player player) // Virtual because we want the option to override this for AIPlayer later. { var pMark = (player.ID == 0) ? "X" : "O"; var choice = new Tuple&lt;int,int&gt;(-1, -1); var waitBtns = new List&lt;Task&gt;() { new Task(() =&gt; new SpinWait().SpinOnce()) }; //Enable eligble buttons for player for (int x = 0; x &lt; grid.cells.GetLength(0); x++) { for (int y = 0; y &lt; grid.cells.GetLength(1); y++) { if (grid.cells[x, y].MarkType == Mark.Empty) { Game.vGrid[x, y].Invoke(new Action(() =&gt; Game.vGrid[x, y].Enabled = true)); Game.vGrid[x, y].Click += new EventHandler( (a,b) =&gt; { var pos = new Tuple&lt;int,int&gt;((a as VisualCell).CellPos.Item1, (a as VisualCell).CellPos.Item2); choice = Tuple.Create(pos.Item1, pos.Item2); Game.vGrid[pos.Item1, pos.Item2].Invoke(new Action(() =&gt; Game.vGrid[pos.Item1, pos.Item2].Text = pMark)); Game.vGrid[pos.Item1, pos.Item2].Invoke(new Action(() =&gt; Game.vGrid[pos.Item1, pos.Item2].Enabled = false)); waitBtns.Add(new Task(() =&gt; new SpinWait().SpinOnce())); waitBtns[waitBtns.FindIndex(t =&gt; t.Status == TaskStatus.Created)].Start(); }); } } } Task.WaitAny(waitBtns.ToArray()); return choice; } public bool PlayerWon(Cell cell, Grid grid, bool checkDiagonals) { if (cell.HorizontalRelatives(grid) == 2 || cell.VerticalRelatives(grid) == 2) { return true; } if (checkDiagonals) { if (cell.DiagonalRelatives(grid) == 2) { return true; } else if (cell.DiagonalRelatives2(grid) == 2) { return true; } } return false; } #endregion } </code></pre> <p><strong>Gameround.cs</strong></p> <pre><code>class GameRound { public delegate void RoundEndHandler(OutcomeType gameOutcome); #region Fields &amp; Properties private static int ctr; private Grid grid; public readonly int ID; public static event RoundEndHandler Complete; public Player CurrentPlayer { get; private set; } #endregion #region Constructors public GameRound() { ID = ctr++; grid = new Grid(); } #endregion #region Instanced Methods public void Start() { bool doLoop = true; while (doLoop) { for (int i = 0; i &lt; Game.players.Length; i++) { CurrentPlayer = Game.players[i]; var coord = Game.players[i].GetPlayerChoice(grid, CurrentPlayer); grid.cells[coord.Item1, coord.Item2].MarkType = CurrentPlayer.marker; //check if game is over if (grid.CheckOutcome(coord, CurrentPlayer)) { doLoop = false; break; } } } Complete(grid.Outcome); } #endregion } </code></pre> <p><strong>ExtensionMethods.cs</strong></p> <pre><code>static class ExtensionMethods { #region Cell Extension Methods public static int DiagonalRelatives(this Cell cell, Grid grid) { int relatives = new int(); for (int x = 0; x &lt; 3; x++) { if (grid.cells[x, x].MarkType.Equals(cell.MarkType)) { relatives++; } } return relatives - 1; } public static int DiagonalRelatives2(this Cell cell, Grid grid) { int relatives = new int(); for (int x = 0; x &lt; 3; x++) { if (grid.cells[x, 2 - x].MarkType.Equals(cell.MarkType)) { relatives++; } } return relatives - 1; } public static int HorizontalRelatives(this Cell cell, Grid grid) { int relatives = new int(); int rowNum = grid.cells.IndexOf(cell).Item2; for (int x = 0; x &lt; 3; x++) { //Find row of cell if (grid.cells[x, rowNum].MarkType.Equals(cell.MarkType)) { relatives++; } } return relatives - 1; } public static int VerticalRelatives(this Cell cell, Grid grid) { int relatives = new int(); int colNum = grid.cells.IndexOf(cell).Item1; for (int y = 0; y &lt; 3; y++) { //Find row of cell if (grid.cells[colNum, y].MarkType.Equals(cell.MarkType)) { relatives++; } } return relatives - 1; } #endregion #region Cell[] Extension Methods public static Cell[] GetEmptyCells(this Cell[,] cells) { List&lt;Cell&gt; emptyCells = new List&lt;Cell&gt;(); foreach (Cell cell in cells) { if (cell.MarkType == Mark.Empty) { emptyCells.Add(cell); } } return emptyCells.ToArray(); } public static Tuple&lt;int, int&gt; IndexOf(this Cell[,] cells, Cell cell) { for (int x = 0; x &lt; cells.GetLength(0); x++) { for (int y = 0; y &lt; cells.GetLength(1); y++) { if (cells[x, y].Equals(cell)) { return new Tuple&lt;int,int&gt;(x, y); } } } //If code reaches this point, then it didn't find anything, return -1 return new Tuple&lt;int,int&gt;(-1, -1); } #endregion } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:28:45.410", "Id": "78525", "Score": "2", "body": "why use extension methods if you can edit the class directly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:34:57.263", "Id": "78526", "Score": "0", "body": "@MarcoAcierno Just a matter of preference really, I think it's cleaner this way. I do have some member methods in the classes directly, but the ones that I've added as extension methods I feel fit better as extension methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:43:44.373", "Id": "78528", "Score": "0", "body": "Well, you will end up with have more methods inside ExtensionMethods than the classes itself.. To read class methods you should read two files not just the file class and, when you project will have more than 10/20/30+ classes you will end up with a ExtensionMethods very big (#region will not help you really) but class file very small and don't give help you to know what the class can do and what is supposed to do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T22:52:47.087", "Id": "78546", "Score": "0", "body": "Sorry for the lack of \"positive feedback\": that's a reflection on my reviewing, not of your code (I point out the few things that are wrong, rather than the many things that are right). Your code works, and I understood almost all of it, so, congratulations!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T23:02:01.023", "Id": "78549", "Score": "0", "body": "Oh don't worry about that Chris, I said that both positive and negative feedback was welcome and personally I feel like negative feedback will probably help me become a better programmer. I just want to extend a big thanks to you for taking the time to review my code, I'm going through your review with a fine comb so I can try to implement your suggested improvements and most importantly learn from them." } ]
[ { "body": "<p>To answer the \"bonus question\" that may not be the right algorithm for the AI: it assumes that the human player is playing randomly.</p>\n\n<p>As a human player, I play to a) not-lose b) win. That's why most games (between experienced humans) end in a draw.</p>\n\n<p>With the algorithm you suggested, there might be a move which results in 10 possible wins (if I play stupidly/randomly) and 1 loss (if I play cleverly). Because the win/loss ratio is high (10-to-1) you might pick it and (because I'm not stupid) I then play the correct move and win.</p>\n\n<p>IMO the algorithm you want is to choose the move which allows you to prevent my winning no matter what I do, i.e. a move which allows you to guarantee you can't lose.</p>\n\n<hr>\n\n<p>Mandatory code review:</p>\n\n<p>I'm surprised that plays and vGrid are static inside Game. What if there's more than one Game instance?</p>\n\n<p>It's difficult to assess the lifetime of a Game: why doesn't a Game include a Grid? Instead Game instantiates a GameRound as a local/temporary, which it passes to a local/temporary Task?</p>\n\n<p>The Cell extension methods like <code>int DiagonalRelatives(this Cell cell, Grid grid)</code> might be more naturally ordinary methods of the Grid class.</p>\n\n<p>What happens if the player plays on an already-marked cell? It looks like nothing happens, except that they lose their turn?</p>\n\n<p>I suspect this could be a lot simpler/clearer (but I'm not tempted to rewrite it at the moment).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T17:50:15.607", "Id": "78537", "Score": "0", "body": "When it comes to the algorithm, it would also take into consideration in how many turns it could win. But you might be right, I \"feel\" like it should work regardless of how the human plays though since it will know every possible future gamestate and their respective branches." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T17:51:01.437", "Id": "78538", "Score": "0", "body": "About your code review. Game is the main form, so there will only be one instance. That's also why a game consists of an infinite amount of game rounds that are instantiated. About the extension methods, I concede that it would make more sense to have them in the grid class. Lastly, you can't play on an already marked cell because the vCell is disabled after it is assigned a value." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:41:59.030", "Id": "45093", "ParentId": "45091", "Score": "5" } }, { "body": "<p>I posted an edited version of some of your classes, below:</p>\n\n<ul>\n<li>I removed your comments so that my comments would be more apparent; all changes are commented.</li>\n<li>I commented-out instead of deleting some your lines of code, to make my deletions apparent</li>\n</ul>\n\n<p>The major change in this version is that there are no longer any static member data.</p>\n\n<p>If I refactor then I refactor in stages: this would be the end of my first round of refactoring; this round doesn't change any existing algorithms, just cleans up stray inter-class interactions (i.e. static data, and unused data).</p>\n\n<h2>Game.cs</h2>\n\n<pre><code>public partial class Game : Form\n{\n #region Fields &amp; Properties\n\n // I don't like static data except where necessary.\n internal VisualCell[,] vGrid;\n internal Player[] players;\n\n #endregion\n\n #region Constructors\n\n public Game()\n {\n InitializeComponent();\n }\n\n #endregion\n\n #region Instanced Methods\n\n private void Game_Load(object sender, EventArgs e)\n {\n players = new Player[2];\n // Clearer to pass the correct Mark as a parameter.\n players[0] = new Player(Mark.Cross);\n players[1] = new Player(Mark.Nought);\n // Avoid static data\n //GameRound.Complete += ShowCompletionDialog;\n GenerateGridBtns();\n // Invoke new method.\n NewGameStart();\n }\n\n private void ShowCompletionDialog(OutcomeType gameOutcome)\n {\n long pID = (long)gameOutcome + 1;\n string WonText = \"Player \" + pID + \" won!\";\n\n if (gameOutcome == OutcomeType.Draw)\n {\n WonText = \"The game ended in a draw!\";\n }\n\n DialogResult dialogResult = MessageBox.Show(\"Play again?\", WonText, MessageBoxButtons.YesNo);\n\n if (dialogResult == DialogResult.Yes)\n {\n RestartGame();\n }\n else if (dialogResult == DialogResult.No)\n {\n // What now?\n }\n }\n\n private void GenerateGridBtns()\n {\n vGrid = new VisualCell[3, 3];\n\n for (int x = 0; x &lt; 3; x++)\n {\n for (int y = 0; y &lt; 3; y++)\n {\n vGrid[x, y] = new VisualCell()\n {\n AutoSize = true,\n Location = new Point(x * 110, y * 110),\n Size = new Size(124, 124),\n Enabled = false,\n Font = new Font(Font.FontFamily, 40),\n CellPos = new Tuple&lt;int, int&gt;(x, y)\n };\n Controls.Add(vGrid[x, y]);\n }\n }\n }\n\n private void RestartGame()\n {\n for (int x = 0; x &lt; 3; x++)\n {\n for (int y = 0; y &lt; 3; y++)\n {\n vGrid[x, y].Invoke(new Action(() =&gt; vGrid[x, y].Text = String.Empty));\n vGrid[x, y].Invoke(new Action(() =&gt; vGrid[x, y].Enabled = false));\n }\n }\n // Invoke new method.\n NewGameStart();\n }\n\n // Make this a method so that it can be called from two places (start and restart)\n void NewGameStart()\n {\n // I don't see why GameRound and Game aren't the same class.\n // Because GameRound uses data owned by Game i.e. players and vGrid it would be\n // more convenient to move the GameRound methods into Game.\n // Or, construct mew players and new vGrid for each GameRound, as members of GameRound.\n // But keeping your existing class stucture (two classes) it's better to share data\n // by passing as parameters (e.g. into the constructor) than sharing static data.\n var round = new GameRound(ShowCompletionDialog, vGrid, players);\n Task roundTask = Task.Factory.StartNew(() =&gt; round.Start());\n }\n\n #endregion\n}\n</code></pre>\n\n<h2>GameRound.cs</h2>\n\n<pre><code>class GameRound\n{\n public delegate void RoundEndHandler(OutcomeType gameOutcome);\n\n #region Fields &amp; Properties\n // Could call these Id and IdCounter\n // or delete them because they're not used anywhere.\n //private static int ctr;\n //public readonly int ID;\n private Grid grid;\n // Doesn't have to be public static. Avoid static unless necessary.\n private event RoundEndHandler Complete;\n VisualCell[,] vGrid;\n Player[] players;\n // CurrentPlayer can be a local variable, not a public property.\n //public Player CurrentPlayer { get; private set; }\n\n #endregion\n\n #region Constructors\n\n // Pass the RoundEndHandler etc. as parameters instead of using public static.\n public GameRound(\n RoundEndHandler complete,\n VisualCell[,] vGrid,\n Player[] players)\n {\n // ID isn't used anywhere.\n //ID = ctr++;\n grid = new Grid();\n // Initialize new instance data.\n Complete = complete;\n this.vGrid = vGrid;\n this.players = players;\n }\n\n #endregion\n\n #region Instanced Methods\n\n public void Start()\n {\n // Use 'return' to escape from a nested loop.\n //bool doLoop = true;\n //while (doLoop)\n while (true)\n {\n // Acts on own instance data i.e. this.players not static Game.players.\n for (int i = 0; i &lt; players.Length; i++)\n {\n // CurrentPlayer can be a local variable, not a public property.\n Player CurrentPlayer = players[i];\n // Pass vGrid as a parameter.\n var coord = players[i].GetPlayerChoice(grid, CurrentPlayer, vGrid);\n grid.cells[coord.Item1, coord.Item2].MarkType = CurrentPlayer.marker;\n\n //check if game is over\n OutcomeType? outcome = grid.CheckOutcome(coord, CurrentPlayer);\n if (outcome.HasValue)\n {\n // Use 'return' to escape from a nested loop.\n Complete(outcome.Value);\n return;\n //doLoop = false;\n //break;\n }\n }\n }\n\n //Complete(grid.Outcome);\n }\n\n #endregion\n}\n</code></pre>\n\n<h2>Player.cs</h2>\n\n<pre><code>class Player\n{\n #region Fields &amp; Properties\n\n // Never used.\n //private static Game form;\n // Clearer to pass the correct Mark as a parameter.\n //private static int ctr;\n //public readonly int ID;\n public Mark marker;\n // Never used.\n //public int Score { get; set; }\n\n #endregion\n\n #region Constructors\n\n public Player(Mark marker)\n {\n // Clearer to pass the correct Mark as a parameter.\n //ID = ctr++;\n\n //if (ID == 0)\n //{ // X is the starting player\n // marker = Mark.Cross;\n //}\n //else\n //{\n // marker = Mark.Nought;\n //}\n this.marker = marker;\n }\n\n #endregion\n\n #region Instanced Methods\n\n // vGrid is passed by parameter, not access static Game.vGrid\n public virtual Tuple&lt;int, int&gt; GetPlayerChoice(Grid grid, Player player, VisualCell[,] vGrid)\n {\n // Player's marker is a public property: might as well use that instead of 'ID'.\n //var pMark = (player.ID == 0) ? \"X\" : \"O\";\n var pMark = (player.marker == Mark.Cross) ? \"X\" : \"O\";\n var choice = new Tuple&lt;int, int&gt;(-1, -1);\n var waitBtns = new List&lt;Task&gt;() { new Task(() =&gt; new SpinWait().SpinOnce()) };\n\n //Enable eligble buttons for player\n for (int x = 0; x &lt; grid.cells.GetLength(0); x++)\n {\n for (int y = 0; y &lt; grid.cells.GetLength(1); y++)\n {\n if (grid.cells[x, y].MarkType == Mark.Empty)\n {\n vGrid[x, y].Invoke(new Action(() =&gt; vGrid[x, y].Enabled = true));\n vGrid[x, y].Click += new EventHandler(\n (a, b) =&gt;\n {\n var pos = new Tuple&lt;int, int&gt;((a as VisualCell).CellPos.Item1, (a as VisualCell).CellPos.Item2);\n choice = Tuple.Create(pos.Item1, pos.Item2);\n vGrid[pos.Item1, pos.Item2].Invoke(new Action(() =&gt; vGrid[pos.Item1, pos.Item2].Text = pMark));\n vGrid[pos.Item1, pos.Item2].Invoke(new Action(() =&gt; vGrid[pos.Item1, pos.Item2].Enabled = false));\n waitBtns.Add(new Task(() =&gt; new SpinWait().SpinOnce()));\n waitBtns[waitBtns.FindIndex(t =&gt; t.Status == TaskStatus.Created)].Start();\n });\n }\n }\n }\n Task.WaitAny(waitBtns.ToArray());\n return choice;\n }\n\n public bool PlayerWon(Cell cell, Grid grid, bool checkDiagonals)\n {\n if (cell.HorizontalRelatives(grid) == 2 || cell.VerticalRelatives(grid) == 2)\n {\n return true;\n }\n\n if (checkDiagonals)\n {\n if (cell.DiagonalRelatives(grid) == 2) { return true; }\n else if (cell.DiagonalRelatives2(grid) == 2) { return true; }\n }\n\n return false;\n }\n\n #endregion\n}\n</code></pre>\n\n<h2>Grid.cs</h2>\n\n<pre><code>class Grid\n{\n const int MAX_CELLS = 3;\n\n #region Properties &amp; Fields\n\n public Cell[,] cells { get; set; }\n // Instead of storing Outcome in the grid, can return it as a return code.\n //public OutcomeType Outcome { get; private set; }\n\n #endregion\n\n #region Constructors\n\n public Grid()\n {\n //Outcome = OutcomeType.None;\n cells = new Cell[MAX_CELLS, MAX_CELLS];\n\n for (int x = 0; x &lt; MAX_CELLS; x++)\n {\n for (int y = 0; y &lt; MAX_CELLS; y++)\n {\n cells[x, y] = new Cell();\n }\n }\n }\n\n #endregion\n\n #region Instanced Methods\n\n // Instead of storing Outcome in the grid, can return it as a return code.\n public OutcomeType? CheckOutcome(Tuple&lt;int, int&gt; coords, Player player)\n {\n //Check for draws first\n if (cells.GetEmptyCells().Length == 0)\n {\n //Outcome = OutcomeType.Draw;\n //return true;\n return OutcomeType.Draw;\n }\n\n var corners = new Tuple&lt;int, int&gt;[] { Tuple.Create(0, 0), Tuple.Create(2, 0), Tuple.Create(0, 2), Tuple.Create(2, 2) };\n var sides = new Tuple&lt;int, int&gt;[] { Tuple.Create(1, 0), Tuple.Create(0, 1), Tuple.Create(1, 2), Tuple.Create(2, 1) };\n var middle = new Tuple&lt;int, int&gt;(1, 1);\n var checkDiagonals = false;\n\n if (corners.Any(e =&gt; e.Equals(coords)) || middle.Equals(coords)) { checkDiagonals = true; }\n\n if (player.PlayerWon(cells[coords.Item1, coords.Item2], this, checkDiagonals))\n {\n switch (player.marker)\n {\n case Mark.Cross:\n //Outcome = OutcomeType.CrossWin;\n //break;\n return OutcomeType.CrossWin;\n case Mark.Nought:\n //Outcome = OutcomeType.NoughtWin;\n //break;\n return OutcomeType.NoughtWin;\n default:\n throw new NotImplementedException();\n }\n\n //return true;\n }\n\n //If execution reaches this point then no one has won, return null\n return null;\n }\n\n #endregion\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T23:17:42.183", "Id": "78555", "Score": "0", "body": "I want to say, I know that you think the seperation of Game & GameRound is sort of off, and it might be but I just want to explain why it's like that, it's mainly two reasons. \n\n1) I'm still quite used to writing console apps, I only recently transitioned into winforms apps 2 months or so ago.\n2) Now this is probably just my personal preference, but I don't like fitting a bunch of logic in \"Form\" source files. For me it only makes sense for them to control the UI, but like I said I don't know if this is standard convention or not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T00:50:26.733", "Id": "78560", "Score": "0", "body": "@OverlyExcessive \"I don't like fitting a bunch of logic in \"Form\" source files\" -- Many would agree. It makes the code a bit longer (to have more than once class) but more flexible if (but perhaps only if) you separate them well. You could move creating players and vGrid into GameRound and not have them in the Game Form at all. Even then you have tight coupling because GameRound is working with the Game's UI buttons. Using `event` as shown at the end of my other answer would help to separate that (GameRound fires an event when a cell changes and doesn't know/care whether their are UI buttons)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T22:20:03.553", "Id": "78843", "Score": "0", "body": "I've updated the code to follow the MVP pattern as suggested by you, as well as some of your other suggested changes. Please have a look and let me know if you think it's an improvement + any other feedback you may have on the code of course." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T22:08:48.893", "Id": "45104", "ParentId": "45091", "Score": "1" } }, { "body": "<p>One more set of comments.</p>\n\n<hr>\n\n<p>You don't do a good job of invoking Dispose on objects whose classes implement IDisposable.</p>\n\n<p>This includes your many Task instances, and your many VisualCell instances (there may be others I didn't notice).</p>\n\n<p>I'd like to see more calls to <code>Dispose</code>, and/or <code>using</code> statements.</p>\n\n<p>You can dispute this advice:</p>\n\n<ul>\n<li><p>Tasks: <a href=\"http://blogs.msdn.com/b/pfxteam/archive/2012/03/25/10287435.aspx\" rel=\"nofollow noreferrer\">Do I need to dispose of Tasks?</a></p></li>\n<li><p>VisualCell instances: they have the same lifetime as your main form, and the application will end (with all resources reclaimed by the O/S) when your main form closes.</p></li>\n</ul>\n\n<p>I mention it because it (disposing disposables) is IMO \"good practice\".</p>\n\n<hr>\n\n<p>The code in GetPlayerChoice is IMO a horror show: masses of Invoke statements and Task instances with SpinWait instances.</p>\n\n<p>You're installing <code>vGrid[x, y].Click</code> event handlers each time you call GetPlayerChoice (and I don't understand what happens to old, previous-installed Click event handlers).</p>\n\n<p>The normal way to do this in a Windows Forms application would be:</p>\n\n<ul>\n<li>Don't use a Task</li>\n<li>Install a Click event handler once, in the Form (Game) class</li>\n<li>The event handler could call a method of GameRound, e.g. a method named <code>void OnPlayerChoice(VisualCell chosenCell)</code></li>\n<li>Game would need a reference to the GameRound instance: therefore the GameRound instance would be member data of Game, instead of just a local variable in the NewGame method, so that Game could call the GameRound instance's OnPlayerChoice method</li>\n<li>OnPlayerChoice could return <code>OutcomeType?</code> in which case it wouldn't need a delegate to do a callback to the ShowCompletionDialog</li>\n<li>GameRound would need to remember which is the CurrentPlayer (as a property not just as a local variable); alternatively, Game could remember that, and pass it as a parameter. I still think that maybe GameRound should be merged into the Game class.</li>\n</ul>\n\n<p>Because there are no Task instances, you don't need to use Invoke. The game is \"event-driven\" from the GUI, i.e. driven by the Click event handlers.</p>\n\n<p>If one of the players is an AI then the Game, instead of waiting for the Click event, can call the AI player's \"choose\" method immediately after processing the human player's GUI click.</p>\n\n<hr>\n\n<p>Alternatively it's theoretically possible, e.g. by defining abstract interfaces between 'View' (Form) and 'Controller' (GameRound) and 'Data Model' (Grid and Cells), to decouple the Game or GameRound from the Form more completely: so that the GameRound doesn't know whether it's attached to a Form, or to a Console, or is simply writing results to a File.</p>\n\n<p>If you eventually did that, that might be another way to implement an AI: if the GameRound doesn't know where the player choices were coming from it might be easy to make some of the choices come from an AI instead of the GUI.</p>\n\n<hr>\n\n<blockquote>\n <p>isn't the point of the managed garbage collector to dispose of objects that aren't used anymore for me?</p>\n</blockquote>\n\n<p>Yes. The garbage collector might take a while to run, though. For example if you open a file and then let go of the open file without disposing it, the O/S file handle will remain open until the garbage collector reclaims the object; during that time, you can't reopen/reuse the file.</p>\n\n<p>Similarly some resources are in limited supply: you might only be allowed a few SQL connections, or SQL transaction, or GDI objects (brushes and fonts). \"A few\" might be hundreds, but if the garbage collector runs every 10 seconds or so that gives you a rate-limited throughput of 10 per second: so your code works fine until you put a real-world heavy load on it.</p>\n\n<p>The garbage collector is there to reclaim memory. It knows what memory you have used. If the memory contains undisposed resources those resources will be properly disposed; but I see that as a second line of defence (in case you didn't dispose them explicitly).</p>\n\n<blockquote>\n <p>Also about the old previous-installed event handlers for Click I also thought that would screw things up but having ran a dozen iterations of the game and seperate rounds without a problem, it doesn't seem to do so?</p>\n</blockquote>\n\n<p>If I put a breakpoint in the event handler I can see that it's called multiple times: once the first time, twice the second time, etc. If it's called more than once (e.g. twice) then it sets the vButton text twice, disables it twice, adds two tasks to the waitBtns list. The event handlers also occupy memory and can't be garbage-collected: so if you ran it for long enough (much longer than you've run it) it would run out of memory.</p>\n\n<blockquote>\n <p>Would you elaborate on what you mean by implementing abstract interfaces?</p>\n</blockquote>\n\n<p>The simplest version I can think of wouldn't have interfaces.</p>\n\n<p>Have a GameController with the following public API:</p>\n\n<pre><code>// Let players play\nvoid PlayerChoose(Marker playerId, Tuple&lt;int,int&gt; position);\n// Let players inspect the current board\n// (optional, otherwise players can remember the state of play\n// e.g. the Game Form has this state already duplicated in its buttons)\nCell[,] Cells { get; }\n// Tell players when the board has changed\ndelegate void PlayedEventHandler(Marker playerId, Tuple&lt;int,int&gt; position);\nevent PlayedEventHandler Played;\n// Tell players when the game is finished\ndelegate void FinishedEventHandler(OutcomeType outcome);\nevent FinishedEventHandler Finished;\n// Let players start a new game\nvoid Reset();\n</code></pre>\n\n<p>An all-human Form-based application can:</p>\n\n<ul>\n<li>Have a Game Form like yours</li>\n<li>Game contains (references) a GameController</li>\n<li>Game attaches to the Played event handler and updates its UI buttons accordingly</li>\n<li>Game attaches to its buttons' Clicked event handler and invokes the PlayerChoose method accordingly</li>\n</ul>\n\n<p>A human-versus-AI application can do the same as the above, except:</p>\n\n<ul>\n<li>The Game Form is only used by one player</li>\n<li>There's another, AI class, which:\n\n<ul>\n<li>Contains a reference to the GameController</li>\n<li>Attaches to the Played event handler</li>\n<li>Chooses its next move and invokes the PlayerChoose method, when the Played event handler tells it that the human has played.</li>\n</ul></li>\n</ul>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter\" rel=\"nofollow noreferrer\">Model–view–presenter</a></li>\n<li><a href=\"https://codereview.stackexchange.com/search?q=%5Bc%23%5D+tic\">Other tic-tac-toe implementations in c# on this site</a> (I don't know which of them are good)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T23:10:33.553", "Id": "78551", "Score": "0", "body": "Regarding disposables on `IDisposable` objects. I have to admit I am not very knowledgeable in the area, but isn't the point of the managed garbage collector to dispose of objects that aren't used anymore for me? \n\nRegarding `GetPlayerChoice()`, I completely agree. The goal was to make it produce an output that would work with both an AI and human player.. Also about the old previous-installed event handlers for Click I also thought that would screw things up but having ran a dozen iterations of the game and seperate rounds without a problem, it doesn't seem to do so?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T23:20:50.530", "Id": "78556", "Score": "0", "body": "I'm very interested in this decoupling thing you're talking about Chris. Would you elaborate on what you mean by implementing abstract interfaces? I don't need specific code examples, I just need the rough idea down so I can research the rest myself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T00:43:10.067", "Id": "78559", "Score": "0", "body": "I updated my answer to reply to your comments." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T22:38:54.940", "Id": "45107", "ParentId": "45091", "Score": "2" } }, { "body": "<p>Okay I've tried my best at revamping my code and restructuring after the MVP design pattern. It's not a complete rewrite, and one could argue that it's not a \"true\" MVP implementation because I never implemented an interface for the model, it felt redudant for the primitive data that I was storing/accessing. Keep in mind, my interpretation of MVP is based on about an hour of reading about it and this is my first attempt at structuring my code after any \"explicit\" programming design pattern.</p>\n\n<p>I've also taken some of your other ChrisW's suggestions and implemented them. I might not have implemented all of them, it's not cause I didn't like them or that I consider myself to know better, it's just that as a part of my learning process, first hand I always try to force myself to think up my own solutions to problems instead of just copy &amp; pasting others solutions, others code should serve as inspiration I believe I'll learn to code better by that.</p>\n\n<p>Overall, I want to thank ChrisW for his great feedback and his patience with me. I think the code looks cleaner now (But I'll await your feedback Chris) the only caveat with this solution is that implementing the AI Player will be a tad bit more difficult now.</p>\n\n<p>Here's my new code(I've only listed the files that I have changed or added):</p>\n\n<p>For easy access, I'll list roughly some of the changes that I've made: </p>\n\n<ul>\n<li>Removed static fields (as suggested by ChrisW)</li>\n<li>Not calling <code>Dispose()</code> on disposables but I have removed almost all of them now </li>\n<li>Removed a bunch of redundant code (IDs and some counters)</li>\n<li>GameRound class removed</li>\n<li>Added GameController class</li>\n<li>MVP design pattern implemented </li>\n<li>... a bunch of other stuff I don't remember</li>\n</ul>\n\n<p><strong>GameForm.cs</strong>(formerly Game.cs)</p>\n\n<pre><code>public partial class GameForm : Form, IGameViewer\n{\n #region Fields &amp; Properties\n\n private VisualCell[,] vGrid = new VisualCell[3, 3];\n private IGamePresenter presenter;\n\n #endregion\n\n #region Constructors\n\n public GameForm()\n {\n InitializeComponent();\n }\n\n #endregion\n\n #region Instanced Methods\n\n private void Game_Load(object sender, EventArgs e)\n {\n presenter = new GameController(this);\n presenter.OnGameEnd += ShowCompletionDialog; // When IGamePresenter raises OnGameEnd event then the viewer is free to show completion dialog\n }\n\n private void ShowCompletionDialog(OutcomeType outcome)\n {\n string WonText = \"Player \" + (long)outcome + \" won!\";\n\n if (outcome.Equals(OutcomeType.Draw))\n { \n WonText = \"The game ended in a draw!\";\n }\n\n DialogResult dialogResult = MessageBox.Show(\"Play again?\", WonText, MessageBoxButtons.YesNo);\n\n if (dialogResult == DialogResult.Yes)\n {\n presenter.RestartGame(); // Viewer -&gt; Presenter, restart the game\n } else if (dialogResult == DialogResult.No)\n {\n //do something else\n }\n }\n\n void IGameViewer.DisplayCell(Cell cell)\n {\n vGrid[cell.coords.Item1, cell.coords.Item2] = new VisualCell() \n {\n AutoSize = true,\n Location = new Point(cell.coords.Item1 * 110, cell.coords.Item2 * 110),\n Size = new Size(124, 124),\n Font = new Font(Font.FontFamily, 40),\n CellPos = new Tuple&lt;int, int&gt;(cell.coords.Item1, cell.coords.Item2)\n };\n\n vGrid[cell.coords.Item1, cell.coords.Item2].Click += new EventHandler(\n (a, b) =&gt;\n {\n var pos = new Tuple&lt;int, int&gt;((a as VisualCell).CellPos.Item1, (a as VisualCell).CellPos.Item2);\n presenter.PlayerChoice(pos); // Viewer -&gt; Presenter, when btn is clicked call PlayerChoice();\n });\n\n Controls.Add(vGrid[cell.coords.Item1, cell.coords.Item2]);\n }\n\n void IGameViewer.CellChanged(Cell cell) \n { \n vGrid[cell.coords.Item1, cell.coords.Item2].Text = (cell.MarkType.Equals(Mark.Cross)) ? \"X\" : \"O\";\n vGrid[cell.coords.Item1, cell.coords.Item2].Enabled = false;\n }\n\n void IGameViewer.ResetCell(Cell cell) \n {\n vGrid[cell.coords.Item1, cell.coords.Item2].Text = String.Empty;\n vGrid[cell.coords.Item1, cell.coords.Item2].Enabled = true; \n }\n\n #endregion \n}\n</code></pre>\n\n<p><strong>GameController.cs</strong></p>\n\n<pre><code>public delegate void GameEndHandler(OutcomeType outcome);\n\nclass GameController : IGamePresenter \n{\n #region Fields &amp; Properties\n\n private IGameViewer viewer;\n private Player[] players = new Player[2];\n public event GameEndHandler OnGameEnd;\n public Player CurrentPlayer { get; private set; }\n\n private Grid grid;\n #endregion \n\n #region Constructors\n\n public GameController(IGameViewer viewer) \n { \n this.viewer = viewer;\n grid = new Grid(viewer);\n players[0] = new Player(Mark.Cross); // Set to human or AI\n players[1] = new Player(Mark.Nought); // Always set to human\n CurrentPlayer = players[0];\n }\n\n #endregion\n\n #region Instanced Methods\n\n void IGamePresenter.PlayerChoice(Tuple&lt;int,int&gt; coords) \n { \n // Presenter -&gt; Model, place marker at coords\n grid.cells[coords.Item1, coords.Item2].MarkType = CurrentPlayer.marker;\n\n // Model -&gt; Presenter, if grid reaches an outcome end the game\n if(grid.CheckOutcome(coords, CurrentPlayer)) \n {\n OnGameEnd(grid.Outcome);\n }\n\n CurrentPlayer = (CurrentPlayer.ID == 0) ? players[1] : players[0];\n }\n\n void IGamePresenter.RestartGame() \n {\n for (int x = 0; x &lt; grid.cells.GetLength(0); x++)\n {\n for (int y = 0; y &lt; grid.cells.GetLength(1); y++)\n {\n grid.cells[x, y].Reset();\n }\n }\n }\n\n #endregion\n}\n</code></pre>\n\n<p><strong>Cell.cs</strong></p>\n\n<pre><code>class Cell\n{\n #region Properties &amp; Fields\n\n private Mark markType = Mark.Empty; /* Have to use old way of defining properties here unfortunately due to lack of support for,\n * default values in auto-implemented properties. */\n\n private IGameViewer viewer;\n public readonly Tuple&lt;int, int&gt; coords;\n public Mark MarkType { \n get { return markType; } \n set \n {\n // Only allow changes to cells without a mark \n if (markType.Equals(Mark.Empty)) \n { \n markType = value;\n viewer.CellChanged(this); //Model -&gt; Viewer update viewer to reflect change in cell marktype\n } \n } \n }\n\n #endregion\n\n #region Constructors\n\n public Cell(IGameViewer viewer, Tuple&lt;int, int&gt; coords)\n {\n this.viewer = viewer;\n this.coords = coords;\n viewer.DisplayCell(this);\n }\n\n #endregion\n\n #region Instanced Methods\n\n public void Reset() //This method is necessary because we can't use the property to\n {\n markType = Mark.Empty;\n viewer.ResetCell(this);\n }\n\n #endregion\n}\n\npublic enum OutcomeType\n{\n None = -1, CrossWin, NoughtWin, Draw\n}\n\nclass Grid\n{\n const int MAX_CELLS = 3;\n\n #region Properties &amp; Fields\n\n public Cell[,] cells { get; set; }\n public OutcomeType Outcome { get; private set; }\n\n #endregion\n\n #region Constructors\n\n public Grid(IGameViewer viewer)\n {\n Outcome = OutcomeType.None;\n cells = new Cell[MAX_CELLS, MAX_CELLS];\n\n for (int x = 0; x &lt; MAX_CELLS; x++)\n {\n for (int y = 0; y &lt; MAX_CELLS; y++)\n {\n cells[x, y] = new Cell(viewer, new Tuple&lt;int,int&gt;(x, y));\n }\n }\n }\n\n #endregion\n\n #region Instanced Methods\n\n public bool CheckOutcome(Tuple&lt;int, int&gt; coords, Player player)\n {\n //Check for draws first\n if (cells.GetEmptyCells().Length == 0)\n {\n Outcome = OutcomeType.Draw; \n return true;\n }\n\n //Now check for player wins\n var corners = new Tuple&lt;int, int&gt;[] { Tuple.Create(0,0), Tuple.Create(2,0), Tuple.Create(0,2), Tuple.Create(2,2) };\n var sides = new Tuple&lt;int, int&gt;[] { Tuple.Create(1,0), Tuple.Create(0,1), Tuple.Create(1,2), Tuple.Create(2,1) };\n var middle = new Tuple&lt;int, int&gt;(1,1);\n var checkDiagonals = false;\n\n //If the cell is at the corner or the middle we have to check for diagonal wins too\n if (corners.Any(e =&gt; e.Equals(coords)) || middle.Equals(coords)) { checkDiagonals = true; }\n\n if (player.PlayerWon(cells[coords.Item1, coords.Item2], this, checkDiagonals))\n {\n switch (player.marker)\n {\n case Mark.Cross:\n Outcome = OutcomeType.CrossWin;\n break;\n case Mark.Nought:\n Outcome = OutcomeType.NoughtWin;\n break;\n }\n\n return true;\n }\n\n //If execution reaches this point then no one has won, return false\n return false;\n }\n\n #endregion\n}\n</code></pre>\n\n<p><strong>Player.cs</strong></p>\n\n<pre><code>class Player\n{\n #region Fields &amp; Properties\n\n private static int ctr;\n public Mark marker;\n public readonly int ID;\n public int Score { get; set; }\n\n #endregion \n\n #region Constructors\n\n public Player(Mark marker)\n {\n ID = ctr++;\n this.marker = marker;\n }\n\n #endregion\n\n #region Instanced Methods\n\n public bool PlayerWon(Cell cell, Grid grid, bool checkDiagonals) \n {\n if (cell.HorizontalRelatives(grid) == 2 || cell.VerticalRelatives(grid) == 2)\n {\n return true;\n }\n\n if (checkDiagonals)\n {\n if (cell.DiagonalRelatives(grid) == 2) { return true; } \n else if (cell.DiagonalRelatives2(grid) == 2) { return true; }\n }\n\n return false;\n }\n\n #endregion \n}\n</code></pre>\n\n<p><strong>IGameViewer.cs</strong></p>\n\n<pre><code>/// &lt;summary&gt;\n/// IGameViewer represents the viewing medium of the game, it could for example be WinForms, WPF or a Console application.\n/// It receives data from the Model and Presenter and displays the data in a visual way for the enduser.\n/// &lt;/summary&gt;\ninterface IGameViewer\n{\n //This is called from Model whenever a cell changes type\n void CellChanged(Cell cell);\n //Called whenever a new cell is created\n void DisplayCell(Cell cell);\n //Resets the cell to it's initial state, called when restarting the game\n void ResetCell(Cell cell);\n}\n</code></pre>\n\n<p><strong>IGamePresenter.cs</strong></p>\n\n<pre><code>/// &lt;summary&gt;\n/// GamePresenter interface will control the flow of the game, by manipulating the model(Cell/Grid) and \n/// formatting the data so it is presentable to the viewer(GameForm).\n/// &lt;/summary&gt;\ninterface IGamePresenter\n{\n void RestartGame();\n void PlayerChoice(Tuple&lt;int, int&gt; coords);\n event GameEndHandler OnGameEnd;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T09:44:14.507", "Id": "78890", "Score": "0", "body": "+1 because it's IMO a big improvement, and is a good answer to the original question above. It's difficult provide detailed feedback in comments; so, if you want a detailed review I suggest you re-post this as a new question: [How to post a follow-up question?](http://meta.codereview.stackexchange.com/a/1066/34757)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T22:18:37.537", "Id": "45264", "ParentId": "45091", "Score": "4" } } ]
{ "AcceptedAnswerId": "45107", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T16:15:59.700", "Id": "45091", "Score": "11", "Tags": [ "c#", "object-oriented", "multithreading", "game" ], "Title": "Clean and well-designed Tic-Tac-Toe game" }
45091
<p>I have been working with Java for a little more than a year. I recently have built a Tic Tac Toe game as an assignment for my Java class. After my instructor graded it, he wrote a comment around my validation method logic. Even though I got 100%, he said that the logic in my validation method is too cumbersome. He stated that I should look into a <code>for or</code>while` statement in order to clean out some code in my validation method.</p> <p>Is there really a way to put all my conditional <code>if</code> statements in to a <code>for</code> or <code>while</code> loop? And if so, I would like to know what logic goes behind that. This program had a set of five arrays but in this validation method I worked only with the <code>JButton</code> array.</p> <pre><code>JButton [] button = new JButton [9]; public void validate() { if(button[0].getText().equals(button[1].getText()) &amp;&amp; button[1].getText().equals(button[2].getText())) { JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[0].getText()); gameOver(); return; } else if(button[3].getText().equals(button[4].getText()) &amp;&amp; button[4].getText().equals(button[5].getText())) { JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[3].getText()); gameOver(); return; } else if(button[6].getText().equals(button[7].getText()) &amp;&amp; button[7].getText().equals(button[8].getText())) { JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[6].getText()); gameOver(); return; } else if(button[0].getText().equals(button[3].getText()) &amp;&amp; button[3].getText().equals(button[6].getText())) { JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[0].getText()); gameOver(); return; } else if(button[1].getText().equals(button[4].getText()) &amp;&amp; button[4].getText().equals(button[7].getText())) { JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[1].getText()); gameOver(); return; } else if(button[1].getText().equals(button[4].getText()) &amp;&amp; button[4].getText().equals(button[7].getText())) { JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[1].getText()); gameOver(); return; } else if(button[2].getText().equals(button[5].getText()) &amp;&amp; button[5].getText().equals(button[8].getText())) { JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[2].getText()); gameOver(); return; } else if(button[0].getText().equals(button[4].getText()) &amp;&amp; button[4].getText().equals(button[8].getText())) { JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[0].getText()); gameOver(); return; } else if(button[2].getText().equals(button[4].getText()) &amp;&amp; button[4].getText().equals(button[6].getText())) { JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[2].getText()); gameOver(); return; } int i; for(i=0;i&lt;button.length;i++) { if(button[i].isEnabled()) { break; } } if(i == button.length) { JOptionPane.showMessageDialog(null,"This was a Draw"); } } </code></pre>
[]
[ { "body": "<p>Start with replacing common code with function calls.\nFor example, you can create a method for checking if an entire row has the same text:</p>\n\n<pre><code>bool checkRow(int row)\n{\n int col = row*3;\n return button[col].getText().equals(button[col+1].getText())\n &amp;&amp; button[col+1].getText().equals(button[col+2].getText());\n}\n</code></pre>\n\n<p>Write similar methods for columns and diagonal. Then you can do something like that:</p>\n\n<pre><code>bool checkWin()\n{\n for(int i=0; i&lt;3; i++)\n {\n if(checkRow(i))\n return true;\n if(checkCol(i))\n return true;\n }\n if(checkMajorDiag())\n return true;\n if(checkMinorDiag())\n return true;\n return false;\n}\n</code></pre>\n\n<p>And then your entire <code>if</code>-<code>else</code> chain will be replaced with:</p>\n\n<pre><code>if(checkWin())\n {\n JOptionPane.showMessageDialog(null,\"Thank you the winner is\" + button[2].getText());\n gameOver();\n return;\n }\n</code></pre>\n\n<p>The code is now much more readable.</p>\n\n<p>Two major points you'd want to remember:</p>\n\n<ol>\n<li><p><strong>Duplicate code leads to bugs</strong> </p>\n\n<p>Let's say you'd have to change the message printed to the user - when the message appears several times this task is tedious, plus in a real (big and complex) situation there's a good chance you'll forget to change one of the usages. In the new version, there's only one line to change.</p></li>\n<li><p><strong>Atomic operations are always better</strong> </p>\n\n<p>When I reviewed your code, I couldn't tell immediately what each <code>if</code> condition means.</p>\n\n<p><code>checkRow(0)</code> means \"check the first row\". <code>checkRow(0)</code> is an atomic operation (atomic in this context means a single operation - a single function call).</p>\n\n<p><code>button[0].getText().equals(button[1].getText()) &amp;&amp; button[1].getText().equals(button[2].getText())</code> is much less understandable. But the real danger here that if the line was <code>button[0].getText().equals(button[1].getText()) &amp;&amp; button[2].getText().equals(button[2].getText())</code>, you probably couldn't tell that one index was changed. Which means that debugging atomic operations is much easier.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-25T15:59:02.583", "Id": "116777", "Score": "0", "body": "But you always show button[2].getText() as the winner!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T21:27:48.813", "Id": "45100", "ParentId": "45097", "Score": "8" } }, { "body": "<p>+1 to <em>@opd</em> and a few other notes:</p>\n\n<ol>\n<li><p>You could extract out another method:</p>\n\n<pre><code>private boolean buttonTextEquals(int index1, int index2) {\n return button[index1].getText().equals(button[index2].getText());\n}\n</code></pre>\n\n<p>And use that in the <code>checkRow()</code>:</p>\n\n<pre><code>private boolean checkRow(int row) {\n int col = row * 3;\n return buttonTextEquals(col, col + 1) &amp;&amp; buttonTextEquals(col + 1, col + 2);\n}\n</code></pre></li>\n<li><p>You could use a more descriptive name here than <code>i</code>:</p>\n\n<blockquote>\n<pre><code>int i;\n</code></pre>\n</blockquote>\n\n<p>What's the purpose of this variable? Use that as a name.</p></li>\n<li><p>There were other <a href=\"https://codereview.stackexchange.com/search?q=tic+tac+toe+is%3Aquestion\">Tic-tac-toe questions</a> recently with great answer, you should check them.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T22:04:50.350", "Id": "45101", "ParentId": "45097", "Score": "5" } }, { "body": "<p>You have the <code>button[1]</code>, <code>button[4]</code> and <code>button[7]</code> check twice in your code! This is a 'classic' mistake when copy/pasting blocks:</p>\n\n<blockquote>\n<pre><code> else if(button[1].getText().equals(button[4].getText()) &amp;&amp; button[4].getText().equals(button[7].getText()))\n {\n JOptionPane.showMessageDialog(null,\"Thank you the winner is\" + button[1].getText());\n gameOver();\n return;\n }\n else if(button[1].getText().equals(button[4].getText()) &amp;&amp; button[4].getText().equals(button[7].getText()))\n {\n JOptionPane.showMessageDialog(null,\"Thank you the winner is\" + button[1].getText());\n gameOver();\n return;\n }\n</code></pre>\n</blockquote>\n\n<p>This is a case where a preset table of values will be helpful to test your conditions.</p>\n\n<p>Consider a structure which identifies what three buttons represent a winning condition:</p>\n\n<pre><code>private static final int[][] TRIPLES = {\n {0, 1, 2},\n {3, 4, 5},\n {6, 7, 8},\n\n {0, 3, 6},\n {1, 4, 7},\n {2, 5, 8},\n\n {0, 4, 8},\n {2, 4, 6}\n}\n</code></pre>\n\n<p>This array represents the buttons that you check for a winning condition (except <code>{1, 4, 7]</code> is only in here once ;-) )</p>\n\n<p>Now, with the above structure, consider the following loop:</p>\n\n<pre><code>for (int[] triple : TRIPLES) {\n int a = triple[0];\n int b = triple[1];\n int c = triple[2];\n if( button[a].getText().equals(button[b].getText())\n &amp;&amp; button[b].getText().equals(button[c].getText())) {\n\n JOptionPane.showMessageDialog(null,\n \"Thank you the winner is\" + button[a].getText());\n gameOver();\n return;\n\n }\n}\n</code></pre>\n\n<p>This checks all your conditions, and there is very little code duplciation. If you want to, you can extract out the button-checks as suggested by palacsint, but I find the above is quite readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T23:45:40.713", "Id": "45111", "ParentId": "45097", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T20:07:59.920", "Id": "45097", "Score": "10", "Tags": [ "java", "game", "validation", "tic-tac-toe" ], "Title": "Conditionals validation for Tic Tac Toe" }
45097
<p>I have nginx serving files with uwsgi and I wanted to lock my server down just to allow SSH and Nginx to run.</p> <pre><code>#!/bin/bash i=/sbin/iptables # Flush all rules $i -F $i -X # Setup default filter policy $i -P INPUT DROP $i -P OUTPUT DROP $i -P FORWARD DROP # Allow unlimited traffic on loopback $i -A INPUT -i lo -j ACCEPT $i -A OUTPUT -o lo -j ACCEPT # Open up ports for nginx $i -A INPUT -p tcp --dport 443 -j ACCEPT $i -A INPUT -p tcp --dport 80 -j ACCEPT $i -A INPUT -p tcp --dport 22 -j ACCEPT # Make sure nothing comes or goes out of this box $i -A INPUT -j DROP $i -A OUTPUT -j DROP </code></pre> <p>It's quite a minimal example but it looks like it would do the job. Are there any improvements to be had?</p>
[]
[ { "body": "<p>There is a miniscule chance of a failure between <code>/sbin/iptable -P INPUT DROP</code> and <code>/sbin/iptables -A INPUT -p tcp --dport 22 -j ACCEPT</code>. It really isn't likely, as there's not much that could go wrong, but it's theoretically possible. If you are remotely administering this server over SSH, then you might get locked out of your own machine. Therefore, I suggest deferring the following sequence of commands:</p>\n\n<ol>\n<li><code>/sbin/iptables -P {INPUT,OUTPUT} ACCEPT</code></li>\n<li><code>/sbin/iptables -F; /sbin/iptables -X</code></li>\n<li>Set up the rules</li>\n<li><code>/sbin/iptables -P {INPUT,FORWARD} DROP</code></li>\n</ol>\n\n<p>In contrast to @eckes, who worries about leaving the server vulnerable for a moment, I worry about possibly losing SSH access to it. If you are raising the firewall for the first time, my sequence introduces no new window of vulnerability. If you are reinitializing the firewall, the window of vulnerability between steps 1 and 3 would only be a split second, not enough for a meaningful attack.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T14:12:03.983", "Id": "78610", "Score": "0", "body": "Thank you for the reply @200_success. Are we saying move this line to the very bottom \"/sbin/iptable -P INPUT DROP\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T15:45:54.320", "Id": "78614", "Score": "0", "body": "@JamesWillson I've clarified my advice in the answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T23:05:24.460", "Id": "45109", "ParentId": "45098", "Score": "7" } }, { "body": "<p>In addition to other answers, I want to caution you about the blanket:</p>\n\n<blockquote>\n<pre><code> $i -A OUTPUT -j DROP\n</code></pre>\n</blockquote>\n\n<p>The following services should be running on your system and will need access:</p>\n\n<ul>\n<li>DNS</li>\n<li>NTP</li>\n<li>DHCP?</li>\n<li>others.</li>\n</ul>\n\n<p>It is my experience that blanket/policy DENY for outbound traffic requires a signfificant effort for maintenance. Are you prepared for that.</p>\n\n<p>Altough it is not the most secure view on the world, I don't think there is much point in restricting out-bound traffic. If a 'hacker' has gained enough access to your system to enable outbound systems you were not expecting, then the chances are that they can just open up your IPTables anyway. The frustration is not worth it.</p>\n\n<p><strong>Ping</strong> allow ping from inside and from outside</p>\n\n<pre><code>iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT\niptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T14:15:47.157", "Id": "78611", "Score": "1", "body": "Great point on the DNS. NTP and DHCP, thank you. I'll look into the outbound traffic" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T23:30:06.627", "Id": "45110", "ParentId": "45098", "Score": "6" } }, { "body": "<p>I typically recommend to first set the policy and then flush the rules. This reduces the chance that you flush all deny rules with a open policy (also it is unlikely). In order to reduce impact on sessions:</p>\n\n<ol>\n<li>set all chain policies to DROP</li>\n<li>flush rules, remove custom chains</li>\n<li>append new chains and rules</li>\n<li>(optionally depending on rules-*) change\npolicies to REJECT and/or RETURN</li>\n</ol>\n\n<p>Your rules will most likely not work as you need to allow the outgoing response packages to the incoming connections as well.</p>\n\n<p>-* i typically add explicit rules to deny packets because then I can see their counters.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T14:10:41.070", "Id": "78608", "Score": "0", "body": "Hi @eckes, thank you for the reply. So are you saying a should move the flush rules to below the \"# Setup default filter policy\" bit or instead all the way to the bottom. Would you also be kind enough to explain what you mean about the outgoing response packages please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:11:21.703", "Id": "78733", "Score": "0", "body": "@JamesWillson yes for security reasons setting up the policy should come before the flush. Optionally you can also do \"set policy to deny, flush rules, setup rules, set policy to reject\" This would avoid intermediate rejects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:12:47.490", "Id": "78736", "Score": "0", "body": "@JamesWillson I mean if you allow incoming packages to the SSH port you also need to allow the answer packages for this connection to go out. You typically do this with a state `established` rule. BTW: most distros have some sort of sample rules shipped, it is easier to expand on them." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T00:10:33.440", "Id": "45113", "ParentId": "45098", "Score": "7" } } ]
{ "AcceptedAnswerId": "45109", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T20:43:27.333", "Id": "45098", "Score": "11", "Tags": [ "bash", "linux", "iptables" ], "Title": "Iptables Lockdown" }
45098
<p>I'm developing a Chrome extension so I can use bleeding-edge technologies like flexbox:</p> <p><a href="http://jsfiddle.net/VhZS5/14/" rel="nofollow">jsfiddle</a></p> <p><strong>HTML:</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;label for="example-search"&gt;Classic search example&lt;/label&gt; &lt;div class="input-wrapper"&gt; &lt;input type="text" id="example-search" /&gt; &lt;button&gt;Search&lt;/button&gt; &lt;/div&gt; </code></pre> <p><strong>CSS (cleared to highlight flexbox):</strong></p> <pre class="lang-css prettyprint-override"><code>.input-wrapper { display: flex; flex-flow: row nowrap; } .input-wrapper &gt; input { flex: 1 1 auto; } .input-wrapper &gt; button { flex-shrink: 0; } </code></pre> <p>I have two questions:</p> <ol> <li>Is this the right way to work with flexbox?</li> <li>Is there is a way to gracefully degrade this to use in websites?</li> </ol> <p>Using flexbox for production:</p> <p>I recently found a great article about my issue: <a href="http://www.planningforaliens.com/blog/2014/03/11/real-world-flexbox/" rel="nofollow">flexbox in the real world</a></p> <p>Raw insigsts from atricle:</p> <ul> <li>use autoprefixer to support all old desktop and mobile browsers (they use old flexbox model syntax)</li> <li>use progressive enhancement for IE8- (see <a href="http://www.planningforaliens.com/blog/2014/03/11/real-world-flexbox/#scenario_3_you_have_to_support_ie8_but_it_doesnt_have_to_look_as_nice" rel="nofollow">Scenario 3</a> from article)</li> </ul>
[]
[ { "body": "<p>Unless you're overwriting properties set elsewhere, there's no reason for this line because this is the default for all flex containers:</p>\n\n<pre><code>flex-flow: row nowrap;\n</code></pre>\n\n<p>If your goal is to make this work on browsers with either of the old Flexbox implementations, there are 2 things to be aware of:</p>\n\n<ul>\n<li>The March 2012 draft (IE10) does not have individual properties for flex-grow, flex-shrink, or flex-basis. The only way to control them is via the flex shorthand.</li>\n<li>The original draft does not allow you to have differing flex-shrink and flex-grow values. It would be ok to translate <code>flex: 1 1 auto</code> to <code>box-flex: 1</code>, but you can't translate something like <code>flex: 1 0</code> (with prefixes). For your purpose, <code>box-flex: 0</code> should work (though you might have problems with buttons in old Webkit browsers, see: <a href=\"https://stackoverflow.com/questions/16961192/flexbox-doesnt-work-with-buttons\">https://stackoverflow.com/questions/16961192/flexbox-doesnt-work-with-buttons</a>).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T09:55:07.463", "Id": "78595", "Score": "0", "body": "Thanks, @cimmanon. \n Do you have any example for production ready solution? \n \n It's not hard to add some old properties and add flexbox model v. 2009 for old Chrome/Firefox/Opera/Mobile, but what to do with IE?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T22:24:33.977", "Id": "78844", "Score": "0", "body": "You've already shown you know how to use the flex shorthand, I didn't think I needed to add it: `flex: 0 1 auto` instead of `flex-shrink: 0`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T08:37:25.227", "Id": "78880", "Score": "0", "body": "I prefer to use property directly for clarifying what i want to achieve. `flex-shrink: 0` explicitly says to me that button wouldn't shrink." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T09:14:49.787", "Id": "78888", "Score": "1", "body": "Er, guess I meant `flex: 1 0 auto`. Unfortunately, you don't have a choice if you want to cover all of your bases: IE10 doesn't have a flex-shrink property, you *have* to use flex instead." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T00:50:05.520", "Id": "45116", "ParentId": "45099", "Score": "6" } } ]
{ "AcceptedAnswerId": "45116", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T20:47:12.437", "Id": "45099", "Score": "11", "Tags": [ "html", "css" ], "Title": "Input group with flex box" }
45099
<ul> <li><a href="https://en.wikipedia.org/wiki/Tic-tac-toe" rel="nofollow">Tic-tac-toe on Wikipedia</a></li> <li><a href="http://stackoverflow.com/tags/tic-tac-toe/info">Stack Overflow tag wiki</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T22:07:52.933", "Id": "45102", "Score": "0", "Tags": null, "Title": null }
45102
Tic Tac Toe is a popular exercise for beginning coders, as the finite resources and game mechanics can be easily grasped and represented in many ways. As it is a short game, it is possible to create an algorithm that never loses.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T22:07:52.933", "Id": "45103", "Score": "0", "Tags": null, "Title": null }
45103
<p>I am attempting problem 7 on Project Euler. I have come up with this solution which works fine for finding smaller nth prime numbers, but really lags when it comes to higher nth prime numbers. I am not quite sure where to start to make it more efficient.</p> <pre><code>public class TenThousandFirstPrime { public static boolean isPrime(int num) { if(num % 2 == 0) return false; for(int i = 3; i &lt; Math.floor(Math.sqrt(num)); i += 2) { if(num % i == 0) return false; } return true; } public static void main(String[] args) { int count = 2; int i = 3; while(count &lt;= 10001) { if(isPrime(i)) { i += 2; count++; } } System.out.println(i); } } </code></pre> <p>The solution only took a couple of minutes and I didn't expect it to be as slow as it is...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T01:28:28.067", "Id": "78563", "Score": "4", "body": "Re. how to make it faster, that's probably been explained in answers to some of the [other questions about prime numbers](http://codereview.stackexchange.com/questions/tagged/primes)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T06:49:10.823", "Id": "78585", "Score": "0", "body": "Use solutions to previously solved problems to solve new problems. Suppose you want to know if 12347 is prime. If you have already computed the prime numbers less than or equal to root 12347, then you only need to check whether 12347 is divisible by each of them, not all the numbers up to the root." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T06:56:32.537", "Id": "78586", "Score": "0", "body": "Skipping every other number is smart. You could be smarter by starting i at 12, increasing by 6 each time, and then checking i-1 and i-5 for primeness in the loop. Clearly i, i-2, i-3 and i-4 are divisible by either 2 or 3." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T08:54:47.013", "Id": "78590", "Score": "1", "body": "\"I didn't expect it to be as slow as it is\" -- The **infinite loop** identified in 200_success' answer and [Jamal's comment](http://codereview.stackexchange.com/questions/45115/ten-thousand-and-first-prime-checker-takes-a-very-long-time#comment78572_45123) explains why it's slower than slow (i.e. endless)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T08:57:44.087", "Id": "78591", "Score": "1", "body": "I've noticed that you use `i += 2;`, probably because you've eliminated all multiples of 2 from the possible prime numbers. Why only for 2? Why not take that to its logical conclusion, and eliminate all multiples of every prime number you find? That's what the Sieve of Eratosthenes does - you should look into that if you want a faster prime number generator." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T16:26:16.093", "Id": "78622", "Score": "0", "body": "The Project Euler website lays out in great detail a fast solution to this problem as soon as you solve the problem the first time... (just fyi)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T19:01:04.833", "Id": "78633", "Score": "0", "body": "Here's something I posted several years ago: http://stackoverflow.com/a/1134851/109122. It actually calculate Euler's Totient values (PHI), but as a side effect, it finds all of the primes up to some N quite fast. It's based on a wheeled Sieve of Eratosthenes and takes 3 secs to get to 1 million, and that's doing all of the extra work for the Totients. Take them out and it would be much faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T19:26:56.890", "Id": "78822", "Score": "0", "body": "@RedAlert Thank you, I ended up using the Sieve of Eratosthenes and it did it in just over 15 milliseconds." } ]
[ { "body": "<p>The square root calculation could just be done before the loop. Since this value does not change within the function, it doesn't need to be recalculated each time through the loop.</p>\n\n<pre><code>public static boolean isPrime(int num) {\n if (num % 2 == 0) return false;\n\n int squareRoot = Math.floor(Math.sqrt(num));\n for (int i = 3; i &lt; squareRoot; i += 2) {\n if (num % i == 0) return false;\n }\n\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T01:34:31.983", "Id": "78564", "Score": "1", "body": "Answer to [this question](http://stackoverflow.com/q/6093537/49942) suggest your answer is correct: that the repeated `sqrt` isn't optimized away by the JVM." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T01:21:22.957", "Id": "45120", "ParentId": "45115", "Score": "6" } }, { "body": "<p>I think you need <code>&lt;=</code> in isPrime's for loop: because otherwise you'll decide that 25 is prime.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T01:57:57.280", "Id": "78567", "Score": "0", "body": "Moreover, you probably want to replace `floor` with `ceil`; due to the limited precision of floating point, `Math.sqrt(25)` could return `4.99999996` or something similar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T02:04:53.237", "Id": "78568", "Score": "1", "body": "@NateEldredge [This document](http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#sqrt(double)) says, \"the result is the double value closest to the true mathematical square root of the argument value\" ... so perhaps the result is exact (an integer value) if the argument is a perfect square." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T03:26:58.387", "Id": "78570", "Score": "0", "body": "Ok, true, assuming that your floating point implementation is able to represent small integers exactly (which most are)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T01:26:09.800", "Id": "45121", "ParentId": "45115", "Score": "4" } }, { "body": "<p>Your code does not work. Your <code>main()</code> has an infinite loop.</p>\n\n<p>Trial division is a simple way to test whether a single number is prime. However, to test many numbers, you want to use the Sieve of Eratosthenes.</p>\n\n<p>You <code>isPrime()</code> reports that 1 is prime and 2 is not. That might be acceptable if you take care to never call it with those parameters and <strong>document those special cases in JavaDoc.</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T03:32:21.737", "Id": "78571", "Score": "1", "body": "1. I don't see the infinite loop in `main`? 2. The Sieve of Eratosthenes would work well here, but there's the question of knowing in advance how large to make your table of candidates. Also it would require O(n) memory instead of O(1) as for trial division. 3. That's a good point about `isPrime`, but you'll notice that in fact it is only ever called with `num >= 3`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T04:31:14.803", "Id": "78572", "Score": "3", "body": "@NateEldredge: `count` is only incremented if `isPrime()` returns true. Once the `while` loop gets a non-prime number (4 being the first one), the `if` will be skipped, so `count` will not increment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T04:45:17.593", "Id": "78575", "Score": "1", "body": "@Jamal Actually, `i` will get stuck at 9." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T05:08:48.403", "Id": "78576", "Score": "0", "body": "@NateEldredge 2. The _n_ th prime is approximately [_n_ ln _n_](http://en.wikipedia.org/wiki/Prime_number#Number_of_prime_numbers_below_a_given_number); it turns out that for 10000, this estimate is about 12% too low, but still it's a useful guide. In my opinion, using 100 kB for the sieve is a worthwhile expense. 3. Avoiding the erroneous cases of `isPrime()` is fine, but my point is that failure to document those cases is poor practice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T13:09:49.310", "Id": "78604", "Score": "1", "body": "Nate, at the point where you have so many primes that the memory matters, you would use consecutive sieves, for example make a sieve for the primes from 1 to 1 million, another for primes from 1 million to 2 millions, and so on, to keep memory use under control." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T02:55:15.503", "Id": "45123", "ParentId": "45115", "Score": "5" } }, { "body": "<p>Unless your compiler is quite clever, it will calculate Math.floor (Math.sqrt (num)) on every single iteration of the loop, which will probably take three times longer than the rest of the operations. </p>\n\n<p>\"i &lt; Math.floor (Math.sqrt (num))\" is really, really bad. It makes your code think that squares of primes are prime (for example 9, 25, 49), but also products of consecutive twin primes, like 15 = 3x5, 35 = 5x7, 143 = 11x13 and so on. </p>\n\n<p>As mentioned, the loop in main stops making progress when it reaches the first non-prime. I would write the loop in the most straightforward way: </p>\n\n<pre><code>for (int i = 3; ; i += 2)\n{\n if (isPrime (i))\n {\n // Whatever you want to do with primes\n }\n}\n</code></pre>\n\n<p>And in general, I wouldn't put lots of code into main (). main () should in my opinion process any parameters, then call code doing the work. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T13:04:51.417", "Id": "45139", "ParentId": "45115", "Score": "0" } }, { "body": "<p>In your code, the i+=2 should be outside the if statement, otherwise it gets stuck on the first non prime number:</p>\n\n<pre><code> i += 2;\n if(isPrime(i)) {\n count++;\n }\n</code></pre>\n\n<p>Moving the sqrt calculation outside is one option, another one is to test for the square value like this because a multiplication is not as expensive as the square root calculation:</p>\n\n<pre><code>for(int i = 3; i*i &lt; num ; i+=2)\n</code></pre>\n\n<p>For testing why it is slow start with printing out the result of every while iteration, so you can if it just gets slower with larger numbers or if it gets stuck somewhere.</p>\n\n<p>You could also try to work with BigInteger and another algorithm, this one takes around 5 seconds on my old PC and it should work fine with larger numbers too.</p>\n\n<pre><code>import java.math.BigInteger;\nimport java.util.Date;\n\npublic class Euler7\n{\n public static void main(String[] args)\n {\n System.out.println(new Date());\n BigInteger primesProduct = BigInteger.valueOf(2*3);\n BigInteger primesFound = BigInteger.valueOf(2);\n BigInteger testForPrime = BigInteger.valueOf(3);\n BigInteger limit = BigInteger.valueOf(10001);\n while(primesFound.compareTo(limit)&lt;0)\n {\n testForPrime = testForPrime.add(BigInteger.valueOf(2));\n if(((primesProduct.gcd(testForPrime)).compareTo(BigInteger.ONE))==0)\n {\n primesProduct = primesProduct.multiply(testForPrime);\n primesFound = primesFound.add(BigInteger.ONE);\n }\n }\n System.out.println(new Date());\n System.out.println(\"found: \"+testForPrime);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T16:53:48.870", "Id": "45148", "ParentId": "45115", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T00:44:19.467", "Id": "45115", "Score": "8", "Tags": [ "java", "performance", "primes", "programming-challenge" ], "Title": "Ten thousand and first prime checker takes a very long time" }
45115
<p>I just tried BDD for the first time and implemented a simple <a href="http://semver.org/" rel="nofollow noreferrer">Semantic Versioning</a> Bumper in Python.</p> <p>The class takes a version string in the format of <strong>major.minor.patch</strong> (i.e. 3.2.2, where major=3, minor=2, patch=2). Then you can bump a level, say <strong>patch</strong>, and you'd get 3.2.3. If you bump <strong>minor</strong>, you'd get 3.3.0 and if you bump <strong>major</strong>, you'd get 4.0.0.</p> <p>For the BDD, I followed this workflow:</p> <p><img src="https://i.stack.imgur.com/uG7Do.jpg" alt="enter image description here"></p> <p>I wrote a high-level features file, then wrote the unit tests and then refactored until everything was working.</p> <p>My problem is that both the unit tests and the acceptance tests are testing the same things, which doesn't feel right to me, but I don't know where to draw the line.</p> <p>The code is not too complex so someone who is not too familiar with Python should be able to understand what's going on as well.</p> <p>I would love to hear feedback regarding the implementation of my tests (or the actual code too, but mainly the tests). </p> <p><a href="https://github.com/vortec/versionbump/blob/master/tests/features/bump.feature" rel="nofollow noreferrer">This is the feature file</a>:</p> <pre><code>Feature: Bump version strings Scenario: Increase patch version Given the version 0.1.2 When we bump patch Then version is 0.1.3 Scenario: Increase minor version Given the version 0.1.2 When we bump minor Then version is 0.2.0 Scenario: Increase major version Given the version 0.1.2 When we bump major Then version is 1.0.0 </code></pre> <p><a href="https://github.com/vortec/versionbump/blob/master/tests/features/steps/bump_steps.py" rel="nofollow noreferrer">This is the steps file</a>:</p> <pre><code>@given('the version {version}') def step_impl(context, version): context.versionbump = VersionBump(version) @when('we bump {level}') def step_impl(context, level): context.versionbump.bump(level) @then('version is {version}') def step_impl(context, version): context.versionbump.get() == version @then('{level} is {number:d}') def step_impl(context, level, number): assert context.versionbump.get(level) == number </code></pre> <p><a href="https://github.com/vortec/versionbump/blob/master/tests/unit/test_versionbump.py" rel="nofollow noreferrer">These are the unit tests</a>:</p> <pre><code>def test_same_version_after_parsing(vb): assert vb.get_version() == '2.0.1' def test_level_access(vb): assert vb.get_level('major') == 2 assert vb.get_level('minor') == 0 assert vb.get_level('patch') == 1 def test_bump(): vb = VersionBump('2.0.1') vb.bump() assert vb.get('patch') == 2 def test_zeroize(): vb = VersionBump('1.2.3') vb.zeroize_after_level('major') assert vb.get_version() == '1.0.0' def test_invalid_version(): with pytest.raises(ValueError): VersionBump('2.0.1.0') def test_get_invalid_level(vb): with pytest.raises(KeyError): vb.get_level('foo') def test_bump_invalid_level(): vb = VersionBump('2.0.1') with pytest.raises(KeyError): vb.bump('foo') </code></pre> <p><a href="https://github.com/vortec/versionbump/blob/master/versionbump/versionbump.py" rel="nofollow noreferrer">And here is the code</a>:</p> <pre><code>_LEVELS = ['major', 'minor', 'patch'] _REGEX = re.compile('^(?P&lt;major&gt;[0-9]+)' '\.(?P&lt;minor&gt;[0-9]+)' '\.(?P&lt;patch&gt;[0-9]+)$') class VersionBump(object): def __init__(self, version): self.version_info = self.parse(version) def bump(self, level='patch'): """ Bump version following semantic versioning rules. """ self.version_info[level] += 1 self.zeroize_after_level(level) def zeroize_after_level(self, base_level): """ Set all levels after ``base_level`` to zero. """ index = _LEVELS.index(base_level) + 1 for level in _LEVELS[index:]: self.version_info[level] = 0 def get(self, level=None): """ Return complete version string if called with no parameters. Return value of given level if ``level`` is given. """ if level: return self.get_level(level) else: return self.get_version() def get_version(self): """ Return complete version string. """ version = '{major}.{minor}.{patch}'.format(**self.version_info) return version def get_level(self, level): """ Return value of given level. """ return self.version_info[level] def parse(self, version): match = _REGEX.match(version) if match is None: raise ValueError('Invalid version: {}'.format(version)) version_info = {} for level, number in match.groupdict().iteritems(): if number: version_info[level] = int(number) else: version_info[level] = None return version_info </code></pre>
[]
[ { "body": "<p>Your problem seems to arise due to the fact, that your project is build from only one class (= unit).</p>\n\n<p>With acceptance tests you test a non-programmers view of your project, that is whether it fullfills given requirements. Acceptance tests are formulated in a style of someone who actually uses features of your program and has no insights on what is going on behind the scenes.</p>\n\n<p>With unit tests you test parts inside your program, which helps you (as a programmer) to verify, that single parts of your program work as expected. You could of course test functionality which the user of your program never gets to see directly.</p>\n\n<p>Since your program has only one unit, your acceptance and unit tests are similar, but formulated differently. If your program was build from different units, the tests would indeed look more different.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:24:04.553", "Id": "45199", "ParentId": "45118", "Score": "2" } }, { "body": "<blockquote>\n <p>Unit Tests were created for the benefit of programmers, programmer\n were not created for the benefit of for unit tests.</p>\n</blockquote>\n\n<p>So if writing unit tests don’t help you writing the code then don’t write unit tests for code that is tested by acceptance tests.</p>\n\n<p>However unit tests help you developer the API to your class and provides examples of how to use the class, so may be of value even when you already have 100% test coverage.</p>\n\n<p>On a normal sized code base, it may also be quicker to track down way a unit test if failing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T14:38:06.387", "Id": "78756", "Score": "0", "body": "What do you consider a normal sized code base?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:12:59.457", "Id": "78770", "Score": "0", "body": "@Fabian, at least 3 man months of coding, most often many man years of coding." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T13:55:43.097", "Id": "45216", "ParentId": "45118", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T01:03:02.403", "Id": "45118", "Score": "5", "Tags": [ "python", "unit-testing", "bdd" ], "Title": "First time BDD: Testing the same things in both acceptance and unit tests" }
45118
<p>I am trying to understand the concepts of <code>friend</code> functions, overloaded operators, and inheritance in C++. I am very confused on the specifics used for coding, since I am fairly new in programming, and working in the Visual Studio C++ environment in writing code. </p> <p>The following is the project details for writing a program in Visual Studio C++: </p> <blockquote> <p>Design a <code>PhoneCall</code> class that holds a phone number to which a call is placed, the length of the call in minutes, and the rate charged per minute. Overload extraction and insertion operators for the class. In this program, overload the <code>==</code> operator to compare two <code>PhoneCall</code>s. Consider one <code>PhoneCall</code> to be equal to another if both calls are placed to the same number. Also, create a <code>main()</code> function that allows you to enter ten <code>PhoneCall</code>s into an array. If a <code>PhoneCall</code> has already been placed to a number, do not allow a second <code>PhoneCall</code> to the same number.</p> </blockquote> <p>I really need some feedback on the following code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; class PhoneCall { private: string phonenumber; double perminuterate; double calldurationminutes; public: bool operator==( const PhoneCall &amp;n ) const; friend ostream &amp; operator&lt;&lt;( ostream &amp;f, const PhoneCall &amp;n ); friend istream &amp; operator&gt;&gt;( istream &amp;f, PhoneCall &amp;n ); }; bool PhoneCall::operator==( const PhoneCall &amp;n ) const { return phonenumber == n.phonenumber; }; ostream &amp; operator&lt;&lt;( ostream &amp;f, const PhoneCall &amp;n ) { f &lt;&lt; "Phone number: " &lt;&lt; n.phonenumber &lt;&lt; ", Duration: " &lt;&lt; n.calldurationminutes &lt;&lt; " minutes, Rate: " &lt;&lt; n.perminuterate &lt;&lt; endl; return f; } istream &amp; operator&gt;&gt;( istream &amp;f, PhoneCall &amp;n ) { f &gt;&gt; n.phonenumber; f &gt;&gt; n.calldurationminutes; f &gt;&gt; n.perminuterate; return f; } int main( ) { PhoneCall a[10]; cout &lt;&lt; "Enter 10 phone numbers, duration in minutes, and the per-minute rates." &lt;&lt; endl &lt;&lt; "Separate each with a space and then hit enter to complete it." &lt;&lt; endl; for ( int i= 0; i &lt; 10; ) { cin &gt;&gt; a[i]; int j; for ( j= 0; j &lt; i; ++j ) if ( a[i] == a[j] ) { cout &lt;&lt; "Duplicate number information ignored. Try again." &lt;&lt; endl; break; } if ( j == i ) ++i; } for ( int i= 0; i &lt; 10; ++i ) cout &lt;&lt; a[i]; system("pause"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T06:09:49.173", "Id": "78579", "Score": "3", "body": "Your indentation is very inconsistent. Four spaces is preferred. One space in `main()` is a little strange." } ]
[ { "body": "<pre><code>using namespace std; \n</code></pre>\n\n<p>This is generally frowned upon, especially at the \"global\" level like this. Since you don't know what names might be defined inside <code>namespace std</code>, this has the potential to create conflicts with your code.</p>\n\n<pre><code>class PhoneCall { \nprivate: \n</code></pre>\n\n<p>Although it's harmless, the <code>private:</code> here is redundant--members of a <code>class</code> are private by default.</p>\n\n<pre><code> string phonenumber; \n double perminuterate; \n double calldurationminutes; \n</code></pre>\n\n<p>I think I'd rename these to something like:</p>\n\n<pre><code>string phone_number;\ndouble per_minute_rate;\ndouble call_duration_minutes;\n</code></pre>\n\n<p>If <em>at all</em> possible, I'd use an <code>std::vector</code> instead of a \"raw\" array, so this:</p>\n\n<pre><code> PhoneCall a[10]; \n</code></pre>\n\n<p>...would turn into something like:</p>\n\n<pre><code>std::vector&lt;PhoneCall&gt; a(10);\n</code></pre>\n\n<p><code>std::endl</code> is drastically overused. I'd generally just use <code>'\\n';</code>. <code>endl</code> also flushes the file's buffer, which you rarely want. When you read/write <code>cin</code> and <code>cout</code>, flushes are done automatically between writing and reading anyway.</p>\n\n<pre><code> cout &lt;&lt; \"Enter 10 phone numbers, duration in minutes, and the per-minute rates.\" &lt;&lt; \n endl &lt;&lt; \"Separate each with a space and then hit enter to complete it.\" &lt;&lt; endl; \n for ( int i= 0; i &lt; 10; ) { \n cin &gt;&gt; a[i]; \n int j; \n for ( j= 0; j &lt; i; ++j ) \n if ( a[i] == a[j] ) { \n cout &lt;&lt; \"Duplicate number information ignored. Try again.\" &lt;&lt; endl; \n break; \n } \n if ( j == i ) ++i; \n } \n</code></pre>\n\n<p>You might want to use <code>std::find</code> to find whether the array already contains an instance of a particular phone number. This could simplify your logic quite a bit.</p>\n\n<p>When you print out your phone call objects:</p>\n\n<pre><code> for ( int i= 0; i &lt; 10; ++i ) \n cout &lt;&lt; a[i];\n</code></pre>\n\n<p>...you traditionally want to only print out the data itself in your <code>operator&lt;&lt;</code>, and leave any final new-line to separate one object from the next to be printed somewhere else (like right here).</p>\n\n<pre><code> system(\"pause\");\n</code></pre>\n\n<p>I'd avoid this, and use something like:</p>\n\n<pre><code>std::cout &lt;&lt; \"Press return to quit.\"\nchar ch;\nstd::cin.get(ch);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T11:53:02.757", "Id": "78600", "Score": "0", "body": "Everything he said. The only difference is that I woudl use camel case notation for variable names: `calldurationminutes` => `callDurationMinutes`;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T21:05:02.863", "Id": "78831", "Score": "0", "body": "How about `std::cin.ignore();` instead of `char ch; std::cin.get(ch);`?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T06:21:44.573", "Id": "45129", "ParentId": "45127", "Score": "5" } }, { "body": "<p>Apart from Jerry's remarks, I would also provide an <strong><code>operator!=</code></strong> to go along with <code>operator==</code> (implementing the former in terms of the latter to avoid code duplication), and make both operators <strong>non-member <code>friend</code></strong> functions. </p>\n\n<p>One advantage is that non-member functions treat left/right arguments symmetrically and avoid tricky argument conversion ambiguities when you have single-argument constructors (not the case in this example, but it's a good habit to get into).</p>\n\n<p>If you have to overload other operators, there is even a <a href=\"http://www.boost.org/doc/libs/1_55_0/libs/utility/operators.htm\" rel=\"nofollow noreferrer\"><strong>Boost.Operators</strong></a> library to help you do this automatically if you overload (overkill for this example, though).</p>\n\n<p>Finally, I prefer writing <code>ArgType const&amp; argname</code> because <code>const</code> applies right-to-left. </p>\n\n<pre><code>class PhoneCall \n{ \npublic:\n//....\n friend bool operator==(PhoneCall const&amp; L, PhoneCall const&amp; R)\n {\n return L.phone_number == R.phone_number; \n }\n\n friend bool operator!=(PhoneCall const&amp; L, PhoneCall const&amp; R)\n {\n return !(L == R);\n } \n };\n</code></pre>\n\n<p>Further reading: <a href=\"https://stackoverflow.com/questions/4421706/operator-overloading\"><strong>the Operator Overloading Q&amp;A</strong></a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T14:49:30.420", "Id": "45219", "ParentId": "45127", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T06:00:02.473", "Id": "45127", "Score": "5", "Tags": [ "c++", "beginner", "operator-overloading" ], "Title": "Overloading operators in PhoneCall class" }
45127
<p>This is a hard question for me to ask, because I don't really know how to explain it. So, please, bear with me.</p> <p>Bootstrap menu, as I know, has 2 modes: "desktop" mode "phone/tablet" mode. The desktop mode is anything above 767px width, and the later is anything below or equal (to 767px).</p> <p>Easy, we copy the navbar example out of Bootstrap's site. And then we can see that the core of the menu looks something like this:</p> <pre><code>&lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="#"&gt;Brand&lt;/a&gt; &lt;/div&gt; </code></pre> <p>And something like this:</p> <pre><code>&lt;ul class="nav navbar-nav"&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>As we can see, the collapsing of the menu is set to the button that appears when the "phone/tablet" mode view is open, and that is fine, but the problem starts when we see that the menu doesn't collapse when we click on a link.</p> <p>So I manage to solve it by adding the following attributes to each of the "a" elements:</p> <pre><code>data-toggle="collapse" data-target=".navbar-collapse" </code></pre> <p>Now it looks ugly(er) ... like this:</p> <pre><code>&lt;ul class="nav navbar-nav"&gt; &lt;li class="active"&gt; &lt;a href="#" data-toggle="collapse" data-target=".navbar-collapse"&gt;Link&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#" data-toggle="collapse" data-target=".navbar-collapse"&gt;Link&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>But now, the problem is worst! When we click on a link and we are not on the "phone" view, we can see that the menu kind of collapses and then displays again.</p> <p>So I see this solution as a workaround (not as a real fix), and to the eye of the developer (in this case.. me) very, very ugly.</p> <p>So I solved it the next way:</p> <p>With the project I'm working with, I have implemented the publish and subscribe pattern, which is not from this subject so I won't go into a dip explanation of it, but basically:</p> <p>This will subscribe a function to a "topic name":</p> <pre><code>$.Topic(topicName).subscribe(function(){...}); </code></pre> <p>And this will publish a topic to execute the functions(handlers/callbacks) that were subscribed to that topic:</p> <pre><code>$.Topic(topicName).publish(arguments); </code></pre> <p>That being said, the code I want to review is the following. Maybe there is already a better way, but this way has worked for me.</p> <p>I first added an ID to the <code>ul</code> element that holds the links to get an easy access, this way:</p> <pre><code>&lt;ul id="navbar-links" class="nav navbar-nav"&gt; ... &lt;/ul&gt; </code></pre> <p>I subscribe to a topic called "resize":</p> <pre><code>$.Topic("resized").subscribe(function (){ var width = $(window).width(); // the current width of the window if(width &gt; 767/*pixels*/){ // Not a phone nor a tablet $("#navbar-links a").attr("data-toggle", ""); // does not collapse $("#navbar-links a").attr("data-target", ""); // does not even have a target to collapse } else { // The opposite $("#navbar-links a").attr("data-toggle", "collapse"); $("#navbar-links a").attr("data-target", ".navbar-collapse"); } }); </code></pre> <p>What really does the trick is (thanks to jQuery and events of course):</p> <pre><code> $(window).on("resize", function(){ $.Topic("resized").publish(); }); $.Topic("resized").publish(); </code></pre> <p>Let me know what you think of that code.</p> <p>Just in case you are wondering for the implementation of the publish and subscribe: </p> <pre><code>var topics = {}; jQuery.Topic = function( id ) { var callbacks, method, topic = id &amp;&amp; topics[ id ]; if ( !topic ) { callbacks = jQuery.Callbacks(); topic = { publish: callbacks.fire, subscribe: callbacks.add, unsubscribe: callbacks.remove }; topics[ id ] = topic; } return topic; }; </code></pre> <p>Obviously it is encapsulated inside a module so the "topics" variable remains "private".</p>
[]
[ { "body": "<p>Actually, there's sort of a built in way to do this. Just attach a click handler to the links in your .navbar-nav and call the collapse hide method on the navbar-collapse class:</p>\n\n<pre><code>$('.navbar-nav').on('click', 'li a', function() {\n $('.navbar-collapse').collapse('hide');\n});\n</code></pre>\n\n<p>Oh yeah, and you don't have to worry about it when the nav isn't collapsed, so you don't have to listen for the resize event or anything. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-10T16:06:17.397", "Id": "53898", "ParentId": "45134", "Score": "3" } }, { "body": "<p>The answer suggested by jmel1 caused problems for me. Everything is fine when the menu was in a \"collapsible\" state, i.e. on narrow pages. However, on wide pages, it seemed to cause glitches in the display of the un-collapsed menu. </p>\n\n<p>Instead, I found this works well: </p>\n\n<pre><code>$('.navbar-collapse a').click('li', function() {\nvar navbar_toggle = $('.navbar-toggle');\nif (navbar_toggle.is(':visible')) {\n navbar_toggle.trigger('click');\n}});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T14:57:12.310", "Id": "103233", "Score": "0", "body": "Is this a correction of the OP code or of @jmel1 answer ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T15:23:05.067", "Id": "103242", "Score": "0", "body": "An improvement (hopefully) of @jmel1's answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T15:29:25.823", "Id": "103244", "Score": "0", "body": "The reason I'm asking this it's because an answer should be about the question code not another answer on the same question. But it's seems to me your code is not only directed at @jme11 answer, but is still \"reviewing\" op code. (it's jme11 not jmel1 ;) )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T15:47:50.163", "Id": "103252", "Score": "1", "body": "To be clear, from the original question, \"the problem starts when we see that the menu doesn't collapse when we click on a link.\"\n\nJme11's code addresses that issue. However, it's not perfect, because it also introduces glitches at widths above the 767px breakpoint. \n\nMy code addresses the same problem, in a manner *similar* to that of jme11, yet without the glitches at wider breakpoints. \n\nSo, I've answered the original question/problem, whilst giving due credit to jme11 for his approach. \n\nSo, what's the problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T15:48:59.687", "Id": "103253", "Score": "0", "body": "There is no problem I just wanted to make sure ;) ! Sorry if I wasn't clear enough in my comment. I should have added \" so this answer is not \"off-topic\"\" at the end of my comment." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T14:26:05.000", "Id": "57682", "ParentId": "45134", "Score": "3" } }, { "body": "<p>What I found the most \"clean\" solution is to use Bootstraps <code>data-toggle</code>, the trick is to add <code>.in</code> to <code>data-target</code>. So the link would look something like this</p>\n\n<pre><code>&lt;li&gt;&lt;a href=\"/help\" data-toggle=\"collapse\" data-target=\"#my_subnav.in\"&gt;Help&lt;/a&gt;&lt;/li&gt;\n</code></pre>\n\n<p>The <code>in</code> class is added to your collapsible navbar, when you expand it on smaller screens. So you can avoid the unwanted collapsing and showing again on larger viewports.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-22T18:04:52.237", "Id": "87679", "ParentId": "45134", "Score": "3" } } ]
{ "AcceptedAnswerId": "53898", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T08:36:43.047", "Id": "45134", "Score": "3", "Tags": [ "javascript", "jquery", "twitter-bootstrap" ], "Title": "Twitter Bootstrap collapsing ONLY \"phone view\" navbar menu on click" }
45134
<p>This game is similar to a Dungeons and Dragons game. How could I improve the efficiency of the program? For example, where can I add functions, records etc? This is for a school Controlled Assessment so any help would really be appreciated.</p> <pre><code>import random play1 = True str1 = int(input("Enter a value for strength")) print("you have chosen",str1,) skl1=int(input("Please enter a value of skill, and then press enter")) print("you have chosen: ",skl1,) str2 =int(input("Enter a value for strength")) print("you have chosen: ",str2,) skl2=int(input("Please enter a value of skill, and then press enter")) print("you have chosen: ",skl2,) strdif=str1-str2 if strdif&lt;0: strdif=str2-str1 strdif=strdif//5 skldif=skl1-skl2 if skldif&lt;0: skldif=skl2-skl1 skldif=skldif//5 while play1 == True: num1=random.randint(1,6) num2=random.randint(1,6) if num1&gt;num2: str1+=strdif skl1+=skldif str2-=strdif skl2-=skldif if num2&gt;num1: str2+=strdif skl2+=skldif str1-=strdif skl1-=skldif if skl1&lt;0: skl1=0 if skl2&lt;0: skl2=0 if str1&lt;=0: play1 = False print("Character 2 Won the game") elif str2&lt;=0: play1 = False print("Character 1 Won the game") if str1 &gt; str2: print("Character 1 won the encounter, now has",str1,"strength and",skl1,"skill") print("Character 2 lost the encounter, now has",str2,"strength and",skl2,"skill") else: print("Character 2 won the encounter, now has",str2,"strength and",skl2,"skill") print("Character 1 lost the encounter, now has",str1,"strength and",skl1,"skill") </code></pre>
[]
[ { "body": "<p>I don't see any performance bottlenecks in the traditional sense. Namely I don't see any tight loops that have to do a lot of work where you are likely to be waiting for the computer to finish. Instead what I see are a lot of small opportunities for you to make the code a little easier to read. Here I'll go over a few ways you might approach doing so:</p>\n<h3>Finding alternate ways to perform arithmetic</h3>\n<p>After getting strength and skill values from the person running the program, you compute the difference between the values entered. If it's negative, you invert it, and then divide by five. This sounds a lot like taking the absolute value of the difference, then dividing by five. The advantage of using an absolute value function to do this is that you hide the <code>if</code>/<code>else</code> code so you don't have to read through it later. A very similar approach is available for ensuring that the skills don't go below zero, using a maximum or minimum function.</p>\n<h3>Finding ways to avoid repetition</h3>\n<p>After you have the strengths, skills, differences, and &quot;rolls&quot; (<code>num1</code> and <code>num2</code>), you have two branches of code which are largely the same. If <code>num1</code> is bigger than <code>num2</code> then the first character wins the encounter. If <code>num2</code> is larger, the second character wins.Since both of the <code>if</code> statements execute the same operation, but on different variables, it would be nice if you could give the variables a new name, say <code>winner</code> and <code>loser</code>, then add points to the winner and subtract them from the loser. However, in order to do that, you would have to change the storage of your strength and skill.</p>\n<h3>Small things</h3>\n<p>It might be helpful to include which character's skill the program is requesting you enter at the beginning. Without that, it might look weird that the program asks you two questions twice.</p>\n<p>It's typically less idiomatic to compare a value to <code>True</code> as the condition of a while loop. Instead prefer to use the value itself as the condition: <code>while play1: ...</code>. Or, better still, it may make sense to incorporate your later conditions into the while loop, for example making its condition whether both of the character's strength are still above zero. If they are not, the while loop will end, and you can print the winner.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T13:26:06.633", "Id": "45141", "ParentId": "45137", "Score": "5" } }, { "body": "<p>There are two huge improvements you can make to increase readability of your code:</p>\n\n<ol>\n<li><p>Choose better names for some variables – <code>skill1</code> is better than <code>skl1</code>, and <code>strength2</code> is better than <code>str2</code> (<code>str</code> usually means “string”, which adds even more confusion). <code>play1</code> should be <code>play</code> or <code>play_on</code>.</p></li>\n<li><p>Put whitespace around operators rather than trying to write your code as compact as possible. For example, change</p>\n\n<pre><code>strdif=str1-str2\nif strdif&lt;0:\n strdif=str2-str1\nstrdif=strdif//5\n</code></pre>\n\n<p>to</p>\n\n<pre><code>strength_difference = strength1 - strength2\nif strength_difference &lt; 0:\n strength_difference = strength2 - strength1\nstrength_difference = strength_difference // 5\n</code></pre></li>\n</ol>\n\n<p>Next, there are a number of small issues that could be improved:</p>\n\n<ul>\n<li><p><code>while play1 == True</code> could be abbreviated to <code>while play1</code>. However, setting a variable to <code>False</code> in order to exit a loop isn't very elegant: You could <code>break</code> out of the loop instead, or put the loop into a function from which you can <code>return</code>.</p></li>\n<li><p>When calculating the differences of strength and skill, you could use the <code>abs</code> function instead: <code>strength_difference = abs(strength1 - strength2) // 5</code>.</p></li>\n<li><p>You roll two random numbers from 1–6, then compare whether they are greater or smaller than each other. Instead, we could directly figure out the probabilities:</p>\n\n<ul>\n<li>2/12: draw</li>\n<li>5/12: player 1 deals a blow</li>\n<li>5/12: player 2 deals a blow</li>\n</ul>\n\n<p>which means we only have to roll one value from 1–12</p></li>\n<li><p>Instead of naming our variables <code>foo1</code> or <code>foo2</code>, let's create dictionaries that hold variables for each player:</p>\n\n<pre><code>player1 = dict()\nplayer1[\"name\"] = \"Character 1\"\nplayer1[\"strength\"] = ...\nplayer1[\"skill\"] = ...\n</code></pre>\n\n<p>This looks more verbose, but allows us to remove a lot of duplication in a minute.</p></li>\n<li><p>We can stuff the character initialization into a function that returns a player dictionary:</p>\n\n<pre><code>def generate_character():\n character = dict()\n character[\"name\"] = raw_input(\"name: \")\n character[\"strength\"] = int(raw_input(\"strength: \"))\n character[\"skill\"] = int(raw_input(\"skill: \"))\n\n print(\"Your character is %s (strength: %d, skill: %d)\" % (character[\"name\"], character[\"strength\"], character[\"skill\"]))\n\n return character\n</code></pre>\n\n<p>Note that I use <code>raw_input</code> instead of <code>input</code>, as this avoids executing the input as if it were code.</p>\n\n<p>We can then initialize the players like this:</p>\n\n<pre><code>player1 = generate_character()\nplayer2 = generate_character()\n</code></pre>\n\n<p>Because all info about a player is conveniently bundled, we can do neat stuff like this:</p>\n\n<pre><code>(loser, winner) = sorted((player1, player2), key = lambda player: player[\"strength\"])\n</code></pre>\n\n<p>which sorts the players by their strength. This simplifies printing out the stats at the end of a round:</p>\n\n<pre><code>for player, status in [(winner, \"won\"), (loser, \"lost\")]:\n print(\"%s %s the encounter, now has %d strength and %d skill\" % \n (player[\"name\"], status, player[\"strength\"], player[\"skill\"]))\n</code></pre></li>\n</ul>\n\n<p>Using dictionaries for this is easy, but awkward. Instead we could write a class that represents characters, and create one instance of this class for each player:</p>\n\n<pre><code>class Character:\n def __init__(self, name, strength, skill):\n self.name = name\n self.strength = strength\n self.skill = skill\n</code></pre>\n\n<p>Our <code>generate_character</code> changes to this:</p>\n\n<pre><code>def generate_character():\n name = raw_input(\"name: \")\n strength = int(raw_input(\"strength: \"))\n skill = int(raw_input(\"skill: \"))\n\n character = Character(name, strength, skill)\n\n print(\"Your character is %s (strength: %d, skill: %d)\" % (character.name, character.strength, character.skill))\n\n return character\n</code></pre>\n\n<p>If we combine all these points (and a few other minor quibbles), we might end up with something like the following code:</p>\n\n<pre><code>import random\n\nclass Character:\n def __init__(self, name, strength, skill):\n self.name = name\n self.strength = strength\n self.skill = skill\n\n def hit(self, other):\n strength_difference = abs(self.strength - other.strength)\n self.strength += strength_difference\n other.strength = max(0, other.strength - strength_difference)\n\n skill_difference = abs(self.skill - other.skill)\n self.skill += skill_difference\n other.skill = max(0, other.skill - skill_difference)\n\ndef generate_character():\n name = raw_input(\"name: \")\n strength = int(input(\"strength: \"))\n skill = int(input(\"skill: \"))\n\n character = Character(name, strength, skill)\n\n print(\"Your character is %s (strength: %d, skill: %d)\" % (character.name, character.strength, character.skill))\n\n return character\n\ndef run(player1, player2):\n while True:\n print(\"Encounter!\")\n\n roll = random.randint(1, 12)\n if roll &lt;= 5:\n player1.hit(player2)\n elif roll &lt;= 10:\n player2.hit(player1)\n else:\n pass # draw\n\n if player1.strength &lt;= 0:\n print(\"%s won the game\" % player1.name)\n return\n if player2.strength &lt;= 0:\n print(\"%s won the game\" % player2.name)\n return\n\n (loser, winner) = sorted((player1, player2), key = lambda player: player.strength)\n for player, status in [(winner, \"won\"), (loser, \"lost\")]:\n print(\"%s %s the encounter, now has %d strength and %d skill\" % \n (player.name, status, player.strength, player.skill))\n\nif __name__ == \"__main__\":\n print(\"Initialize the first character:\")\n player1 = generate_character()\n print(\"Initialize the second character:\")\n player2 = generate_character()\n run(player1, player2)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T15:53:40.837", "Id": "78616", "Score": "2", "body": "Good advice, but in the future please refrain from providing complete solutions to schoolwork questions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T16:20:14.000", "Id": "78620", "Score": "0", "body": "Thanks a lot , you spent quite a lot of time answering my question. This will help a lot. Thanks again !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T19:52:38.183", "Id": "78641", "Score": "0", "body": "[tag:homework] \"Homework means the question is requesting help with school homework. This lets potential answerers know that they SHOULD guide the student in solving the problem, and SHOULD NOT simply show the complete answer.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T20:10:32.047", "Id": "78643", "Score": "7", "body": "@ChrisW (and @200_success) thanks for that reminder – I may not have written this answer in the most responsible fashion in the light of that tag. But please note that the problem was already completely “solved” by OP, and that my example refactoring comes only after extensive discussion. But fundamentally, there's [nothing special about homework questions](https://meta.codereview.stackexchange.com/a/588): The asker (not the answerer) is responsible for not cheating, just as a professional programmer is responsible for not copying CC-BY-SA licensed code without respecting that license." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T14:31:20.280", "Id": "45144", "ParentId": "45137", "Score": "16" } }, { "body": "<p>You have a problem in that your code fails when the strength of your characters is equal. The strength difference is zero and this is applied to each character at each encounter. If its zero then neither character is affected.</p>\n\n<p>Also, skill seems to have no effect on anything. I would expect it to modify the damage and/or the 'dice roll'.</p>\n\n<p>With that in mind, I would create a class for your character</p>\n\n<pre><code>class Player(object):\n def __init__(self, name, strength, skill):\n self.name = name\n self.strength = strength\n self.skill = skill\n\n def alive(self):\n return self.strength &gt; 0\n\n def roll(self):\n return random.randint(1,6)\n\n def __str__(self):\n return \"%s(strength=%i, skill=%i)\" % (self.name, self.strength, self.skill)\n</code></pre>\n\n<p>It's not strictly necessary to have the dice roll in the character class but that's how I've coded it. The <code>__str__</code> method provides a nice way to present your character. e.g.</p>\n\n<pre><code>p = Player('Graeme', 100, 1000)\nprint(p)\n</code></pre>\n\n<blockquote>\n <blockquote>\n <p>Graeme(strength=100, skill=1000)</p>\n </blockquote>\n</blockquote>\n\n<p>Now you need to run the fight. I've created a function that takes two player instances. I've kept some of your logic here (though using abs() is better). The fight function calls the encounter function in a while loop which checks they are both alive.</p>\n\n<pre><code>def fight(p1, p2):\n strdiff = abs(p1.strength - p2.strength) // 5\n skldiff = abs(p1.skill - p2.skill) // 5\n while p1.alive() and p2.alive():\n encounter(p1, p2, strdiff, skldiff)\n if p1.alive():\n print(\"%s won the game\" % p1)\n else:\n print(\"%s won the game\" % p2)\n</code></pre>\n\n<p>The encounter function takes your difference variables as input.</p>\n\n<pre><code>def encounter(p1, p2, strdiff, skldiff):\n num1 = p1.roll()\n num2 = p2.roll()\n\n if num1 == num2:\n return \n if num1 &gt; num2:\n winner = p1\n loser = p2\n else:\n winner = p2\n loser = p1\n\n winner.strength += strdiff\n winner.skill += skldiff\n loser.strength -= strdiff\n loser.skill -= skldiff\n loser.strength = max(0, loser.strength)\n loser.skill = max(0, loser.skill)\n\n print(\"%s won the encounter\" % winner)\n print(\"%s lost the encounter\" % loser)\n</code></pre>\n\n<p>Now the whole thing can be run using a simple function to get input.</p>\n\n<pre><code>def get_value(attribute):\n \"\"\"get user input as integer\"\"\"\n return int(raw_input(\"Enter a value for %s: \" % attribute)) \n\np1 = Player(\"Character 1\", get_value('strength'), get_value('skill'))\nprint(p1)\np2 = Player(\"Character 2\", get_value('strength'), get_value('skill'))\nprint(p2)\n\nfight(p1, p2)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T13:30:06.597", "Id": "45213", "ParentId": "45137", "Score": "3" } }, { "body": "<p>The major one, right off the back that I see (and knowing how most teachers are) is the lack of comments in your code, I'm not sure if your teacher requires it, but it certainly couldn't hurt. </p>\n\n<p>Use # for one line comments, or</p>\n\n<p>\"\"\" to span\nmultiple \nlines \"\"\"</p>\n\n<p>For instance: </p>\n\n<pre><code>#This is a one-line comment, it ends when the line ends, and cannot be used for any code\n\n#import necessary modules and set variables\nimport random\nplay1 = True \n\n#Get user input\nstr1 = int(input(\"Enter a value for strength\"))\nprint(\"you have chosen\",str1,)\n\"\"\" This makes a comment.\nIt spans multiple lines!\n\"\"\"\n</code></pre>\n\n<p>Also, if the user enters a number that is a decimal your program will fail because of this:</p>\n\n<pre><code>str1 = int(input(\"Enter a value for strength\" ))\n\n\"\"\"int returns an integer - which in python cannot be a decimal.\nIf the user enters a decimal it will return the error:\nValueError: invalid literal for int() with base 10: '87.94'\n\"\"\"\n</code></pre>\n\n<p>If you want to keep this as an integer, you will first need to 'float' the input, then you will need to convert it to an integer. The following will work:</p>\n\n<pre><code>str1 = int(float(input(\"Enter a value for strength\" )))\n</code></pre>\n\n<p>When you 'float' a number, you are basically saying that the value is the exact value. So if you float \"1/3\" you will get .333 repeating. 1.2 is not an integer, and I have no idea how to explain why that is. Bottom line: decimals are not integers.</p>\n\n<p>You could also merely 'float' the input, assuming your program has no need for the number to be an integer (at this stage it doesn't).</p>\n\n<pre><code>str1 = float(input(\"Enter a value for strength\" ))\n</code></pre>\n\n<p>That is the extent of my pea-sized knowledge.\nMost importantly though is the comments, always comment, comment, and comment some more; it shows the teacher you 'understand' what's going on, and I can't even tell you how many times it's saved me when debugging</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T08:42:47.267", "Id": "79854", "Score": "1", "body": "Comments should explain _why_, not reiterate _what_. A comment like `#Get user input` adds noise without insight — the call to `input()` is self-explanatory. (It's like a useless public speaker who just reads bullet points on PowerPoint slides that the audience can already read.) On the other hand, a comment like `# Character 1 defeats Character 2 and absorbs strength and skill points equal to the difference in their power` could be helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T16:52:19.237", "Id": "79884", "Score": "0", "body": "I see what you're getting at, when I add comments like that it's merely because I outline what I'm trying to do before the next line of code; I just find it helpful to keep me on track." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T17:22:33.500", "Id": "79885", "Score": "0", "body": "When code is long and convoluted enough that it needs comments as signposts, it probably needs to be reorganized for clarity, as in [@amon's answer](http://codereview.stackexchange.com/a/45144/9357)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T08:32:33.200", "Id": "45741", "ParentId": "45137", "Score": "1" } } ]
{ "AcceptedAnswerId": "45144", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T12:45:58.230", "Id": "45137", "Score": "10", "Tags": [ "python", "game", "homework", "python-3.x" ], "Title": "Suggestions for a Dungeons and Dragons-like game" }
45137
<p>Below is my solution for <a href="http://www.codechef.com/MARCH14/problems/TMSLT">this 'Team Split' problem</a>.</p> <p>In summary, the problem is to find relative strength of 2 teams by finding the difference between their total strength (individual strengths can be found using a quadratic expression of form ax<sup>2</sup>+bx+c).</p> <p>The solution in Java manages to solve the problem, but I am regularly getting the Time Limit Exceeded issue.</p> <p>Can anyone offer advice on how to reduce the complexity of this code?</p> <pre><code>import java.util.*; import java.io.*; public class Main { public static void main (String args[]) throws IOException{ try{ BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); int not=Integer.parseInt(sc.readLine()); int a,b,c,d; for(int i=0;i&lt;not;i++){ String s[]=sc.readLine().trim().split(" "); int r=Integer.parseInt(s[0]); a=Integer.parseInt(s[1]); b=Integer.parseInt(s[2]); c=Integer.parseInt(s[3]); d=Integer.parseInt(s[4]); long S[]=new long [r]; S[0]=d; for(int k=1;k&lt;r;k++){ S[k]=((a*S[k-1]*S[k-1])+(b*S[k-1])+c)%1000000; //System.out.println(S[k]); } Arrays.sort(S); long so1=0; long so2=0; long t; for(int p=r-1,q=r-2;p&gt;=0;p=p-2,q=q-2){ if(q&gt;=-1){ so1=so1+S[p]; if(q&gt;=0){ so2=so2+S[q]; } } } // System.out.println(so1); // System.out.println(so2); t=so1-so2; if(t&lt;0){ t=(-1)*t; } System.out.println(t); //sc.close(); } }catch(NumberFormatException afe){ System.out.println(afe); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T16:38:44.447", "Id": "78623", "Score": "1", "body": "When exactly are you getting time limit exceeded? For what inputs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T16:45:59.440", "Id": "78624", "Score": "0", "body": "@SimonAndréForsberg You can submit your code to http://www.codechef.com/MARCH14/problems/TMSLT ... perhaps it will show you its inputs. One of the comments on that page (dated `8 Mar 2014 11:07 AM`) gives one set of example inputs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T17:24:16.053", "Id": "78627", "Score": "0", "body": "guys the issue is my solution involves sorting of arrays and that increases the complexity,any workarounds such that sorting can be avoided to solve that problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T13:02:29.413", "Id": "78745", "Score": "0", "body": "@arunkrishnamurthy01 I have asked once: Which inputs are giving you time limit exceeeded? I understand your concerns about speed and I'd gladly help you with them (if ChrisW's answer below isn't enough for you) if your code would have been easier to read and I'd had known what inputs are causing the time limit exceeded issue. Given the current state of your code and question, the time limit isn't your biggest problem IMO." } ]
[ { "body": "<h1>Rewafadhabihlgdity</h1>\n\n<p>(If you can't tell, that is supposed to say 'readability'). Leaves some things to be desired.</p>\n\n<ul>\n<li><p>Variable names: All your variable names are three characters or less. This makes it very hard to read your code. Renaming <code>r</code> to <code>playerCount</code> is a start, and <code>S</code> can be called <code>strengths</code>. <code>so1</code> and <code>so2</code> should also be renamed, along with <code>t</code>, <code>p</code> and <code>q</code>. Make variables self-documenting by giving them a reasonable name.</p></li>\n<li><p>Spacing: Dontyoufinditabithardtoreadtext/codethatdoesntcontainanyspacesandappropriatepunctuation? (I'm exagerating just to prove a point). Even though it is a bit easier to read lack of code spacing than lack of word-spacing in written text, I find a line like this hard to read:</p>\n\n<pre><code>S[k]=((a*S[k-1]*S[k-1])+(b*S[k-1])+c)%1000000;\n</code></pre>\n\n<p>For this particular line, consider rewriting it to this:</p>\n\n<pre><code>int previous = strengths[index - 1];\nstrengths[index] = (a * previous * previous + b * previous + c) % 1000000;\n</code></pre>\n\n<p>By using better variable names, adding space, extracting a variable, and removing unnecessary parenthesis that line becomes a lot more readable.</p>\n\n<p>The lack of good variable names and spacing especially made this part of the code really hard for me to understand what you are doing and why:</p>\n\n<pre><code>for(int p=r-1,q=r-2;p&gt;=0;p=p-2,q=q-2){\n if(q&gt;=-1){\n so1=so1+S[p];\n if(q&gt;=0){\n so2=so2+S[q];\n }\n }\n}\n</code></pre></li>\n</ul>\n\n<h1>Speed</h1>\n\n<p>Unable to reproduce / Unclear what the issues are. It seems to me that your code is quite fast. Even the input <code>10000000 5 6 7 8</code> calculated with reasonable speed IMO.</p>\n\n<h1>Extensibility</h1>\n\n<p>For testing purposes, to ensure both correct results and fast enough results, it would be useful to <strong>extract a method</strong> to do the actual calculations, and then your outermost loop could be:</p>\n\n<pre><code> for (int i = 0; i &lt; count; i++) {\n String s[] = sc.readLine().trim().split(\" \");\n int playerCount = Integer.parseInt(s[0]);\n a = Integer.parseInt(s[1]);\n b = Integer.parseInt(s[2]);\n c = Integer.parseInt(s[3]);\n d = Integer.parseInt(s[4]);\n System.out.println(determineTeamDifferences(playerCount, a, b, c, d));\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T17:52:10.453", "Id": "78629", "Score": "1", "body": "That weird p-q-r for-loop can be untangled by noticing that `p` and `q` have a constant offset, by moving the bounds, removing unnecessary tests, and noticing that `if(q>=0)` is true when `r` is odd. I [played a bit with the source code](http://ideone.com/5vaIBI) which makes this more obvious but doesn't improve performance (the other solutions from the challenge's page use a weird form of memoization to find repetitions – there are only 1M possible values, after all)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T17:29:40.963", "Id": "45150", "ParentId": "45146", "Score": "26" } }, { "body": "<blockquote>\n <p>guys the issue is my solution involves sorting of arrays and that increases the complexity,any workarounds such that sorting can be avoided to solve that problem.</p>\n</blockquote>\n\n<p>There's one Sort statement in your program:</p>\n\n<pre><code> long S[]=new long [r];\n S[0]=d;\n for(int k=1;k&lt;r;k++){\n S[k]=((a*S[k-1]*S[k-1])+(b*S[k-1])+c)%1000000;\n //System.out.println(S[k]);\n }\n Arrays.sort(S);\n</code></pre>\n\n<p>It seems to me that the output (for reasonable values of a,b,c) is mostly sorted already. It will wrap when it exceeds 1000000.</p>\n\n<p>So an algorithm like:</p>\n\n<pre><code>long knext = ((a*S[k-1]*S[k-1])+(b*S[k-1])+c)%1000000;\nif (knext &gt;= kprev)\n store in same array as kprev\nelse\n create a new array and store as first element in new array\n</code></pre>\n\n<p>After you do that, you have one sorted array (if it never wrapped), or several sorted arrays to be merged. Every array is already sorted.</p>\n\n<p><a href=\"https://www.google.com/search?q=merging+sorted+arrays\">Merging those sorted arrays into one array ought to be cheaper than sorting one big, unsorted array</a>.</p>\n\n<hr>\n\n<p>The above might be a large optimization: changing the data structure and algorithm.</p>\n\n<p>The following might be a micro-optimization:</p>\n\n<pre><code>S[k]=((a*S[k-1]*S[k-1])+(b*S[k-1])+c)%1000000;\n</code></pre>\n\n<p>The above does an array lookup 3 times to calculate the expression; so the following may be a little faster (cache the previous value in a local variable instead of only in the previous element of the array):</p>\n\n<pre><code>S[0] = d;\nlong value = d;\nfor (int k = 1; k &lt; r; ++k) {\n value = ((a*value*value) + (b*value) + c) % 1000000;\n S[k] = value;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T17:54:22.803", "Id": "45151", "ParentId": "45146", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T15:54:32.020", "Id": "45146", "Score": "15", "Tags": [ "java", "complexity", "programming-challenge" ], "Title": "'Team Split' problem" }
45146
<p>So today after few years of not programming in PHP I decided to go back, but to do so I needed to change all MySQL connections. So I want to check if I am using it good.</p> <p>Earlier I used to write something like this:</p> <pre><code>$user = clean($_COOKIE["Logged"]); $GameReg = mysql_fetch_array(mysql_query("SELECT * FROM DB.GameReg WHERE hash='$user'")); </code></pre> <p>But now it is like this:</p> <pre><code>$stmt = $dbh-&gt;prepare("SELECT * FROM DB.GameReg WHERE hash = :user"); $stmt-&gt;bindParam(':user', $user); $user = $_COOKIE["Logged"]; $stmt-&gt;execute(); $GameReg = $stmt-&gt;fetch(PDO::FETCH_ASSOC); </code></pre> <p>So am I using it correctly? I used to do all kinds of filtering before inserting or updating SQL table, but I've read that prepared statements doesn't need that. Is this safe to use?</p> <p>As I am knew to PDO I am trying to save up some code, so I kinda came up with this:</p> <pre><code>$stmt = $dbh-&gt;prepare("SELECT * FROM DB.GameStats WHERE hash = :user"); $stmt = $dbh-&gt;prepare("SELECT * FROM DB.GameReg WHERE hash = :user"); $stmt-&gt;bindParam(':user', $user); $user = $_COOKIE["Logged"]; $stmt-&gt;execute(); $GameReg = $stmt-&gt;fetch(PDO::FETCH_ASSOC); $stmt-&gt;execute(); $GameStats = $stmt-&gt;fetch(PDO::FETCH_ASSOC); </code></pre> <p>I checked this by trying to call some table members:</p> <pre><code>echo $GameReg["pass"]; echo "\n"; echo $GameStats["nick"]; </code></pre> <p>It works, but I am not sure if this is the best way to do. Any comments?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T17:13:16.987", "Id": "78625", "Score": "0", "body": "Probably not on the point you're trying to make but: you should do `$user = $_COOKIE[\"Logged\"]` before `$stmt->bindParam(':user', $user)`, no?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T17:15:47.743", "Id": "78626", "Score": "0", "body": "Well I did this by these examples http://it2.php.net/manual/en/pdo.prepared-statements.php" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T18:26:40.203", "Id": "78632", "Score": "1", "body": "@NadirSampaoli, bindParam() takes a reference to the variable." } ]
[ { "body": "<p>It's good that you're moving over. Many people think it's too difficult to switch over, but in the long run, it's definitely worth it.</p>\n\n<p>Technically you can assign <code>$user</code> after you bind, because it's the actual execute call that substitutes. Although, in my opinion, it's easier to read when scanning the code to see the assignment before the binding. You could also do it like so:</p>\n\n<pre><code>$stmt-&gt;execute(array(':user' =&gt; $user));\n</code></pre>\n\n<p>However, it's even safer to apply a data type, so that if <code>$user</code> is an unacceptable type (assuming it's supposed to be a string), it returns false. Like so:</p>\n\n<pre><code>$stmt-&gt;bindParam(':user', $user, PDO::PARAM_STR);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T14:38:36.917", "Id": "78757", "Score": "0", "body": "Thanks, tip about applying data type is good, I can really use it :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T20:10:09.967", "Id": "45156", "ParentId": "45147", "Score": "7" } }, { "body": "<p>Your code is fine. Really. However, it does show some lack of understanding the <em>true</em> benefits and power of prepared statements.<br>\nI'm also not convinced you fully understand how the <code>PDOStatement::bindParam</code> method works. Allow me to explain:</p>\n\n<p>A prepared statement is sent to the DB server as a string, with the placeholders that will be replaced with the query values. This query string is already parsed, compiled and optimized at this point, in case it is possible, the result is already being stored in a temp-table, too.<br>\nAt this point, you have a resource handle to this prepared statement, assigned to the variable <code>$stmt</code>. The really neat thing is that this statement can be used as much as you like, each times specifying new parameters, for example:</p>\n\n<pre><code>$stmt = $pdo-&gt;prepare('SELECT age, sex, nationality FROM people WHERE name = :name');\n$names = array(\n 'Frank',\n 'Lisa',\n 'John',\n 'Jane'\n);\n$bind = array(\n ':name' =&gt; null\n);\n$personalia = array();\nforeach ($names as $name)\n{\n $bind[':name'] = $name;\n $stmt-&gt;execute($bind);\n $personalia[$name] = $stmt-&gt;fetch(PDO::FETCH_ASSOC);\n}\n</code></pre>\n\n<p>As you can see, I only call <code>prepare</code> once, but execute 4 distinct queries. The advantage then, is simple: the query only has to be parsed, compiled and optimized once, and in some cases, the result set can be pre-fetched in such a way that you'd never need to search through the entire tbl.<br>\nBottom line: prepared statements not only provide security against injection, it often outperforms regular queries, too.</p>\n\n<p>You may have noticed how I used <code>execute(array)</code>, and not <code>bindParam</code>, like your code does. Though sometimes I do use <code>bindParam</code>, I find it best to avoid this method when I can, in favour of <code>execute(array)</code>, or if needs must <code>PDOStatement::bindValue</code>. As to why, we need to look at the method's signature:</p>\n\n<pre><code>public bool PDOStatement::bindParam ( mixed $parameter , mixed &amp;$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )\n</code></pre>\n\n<p>The <code>$parameter</code> argument is the <em>Parameter identifier</em>, or placeholder. In this case, the string <code>:name</code>.<br>\nThe <code>$variable</code> argument is <strong><em>not</em></strong> the value that will be used in the query but if you look closely, the parameter is passed <em>by reference</em>: <code>&amp;$variable</code> &lt;-- that's what the <code>&amp;</code> operator is for. Using it yourself is, arguably, <a href=\"https://stackoverflow.com/questions/17459521/what-is-better-in-a-foreach-loop-using-the-symbol-or-reassigning-based-on-k/18464019#18464019\">bad practice</a>, but no matter how you look at it, it does make your code harder to read and maintain. Imagine I did this, for example:</p>\n\n<pre><code>$stmt-&gt;bindParam(':name', $name);\nwhile($name = array_pop($names))\n{\n $stmt-&gt;execute();\n}\n</code></pre>\n\n<p>This should work just fine, but what if <code>$names</code> changes, or someone re-assignes <code>$name</code> at some point as the <code>while</code> loop becomes more complex? You end up with quite error-prone code.</p>\n\n<p>The advantage of this method, then, is the third parameter: <code>$data_type</code>. It allows you to specify the data-type you want to pass to the query. using the <code>PDOStatement::execute(array)</code> method, all parameters will follow the default behaviour, which means they'll be passed as strings. MySQL is capable to cast those string values to the appropriate types most of the time. As always, a cast implies <em>some</em> overhead, but it's highly unlikely that this will be a bottleneck and most of the time, this'll do just fine. It's an old quote, but keep in mind that premature optimization still is the root of all evil. Be that as it may, when dealing with values like <code>NULL</code> or booleans, it can sometimes come in handy to pass specific types.<br>\nStill, for those cases, <code>PDOStatement::bindParam</code> shouldn't be the default method to turn to. As you can see from the method's signature, it's powerful, but complex. Bugs and complexity go hand in hand, so let's look at another method, that <em>does</em> allow you to specify specific types: <code>PDOStatement::bindValue</code>. This method does the same thing as <code>PDOStatement::bindParam</code>, but <em>does not</em> use references (that's one less source of woes you don't have to think about), and doesn't take as many arguments:</p>\n\n<pre><code>public bool PDOStatement::bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )\n</code></pre>\n\n<p>If all you need is to specify a specific type, then this method is to be preferred: it allows you to specify all the types, but without the added risk of passing references around. </p>\n\n<p>To recap: Unless you're looking to optimize your code to save every millisecond you can, or you need to pass some driver-specific options, I'd use <code>bindValue</code> rather than <code>bindParam</code>. Which, again, makes your code less error-prone and generally easier to maintain.</p>\n\n<p>In short, then, and applied to your specific code, I'd recommend you write something like:</p>\n\n<pre><code>$stmt = $pdo-&gt;prepare(\n 'SELECT * FROM DB.GameReg WHERE hash = :user'\n);\n$stmt-&gt;execute(\n array(\n ':user' =&gt; $_COOKIE['Logged']\n )\n);\n$gameReg = $stmt-&gt;fetch(PDO::FETCH_ASSOC);\n</code></pre>\n\n<p>Which gives you spacious, easy to read and maintain code.<br>\nIf you want to be able to specify the type, and need nothing more, then use <code>bindValue</code>.</p>\n\n<p>If you want to call a stored procedure, that uses an <code>INOUT</code> argument, then you have to resort to `PDOStatement::bindParam:</p>\n\n<pre><code>$stmt = $pdo-&gt;prepare(\n 'CALL your_sp(:io)'\n);\n$was = $io = 'hello';\n$stmt-&gt;bindParam(\n ':io',\n $io,\n PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT,//string, inout argument\n 6\n);\n//example:\n$stmt-&gt;execute();\necho 'Argument was: ', $was, PHP_EOL, 'Now is: ', $io;\n</code></pre>\n\n<p>Could echo something like:</p>\n\n<blockquote>\n <p>Argument was: hello<br>\n Now is: world</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T14:37:33.467", "Id": "78755", "Score": "0", "body": "Thanks for truly great answer, yes you are right I started just yesterday to work with PDO so I understand very little, but thanks to you now I know a bit more :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T10:30:58.520", "Id": "45192", "ParentId": "45147", "Score": "10" } } ]
{ "AcceptedAnswerId": "45192", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T16:38:48.410", "Id": "45147", "Score": "14", "Tags": [ "php", "mysql", "pdo" ], "Title": "Want to check if I am using PDO correctly" }
45147
<p>A <a href="http://en.wikipedia.org/wiki/White_elephant_gift_exchange" rel="nofollow">secret santa gift exchange</a> is a game where each player is randomly assigned a person to whom they anonymously give a gift. The algorithm is referred to as <a href="http://en.wikipedia.org/wiki/Derangement" rel="nofollow">Derangement</a>.</p> <p>For example, given the following players:</p> <blockquote> <p>Mohamad, Carolina, Sami, Tania, Ikram, José</p> </blockquote> <p>A game may be:</p> <blockquote> <p>Mohamad gets Sami<br> Carolina gets José<br> Sami gets Tania<br> Tania gets Mohamad<br> Ikram gets Carolina<br> José gets Ikram </p> </blockquote> <p>The important rules are:</p> <ol> <li>A person can not be assigned to themselves.</li> <li>A person can only be assigned to another person once.</li> <li>Assignment must be random.</li> </ol> <h2>Implementation</h2> <p>This is my object oriented implementation. I do not like my <code>random_player_for</code> implementation. It seems procedural and the use of temporary flags seems like a code smell.</p> <p>How would you improve this implementation?</p> <pre><code>class Derangement attr_reader :game # for convenience # PLAYERS = %w[Mohamad Carolina Sami Tania Jose Ikram Rabii Ahmad Kazem] def initialize(players) @players = players @santas = players.dup @game = {} end def solve @santas.each do |santa| @game[santa] = random_player_for(santa) end end private def random_player_for(santa) found = false until found do player = @players.sample unless player == santa found = true @players.delete(player) end end player end end </code></pre>
[]
[ { "body": "<p>I'm a bit unsure about whether the question is about a game of Secret Santa or if it's actually about derangement, specifically. Derangement requires that no element can appear <em>in its original position</em>. <strike>But that's irrelevant for a game of Secret Santa, since there's no ordering to speak of.</strike></p>\n\n<p><em>Edit:</em> As tokland rightly points out in the comments derangement <em>is</em> of course related to the game. I wasn't thinking it through.</p>\n\n<p>For derangement, <a href=\"http://rosettacode.org/wiki/Permutations/Derangements#Ruby\" rel=\"nofollow\">Rosetta Code has a Ruby implementation</a> you might be able to use or learn from.</p>\n\n<p>For a game of Secret Santa, though, the specs are pretty much as you summed up in your 3 rules (although #3 \"Assignment must be random\" is a bit difficult to define/verify.) So here, things can be simplified; you need not worry about derangement \"by itself\" as long as the rules are obeyed. For instance, you might simply do:</p>\n\n<pre><code>players = %w[Mohamad Carolina Sami Tania Ikram Jose].shuffle\nplayers &lt;&lt; players.first # repeat the first player\n\nassignments = players.each_cons(2).to_a\n</code></pre>\n\n<p>which will give you an array of santa/gift-receiver pairs such as:</p>\n\n<pre><code>[[\"Carolina\", \"Ikram\"],\n [\"Ikram\", \"Mohamad\"],\n [\"Mohamad\", \"Jose\"],\n [\"Jose\", \"Tania\"],\n [\"Tania\", \"Sami\"],\n [\"Sami\", \"Carolina\"]]\n</code></pre>\n\n<p>Alternatively, you can get the \"Santa targets\" for several rounds by doing something like</p>\n\n<pre><code>players = %w[Mohamad Carolina Sami Tania Ikram Jose].shuffle\nassignments = players.each_with_index.map do |santa, index|\n others = players.rotate(index+1)[0...-1]\n [santa, others]\nend\n</code></pre>\n\n<p>Which will give you something like</p>\n\n<pre><code>[[\"Tania\", [\"Mohamad\", \"Sami\", \"Ikram\", \"Carolina\", \"Jose\"]],\n [\"Mohamad\", [\"Sami\", \"Ikram\", \"Carolina\", \"Jose\", \"Tania\"]],\n [\"Sami\", [\"Ikram\", \"Carolina\", \"Jose\", \"Tania\", \"Mohamad\"]],\n [\"Ikram\", [\"Carolina\", \"Jose\", \"Tania\", \"Mohamad\", \"Sami\"]],\n [\"Carolina\", [\"Jose\", \"Tania\", \"Mohamad\", \"Sami\", \"Ikram\"]],\n [\"Jose\", [\"Tania\", \"Mohamad\", \"Sami\", \"Ikram\", \"Carolina\"]]]\n</code></pre>\n\n<p>There's a pattern of course (if you've given Ikram a gift, next you'll be giving Carolina a gift, then José, etc.). But if it's Secret Santa, the players shouldn't be able to figure that out anyway unless they cheat (and if they do, well, all bets are off).</p>\n\n<p>You could of course use <a href=\"http://ruby-doc.org/core-2.0.0/Array.html#method-i-combination\" rel=\"nofollow\"><code>Array#combination</code></a> or <a href=\"http://ruby-doc.org/core-2.0.0/Array.html#method-i-permutation\" rel=\"nofollow\"><code>Array#permutation</code></a> to achieve similar results. I highly encourage you to check out all of the built-in array methods, and those included from <a href=\"http://www.ruby-doc.org/core-2.1.1/Enumerable.html\" rel=\"nofollow\">the <code>Enumerable</code> module</a>. There's a lot of good stuff there.</p>\n\n<p>As for a more OOP approach, I wouldn't make a class called \"Derangement\". Derangement is a <em>method</em>. It's an action, an operation, a means of achieving a certain result or state - not something that is itself stateful.<br>\nThe simple solution, given your code, is to rename you class to \"Game\" or something along those lines.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T10:50:07.320", "Id": "78716", "Score": "2", "body": "@Flambino: AFAICS the Secret Santa game is 100% related to derangement, since `persons.zip(persons.shuffle_with_derangement)` is the solution to the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:01:49.787", "Id": "78718", "Score": "1", "body": "@tokland Ah, you're right, of course. I'll update my answer - thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:52:00.227", "Id": "78726", "Score": "0", "body": "@tokland I don't understand something. Is `shuffle_with_derangement` a ruby method? I can't find it in the docs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:59:36.480", "Id": "78728", "Score": "0", "body": "@Mohamad No, you must write `Array#shuffle_with_derangement` yourself :) It was just an example to show the relation (but you can actually implement it this way)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:04:40.223", "Id": "78731", "Score": "0", "body": "@tokland Ha! Of course, that would be too easy! I'm not at a level yet to understand your example, so I assumed the method existed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:17:18.730", "Id": "78737", "Score": "1", "body": "@Mohamad: Ruby has a Array#shuffle method, but of course it does not enforce that all elements end up in different positions as you need. But I think this is correct path for the abstraction (adding a generic abstraction to Array) instead of creating a custom object." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T22:35:05.387", "Id": "45160", "ParentId": "45155", "Score": "5" } }, { "body": "<p>Your <code>random_player_for()</code> method can be better expressed as:</p>\n\n<pre><code> def random_player_for(santa)\n loop do\n player = @players.sample\n if player != santa\n @players.delete(player)\n return player\n end\n end\n end\n</code></pre>\n\n<p>However, you should recognize that there is a <strong>possibility for an infinite loop,</strong> if all other players have already been assigned to each other and there is only one loner left.</p>\n\n<p>The following method would be an improvement in two ways:</p>\n\n<ul>\n<li>Predictable running time</li>\n<li>Detection of a loner</li>\n</ul>\n\n\n\n<pre><code> def random_player_for(players, santa)\n others = players.reject { |player| player == santa }\n if others.empty?\n throw LonerException.new(santa)\n else\n return players.delete(others.sample)\n end\n end\n</code></pre>\n\n<p>Then, if <code>solve()</code> catches the <code>LonerException</code>, it could <code>retry</code> all the assignments from scratch.</p>\n\n<pre><code> def solve\n begin\n @game = {}\n players = @players.dup\n @santas.each { |santa| @game[santa] = random_player_for(players, santa) }\n rescue LonerException\n retry\n end\n end\n</code></pre>\n\n<p>Better yet, modify <code>random_player_for()</code> such that when there are only two players left, and at least one of them has not yet been given an assignment as a Santa, take care to assign them in such a way that there is no loner.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T04:34:39.823", "Id": "78702", "Score": "0", "body": "Thank you. I maybe wrong, but I can not see a scenario where a loner is left. The number of santas should always be equal to the number of players. So every santa will be matched with player other than himself. How can a loner be left over?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T06:14:16.413", "Id": "78705", "Score": "1", "body": "Take your example: { Mohamad, Carolina, Sami, Tania, Ikram, José }. Let's say the first five form a cycle: Mohamad → Carolina, Carolina → Sami, Sami → Tania, Tania → Ikram, Ikram → Mohamad. Poor José is a loner and would have to be assigned to himself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:02:30.730", "Id": "78730", "Score": "1", "body": "I see. But doesn't your implementation of the `random_player_for` leave the chance of duplicate assignments? No where I see we are modifying the `player` array. So what's to stop the same player being picked on another iteration? Perhaps we should change `return others.sample` to `players.delete(others.sample)`?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T03:51:48.577", "Id": "45181", "ParentId": "45155", "Score": "2" } } ]
{ "AcceptedAnswerId": "45160", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T19:14:43.463", "Id": "45155", "Score": "10", "Tags": [ "algorithm", "ruby" ], "Title": "A Ruby implementation of derangement (secret santa) algorithm" }
45155
<p>For class we were to make a MapReduce program in Python to find low value hashes of our name. I have completed the assignment but want to try and speed it up. The program currently takes about 45s to complete. I would like to see if there are any suggestions on speeding it up some.</p> <p>The requirements are to find hashes of your name with 5 leading 0's when printed in hex. We are to try 40 million nonces. I did a few naive implementations before I finally settled on what is below. What I do is send a dict of 40 consecutive numbers to use as multipliers in the Map function. The multiplier represents the range of millions to go through. So when mult = 0 I will use the nonces 0-1mil, when mult = 23 use the nonces 23mil-24mil.</p> <pre><code>#!/usr/bin/env python import mincemeat def mapfn(k, v): #Hash the string with the given nonce, if its good save it import md5 #Create a md5 hash and fill it with out initial value #The "blockheader" in Bitcoin terms m = md5.new() m.update("Kevin") #Now, step through 1 million nonces with v as a multiplier for i in range(v*1000000, ((v+1)*1000000), 1): mPrime = m.copy() mPrime.update(str(i)) hashOut = mPrime.hexdigest() if(hashOut[:5] == '0' * 5): yield hashOut, i else: pass #Hash trash! def reducefn(k, vs): return (k, vs) if __name__ == "__main__": #Import some useful code import sys import collections #Build the data source, just a list 0-39 nonces = [i for i in range(0, 40)] datasource = dict(enumerate(nonces)) #Setup the MapReduce server s = mincemeat.Server() s.mapfn = mapfn s.reducefn = reducefn s.datasource = datasource #Get the results of the MapReduce results = s.run_server(password="changeme") #List the good hashes print "\nHashed on the string: Kevin\nResults..." for i in range(0, len(results)): key, value = results.popitem() hashStr, nonce = value print "Nonce: " + str(nonce[0]) + ", hash: " + str(hashStr) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T23:42:41.097", "Id": "78663", "Score": "0", "body": "Have you tried using `xrange()` instead of `range()` for the loops inside `mapfn`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T01:02:01.420", "Id": "78675", "Score": "0", "body": "I've done that, along with removing the `,1` from it too. It didn't reduce the time, it actually increased it by .2s. I will wait for @Josay to finish his question and see what else he has in mind." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T01:07:46.533", "Id": "78678", "Score": "0", "body": "Huh, interesting. Not a speed related note, but what’s the argument `k` to `mapfn`? It doesn’t seem to be used anywhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T01:42:38.540", "Id": "78685", "Score": "0", "body": "k and v are key and value pairs from the data source. For this program, the same value. The data source is a dict that looks like `[0: 0, 1: 1 ...etc]`. But say for a MapReduce that counts the word frequency of a text k would still be an index and v might be a single word or line in the text." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T03:08:44.853", "Id": "78689", "Score": "1", "body": "why don't you move `import md5` out of the function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T09:51:20.857", "Id": "78712", "Score": "0", "body": "@m.wasowski Placing imports inside functions seems to be a requirement of [`mincemeat`](https://github.com/michaelfairley/mincemeatpy#imports)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:31:20.870", "Id": "79026", "Score": "0", "body": "^, mincemeat (sorry I do not know the terminology) does not know anything about the \"work server\" (this program) it only knows about the supplied datasource, map, and reduce functions. So you have to supply all imports in the reduce and map functions that they will use." } ]
[ { "body": "<p>From <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a> :</p>\n\n<blockquote>\n <p>Imports are always put at the top of the file, just after any module\n comments and docstrings, and before module globals and constants.</p>\n</blockquote>\n\n<p><em>Edit : Ok, from your comment, it seems like this is a requirement for <a href=\"https://github.com/michaelfairley/mincemeatpy#imports\" rel=\"nofollow\">mincemeat</a>.</em></p>\n\n<hr>\n\n<p>The default value for the third argument of <a href=\"http://docs.python.org/2.7/library/functions.html#range\" rel=\"nofollow\">range</a> is <code>1</code> so you don't need to provide it.</p>\n\n<hr>\n\n<p>You shouldn't use magic numbers. Especially when they have so many digits and are so tedious to read/compare.</p>\n\n<p>It makes the following snippet a bit awkward:</p>\n\n<pre><code>for i in range(v*1000000, ((v+1)*1000000), 1):\n</code></pre>\n\n<p>Just trying to understand how many iterations there will be is a bit of a pain.\nI'd much rather read :</p>\n\n<pre><code>nb_nounces = 1000000\nfor i in range(v*nb_nounces, (v+1)*nb_nounces):\n</code></pre>\n\n<hr>\n\n<p>There is no point in having :</p>\n\n<pre><code> else: \n pass\n</code></pre>\n\n<hr>\n\n<pre><code>nonces = [i for i in range(0, 40)]\ndatasource = dict(enumerate(nonces))\ns.datasource = datasource\n</code></pre>\n\n<p>can be much more concisely written :</p>\n\n<pre><code>s.datasource = {i:i for i in xrange(40)}\n</code></pre>\n\n<p>using <a href=\"http://docs.python.org/2/tutorial/datastructures.html#dictionaries\" rel=\"nofollow\">dict comprehension</a> and <a href=\"http://docs.python.org/2.7/library/functions.html#xrange\" rel=\"nofollow\">xrange</a>.</p>\n\n<hr>\n\n<p><code>for i in range(0, len(container)):</code> is usually an antipattern in Python. This usually corresponds to something that can be written with straight-forward iteration. In your case, I guess (but I haven't tested), you could just do : <code>for key,value in results.iteritems()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T00:47:39.187", "Id": "78670", "Score": "0", "body": "Do you mean make my hard coded values of 40 and 1mil into constants? en.wikipedia.org/wiki/Magic_number_(programming)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T23:47:43.077", "Id": "45168", "ParentId": "45157", "Score": "2" } } ]
{ "AcceptedAnswerId": "45168", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T20:20:40.147", "Id": "45157", "Score": "2", "Tags": [ "python", "performance", "algorithm", "mapreduce" ], "Title": "MapReduce program for finding low value hashes" }
45157
<p>I'm writing a virtual machine in Python using RPython and the PyPy toolchain. The RPython will still work in the ordinary Python 2 interpreter; it's just a bit slow unless it's compiled to C code with PyPy.</p> <p>Does anyone have any positive or negative feedback about my VM?</p> <p>The virtual machine has 4 instructions:</p> <ol> <li><code>EOP</code> - End of Program</li> <li><code>EOI</code> - End of Instruction</li> <li><code>PUSH</code> - Push item onto stack</li> <li><code>PRINT</code> - Print the item at the top of the stack</li> </ol> <p></p> <pre><code>bcode = [] stack = [] regs = [] sp = 0 bcd = [] ''' Instructions ''' OP_EOP = 0 OP_EOI = 1 OP_PUSH = 2 OP_PRINT = 3 def load_program(f2o): f = open(f2o, "r") f2 = f.read() f2 = f2.replace("\n"," ") bcode = f2.split(" ") i = 0 for item in bcode: item = int(item, 16) bcd.append(item) i += 1 return bcd # VM action functions def do_EOP(): print "End of Program" def do_PUSH(ba, b, ip): i = 2 loop = 1 cb = len(b) stack.insert(0, ba) def do_PRINT(stack): stk = stack[0].split(" ") for item in stk: print unichr(int(item)) def execute_program(b): ip = 0 sp = 0 loop = 1 cb = len(b) while (loop): if ip &lt; cb: bc = b[ip] if bc == OP_PUSH: if bc != OP_EOI: ba = str(b[ip + 1]) do_PUSH(ba, b, ip) elif bc == OP_PRINT: do_PRINT(stack) ip += 1 else: loop = 0 def run_program(f): b = load_program(f) execute_program(b) def main(argv): run_program(argv[1]) return 0 def target(*args): return main, None if __name__ == '__main__': import sys main(sys.argv) </code></pre> <p>Here's a file that includes the bytecode that prints "Hello World!" to the screen:</p> <blockquote> <pre><code>0002 0048 0001 0003 0002 0065 0001 0003 0002 006C 0001 0003 0002 006C 0001 0003 0002 006F 0001 0003 0002 0020 0001 0003 0002 0057 0001 0003 0002 006F 0001 0003 0002 0072 0001 0003 0002 006C 0001 0003 0002 0064 0001 0003 0002 0021 0001 0003 </code></pre> </blockquote> <p>You can test the VM like this; it's written in Python 2.7:</p> <blockquote> <p>python vm.py </p> </blockquote>
[]
[ { "body": "<pre><code>bcode = []\nstack = []\nregs = []\nsp = 0\nbcd = []\n</code></pre>\n\n<p>Global variables like this are frowned upon. To be pythonic you should really put them a in a class or something.</p>\n\n<pre><code>'''\nInstructions\n'''\nOP_EOP = 0\nOP_EOI = 1\nOP_PUSH = 2\nOP_PRINT = 3\n\ndef load_program(f2o):\n</code></pre>\n\n<p>f2o? What in the world is that?</p>\n\n<pre><code> f = open(f2o, \"r\")\n f2 = f.read()\n</code></pre>\n\n<p>My recollection of RPython is that it doesn't support this pattern. Are you sure it works in RPython?</p>\n\n<pre><code> f2 = f2.replace(\"\\n\",\" \")\n bcode = f2.split(\" \")\n i = 0\n for item in bcode:\n item = int(item, 16)\n bcd.append(item)\n i += 1\n</code></pre>\n\n<p>What are you ding with i? You count it, but don't do anything with the value that you count.</p>\n\n<pre><code> return bcd\n\n# VM action functions\ndef do_EOP():\n print \"End of Program\"\n\ndef do_PUSH(ba, b, ip):\n</code></pre>\n\n<p>ba? b? pick variables names that let me know what they represent.</p>\n\n<pre><code> i = 2\n loop = 1\n cb = len(b)\n</code></pre>\n\n<p>None of these last three lines do anything. They set variables local to the function when then gets thrown away.</p>\n\n<pre><code> stack.insert(0, ba)\n</code></pre>\n\n<p>For a stack, we usually use the end of the list as the top of stack. That way you can simply append() and pop() the list. Its rather inefficient to insert at the begining.</p>\n\n<pre><code>def do_PRINT(stack):\n stk = stack[0].split(\" \")\n for item in stk:\n print unichr(int(item))\n\ndef execute_program(b):\n ip = 0\n sp = 0\n loop = 1\n</code></pre>\n\n<p>Use True and False for true/false.</p>\n\n<pre><code> cb = len(b)\n while (loop):\n</code></pre>\n\n<p>You don't need the ( or )</p>\n\n<pre><code> if ip &lt; cb:\n bc = b[ip]\n if bc == OP_PUSH:\n if bc != OP_EOI:\n</code></pre>\n\n<p>Are you expecting bc to change between those two lines?</p>\n\n<pre><code> ba = str(b[ip + 1])\n</code></pre>\n\n<p>You read the next piece of bytecode to push it, but you don't skip increment ip to account for it.</p>\n\n<pre><code> do_PUSH(ba, b, ip)\n\n elif bc == OP_PRINT:\n do_PRINT(stack)\n ip += 1\n else:\n loop = 0\n\n\ndef run_program(f):\n b = load_program(f)\n execute_program(b)\n\ndef main(argv):\n run_program(argv[1])\n return 0\n\ndef target(*args):\n return main, None\n\nif __name__ == '__main__':\n import sys\n main(sys.argv)\n</code></pre>\n\n<p>The biggest issue with your code is that you have a lot of code that can't possibly do anything useful. Reading me leaves me to wonder if you just haven't cleaned up your code or are confused about the code actually works. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T23:06:48.783", "Id": "45164", "ParentId": "45158", "Score": "8" } }, { "body": "<p>You need to close files you've open. From <a href=\"http://docs.python.org/2/tutorial/inputoutput.html\">the Python doc</a> :</p>\n\n<blockquote>\n <p>When you’re done with a file, call f.close() to close it and free up\n any system resources taken up by the open file.</p>\n</blockquote>\n\n<p>Even better, you should use the <a href=\"http://docs.python.org/2/reference/compound_stmts.html#with\">with</a> keyword :</p>\n\n<blockquote>\n <p>It is good practice to use the with keyword when dealing with file\n objects. This has the advantage that the file is properly closed after\n its suite finishes, even if an exception is raised on the way. It is\n also much shorter than writing equivalent try-finally blocks.</p>\n</blockquote>\n\n<hr>\n\n<p>Don't use the same variable for two different things if you can avoid it as it can make it hard to understand the kind of data the variable is supposed to refer to. For instance, it's easier to get what <code>f2</code> is like if you rewrite </p>\n\n<pre><code>f2 = f.read()\nf2 = f2.replace(\"\\n\",\" \")\n</code></pre>\n\n<p>with a single assignment to it</p>\n\n<pre><code>f2 = f.read().replace(\"\\n\",\" \")\n</code></pre>\n\n<p>But ultimately, you don't need <code>f2</code> at all.</p>\n\n<hr>\n\n<p>The <code>i</code> variable does not seem to be useful.</p>\n\n<hr>\n\n<p>I had troubles testing your code on your example because an empty string was messing with the conversion to int. I took the liberty to had a simple <code>if item</code> in the loop to deal with this but you can probably find other solutions depending on the input files you want to accept.</p>\n\n<hr>\n\n<p>The whole <code>load_program</code> function can be rewritten in a more concise way with list comprehension :</p>\n\n<pre><code>def load_program(f2o):\n with open(f2o, \"r\") as f:\n bcode = f.read().replace(\"\\n\",\" \").split(\" \")\n return [int(item,16) for item in bcode if item]\n</code></pre>\n\n<hr>\n\n<p>Many variables are defined but not used : just get rid of them!</p>\n\n<p>The same comment applies to unused parameters.</p>\n\n<hr>\n\n<p>You could use the Boolean type for the <code>loop</code> variable. You could also get rid of it altogether by using <a href=\"http://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops\">break</a> (this is a bit personal, some like it with a <code>loop</code> variable, I'd rather see avoid it).</p>\n\n<hr>\n\n<p>Actually, going further, one can easily spot that this <code>while</code> loop is nothing but a <code>for</code> loop in disguise. What you want is just <code>ip</code> to go from <code>0</code> to <code>len(cb)-1</code>. The pythonic way to write this is : </p>\n\n<pre><code>for ip in range(len(b)):\n</code></pre>\n\n<p>Also, if what you want is to iterate over a container and also get the corresponding index, the pythonic way is :</p>\n\n<hr>\n\n<p><code>ba = str(b[i + 1])</code> probably deserves some extra logic you don`t go too far.</p>\n\n<hr>\n\n<p>In :</p>\n\n<pre><code> if bc == OP_PUSH:\n if bc != OP_EOI:\n</code></pre>\n\n<p>you are comparing <code>bc</code> to <code>2</code> and if they are equal you compare <code>bc</code> to <code>1</code>. As far as I can understand, the second check is not useful at all.</p>\n\n<hr>\n\n<p>At this stage, my current version of the code is :</p>\n\n<pre><code>#!/usr/bin/python\n\nstack = []\n\n'''\nInstructions\n'''\nOP_PUSH = 2\nOP_PRINT = 3\n\ndef load_program(f2o):\n with open(f2o, \"r\") as f:\n bcode = f.read().replace(\"\\n\",\" \").split(\" \")\n return [int(item,16) for item in bcode if item]\n\n# VM action functions\ndef do_EOP():\n print \"End of Program\"\n\ndef do_PUSH(ba):\n stack.insert(0, ba)\n\ndef do_PRINT(stack):\n stk = stack[0].split(\" \")\n for item in stk:\n print unichr(int(item))\n\n\ndef execute_program(b):\n for i,bc in enumerate(b):\n if bc == OP_PUSH:\n ba = str(b[i + 1])\n do_PUSH(ba)\n elif bc == OP_PRINT:\n do_PRINT(stack)\n\ndef run_program(f):\n execute_program(load_program(f))\n\ndef main(argv):\n run_program(argv[1])\n return 0\n\ndef target(*args):\n return main, None\n\nif __name__ == '__main__':\n import sys\n main(sys.argv)\n</code></pre>\n\n<p>but I'm realising that many things are probably wrong and nor nearly as tested as they should be giving the amount of things I've removed without any impact on the test you have provided.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T23:14:41.420", "Id": "45166", "ParentId": "45158", "Score": "5" } } ]
{ "AcceptedAnswerId": "45164", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T21:35:12.847", "Id": "45158", "Score": "11", "Tags": [ "python", "python-2.x", "interpreter", "rpython" ], "Title": "Virtual machine using RPython and PyPy" }
45158
<p>I'm using a third-party library which utilizes <a href="http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm" rel="noreferrer"><code>boost::shared_ptr</code></a> for memory management.</p> <p>The problem is that I need to allocate many objects and I have detected that the allocation and deallocation is rather resource-demanding. So I thought I should utilize a smart-pointer memory pool to reduce the overhead.</p> <pre><code>#include &lt;boost/smart_ptr/make_shared_array.hpp&gt; template &lt;class T, size_t pool_size&gt; class shared_ptr_pool { boost::shared_ptr&lt;T[]&gt; pool; size_t avail = 0; public: boost::shared_ptr&lt;T&gt; make_shared() { if (!avail) { pool = boost::make_shared&lt;T[]&gt;(pool_size); avail = pool_size; } return boost::shared_ptr&lt;T&gt;(pool, &amp;pool[--avail]); } }; </code></pre> <p>The solution is to utilize <a href="http://www.boost.org/doc/libs/release/libs/smart_ptr/make_shared_array.html" rel="noreferrer"><code>make_shared</code> for arrays</a> and the <a href="http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm#aliasing_constructor" rel="noreferrer"><code>shared_ptr</code> aliasing constructor</a>. The solution in inherently thread-unsafe, but for my needs that is okay.</p> <p>Any thoughts, comments or pretty much anything would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T01:07:10.153", "Id": "78677", "Score": "0", "body": "The main advantage of a pool is that released pointers can quickly be re-used. I don't see that functionality here. Once your pool is empty you need to re-create another pool." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T01:26:06.770", "Id": "78857", "Score": "0", "body": "This might be a silly question. But why would you use a third party library for something that is already in the language?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T08:44:00.000", "Id": "78881", "Score": "1", "body": "@Mads: The third-party library I use in turn use `boost::shared_ptr` because of performance, portability and it correctly uses `delete[]` on array types." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T08:46:28.187", "Id": "78883", "Score": "0", "body": "@LokiAstari: You are correct, this isn't a pool as such, as it doesn't return objects to the pool, but a chunk-allocator-thingy (?)." } ]
[ { "body": "<p>Per the comments, this isn't really a \"pool\" because things don't go back into it when you're done using them. It's just an \"incremental allocator\" that does allocation in \"chunks\". A better name for it might be <code>shared_ptr_chunk_allocator</code> (and <code>chunk_size</code> instead of <code>pool_size</code>).</p>\n\n<p>Given that <code>pool_size</code> is used only on the codepath that also allocates memory (so it's not a super speed-critical path where one more memory load would hurt performance), and <code>shared_ptr_pool&lt;...&gt;</code> has non-static data members (so there's no harm in adding one more non-static data member), surely it would make more sense to make <code>pool_size</code> a runtime parameter to <code>shared_ptr_pool</code>'s constructor.</p>\n\n<pre><code>// your current code:\nshared_ptr_pool&lt;myclass, 16&gt; pool;\n// versus my suggestion:\nshared_ptr_pool&lt;myclass&gt; pool(16);\n</code></pre>\n\n<p>This would even allow you to provide a member function for modifying the chunk size on the fly, in case maybe your code could detect that its particular workload demanded a bigger chunk size.</p>\n\n<pre><code>if (memory_usage_low &amp;&amp; still_spending_lots_of_time_in_allocation) {\n pool.set_chunk_size(pool.chunk_size() * 2);\n}\n</code></pre>\n\n<p>The actual code implementation looks fine to me; nothing to complain about there. :)</p>\n\n<p>You might be pleased to (or, you might already) know that <code>std::shared_ptr&lt;T[]&gt;</code> is part of the Library Fundamentals v1 Technical Specification, which I think means it <em>ought</em> to be coming to C++1z. However, it's not in the working draft yet as of N4567 (November 2015).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-24T21:12:14.497", "Id": "115006", "ParentId": "45161", "Score": "5" } } ]
{ "AcceptedAnswerId": "115006", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T22:47:33.710", "Id": "45161", "Score": "8", "Tags": [ "c++", "c++11", "memory-management", "boost", "smart-pointers" ], "Title": "Smart pointer memory pool" }
45161
<p>I'm working on a little game where you press a button and a new image appears. There's a glitch every time you ask a new image to display and it occurred to me that I should preload the necessary images. However, I'm not sure how to do this efficiently as I'm not using a variable to display the images. It's also been pointed out to me that I should look into storing reference for the elements, but I don't know how to go about doing so. <a href="http://theyellowparachute.com/test/Jajo/" rel="nofollow">This</a> is what I'm working on. Any suggestions?</p> <p>HTML:</p> <pre><code>&lt;body onLoad="setup()"&gt; &lt;div id="wrapper"&gt; &lt;div id="jajo"&gt;&lt;/div&gt;&lt;!--this is where jajo will be displayed--&gt; &lt;div id="directions"&gt;&lt;/div&gt;&lt;!--directions for how to interact with jajo--&gt; &lt;/div&gt;&lt;!--wrapper--&gt; &lt;/body&gt; </code></pre> <p>JavaScript:</p> <pre><code>// Calls the loadJajo function and passes the image URL // Initiates directionSlide function function setup() { loadJajo('jajo.png'); elem = document.getElementById('directions'); directionSlide(); } //Creates a new image object (Jajo) and writes it to the page. function loadJajo(jajoSRC) { var main = document.getElementById('jajo'); // Creates an variable to represent the "main" division var defaultJajo = document.createElement('img'); // Creates a new image object (default Jajo image) defaultJajo.src = jajoSRC; // adds the source file name to the defaultJajo image object main.appendChild(defaultJajo); //puts the defaultJajo object inside the "main" division } // Listen for key pressed events. document.onkeydown = function(event) { var keyPress = String.fromCharCode(event.keyCode); // Assigns value of key pressed to variable. if(keyPress == "W") { // If 'W' is pressed, display Jajo waving. document.getElementById("jajo").innerHTML= "&lt;img alt='car' src='jajo_wave.png'&gt;"; document.onkeyup = function(event) { // If 'W' is released, display default Jajo. document.getElementById("jajo").innerHTML= "&lt;img alt='Jajo' src='jajo.png'&gt;"; } } else if(keyPress == "A") { // If 'A' is pressed, display Jajo winking. document.getElementById("jajo").innerHTML= "&lt;img alt='car' src='jajo_wink.png'&gt;"; document.onkeyup = function(event) { // If 'A' is released, display default Jajo. document.getElementById("jajo").innerHTML= "&lt;img alt='Jajo' src='jajo.png'&gt;"; } } else if(keyPress == "S") { // If 'S' is pressed, display transparent Jajo. document.getElementById("jajo").innerHTML= "&lt;img alt='car' src='jajo_invisible.png'&gt;"; document.onkeyup = function(event) { // If 'S' is released, display default Jajo. document.getElementById("jajo").innerHTML= "&lt;img alt='Jajo' src='jajo.png'&gt;"; } } else if(keyPress == "D") { // If 'D' is pressed, display purple Jajo. document.getElementById("jajo").innerHTML= "&lt;img alt='car' src='jajo_purple.png'&gt;"; document.onkeyup = function(event) { // If 'D' is released, display default Jajo. document.getElementById("jajo").innerHTML= "&lt;img alt='Jajo' src='jajo.png'&gt;"; } } else if(keyPress == "E") { // If 'E' is pressed, display Jajo eating a carrot. document.getElementById("jajo").innerHTML= "&lt;img alt='car' src='jajo_carrot.png'&gt;"; document.onkeyup = function(event) { // If 'E' is released, display default Jajo. document.getElementById("jajo").innerHTML= "&lt;img alt='Jajo' src='jajo.png'&gt;"; } } } var elem; var i = 0; // Counter variable. // Array with directions for interacting with Jajo. var directionArray = ["This is Jajo, your new pet monster!", "Jajo wants to say 'Hi!'&lt;br&gt;Press and hold 'W'", "Jajo has some special skills.&lt;br&gt;Press and hold 'D' to see one!", "Jajo is hungry for a healthy snack.&lt;br&gt;Press and hold 'E'", "Jajo wants to show you his secret power.&lt;br&gt;Press and hold 'S'", "That secret is just between you and Jajo!&lt;br&gt;Press and hold 'A'"]; // Transitions one direction to the next. function nextDirection() { i++; // Continuously add 1 to i. elem.style.opacity = 0; // Directions opacity at 0%. if(i &gt; (directionArray.length - 1)) { // Resets counter to 0 when it reaches the end of the array. i = 0; } setTimeout(directionSlide,1000); // Set time delay for transition between directions. } // Displays direction one at a time. // http://www.developphp.com/view.php?tid=1380 function directionSlide() { elem.innerHTML = directionArray[i]; // Displays direction based on position of counter variable. elem.style.opacity = 1; // Direction opacity at 100%. setTimeout(nextDirection,5000); // Set time delay for display of directions. } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:06:38.120", "Id": "78720", "Score": "0", "body": "Do all the images need to be individual? you'd most likely be better of using a sprite sheet loading that. http://stackoverflow.com/questions/8050152/why-use-a-sprite-sheet-rather-than-individual-images" } ]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li><p>Please indent your functions, bad:</p>\n\n<pre><code>function setup() {\nloadJajo('jajo.png');\nelem = document.getElementById('directions');\ndirectionSlide();\n}\n</code></pre>\n\n<p>better:</p>\n\n<pre><code>function setup() {\n loadJajo('jajo.png');\n elem = document.getElementById('directions');\n directionSlide();\n}\n</code></pre></li>\n<li>Consider having only 1 comma separated <code>var</code> statement on the top of your code</li>\n<li><p>Lighten up on the comments, you are overdoing it, this:</p>\n\n<pre><code>//Creates a new image object (Jajo) and writes it to the page.\nfunction loadJajo(jajoSRC) {\nvar main = document.getElementById('jajo'); // Creates an variable to represent the \"main\" division\nvar defaultJajo = document.createElement('img'); // Creates a new image object (default Jajo image)\ndefaultJajo.src = jajoSRC; // adds the source file name to the defaultJajo image object\nmain.appendChild(defaultJajo); //puts the defaultJajo object inside the \"main\" division\n}\n</code></pre>\n\n<p>could be this:</p>\n\n<pre><code>//Creates a new image object (Jajo) and writes it to the page.\nfunction loadJajo(jajoSRC) {\n var main = document.getElementById('jajo'), \n defaultJajo = document.createElement('img'); \n defaultJajo.src = jajoSRC; \n main.appendChild(defaultJajo); \n}\n</code></pre></li>\n<li><p>You are actually storing a reference to an element here:</p>\n\n<pre><code>elem = document.getElementById('directions');\n</code></pre>\n\n<p>However, you should call <code>elem</code> differently, probably <code>directions</code>. Also, you should consider caching <code>document.getElementById('jajo')</code> since you use it a ton of times.</p></li>\n<li><p>There is a clear mapping in your code between key presses and images, you could write your <code>keydown</code> handler like this:</p>\n\n<pre><code>var keyImageMap = \n{\n 'W' : 'jajo_wave.png', // If 'W' is released, display default Jajo.\n 'A' : 'jajo_wink.png', // If 'A' is pressed, display Jajo winking.\n 'S' : 'jajo_invisible.png', // If 'S' is pressed, display transparent Jajo.\n 'D' : 'jajo_purple.png', // If 'D' is pressed, display purple Jajo.\n 'E' : 'jajo_carrot.png' // If 'E' is pressed, display Jajo eating a carrot.\n}\n\n// Listen for key pressed events.\ndocument.onkeydown = function(event) {\n // Assigns value of key pressed to variable.\n var keyPress = String.fromCharCode(event.keyCode); \n\n if( keyImageMap[ keyPress ] )\n {\n document.getElementById('jajo').innerHTML = '&lt;img alt=\"car\" src=\"' + keyImageMap[ keyPress ] + '\"&gt;';\n }\n}\n</code></pre></li>\n<li>In the previous sample code you should of course have used a reference to <code>jajo</code> instead of calling <code>document.getElementById</code>. Also you should have deep thoughts on rewriting that image tag every time, perhaps it would be better to have a reference to the image and then keep changing <code>src</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:29:55.150", "Id": "45305", "ParentId": "45162", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T22:58:03.230", "Id": "45162", "Score": "5", "Tags": [ "javascript", "beginner", "image" ], "Title": "Preloading images in JavaScript" }
45162
<p>I'm currently in the process of coding a QuadTree. The QuadTree seperates into four quadrants, with 1 being the top right and 4 being the bottom right. I have this code to determine which quadrant the AABB fits into: </p> <pre><code>int getIndex(AABB aabb) { int index = -1; double vertMid = bounds.getX() + (bounds.getWidth() / 2); double horzMid = bounds.getY() + (bounds.getHeight() / 2); // Fits in top bool topQuadrant = aabb.getY() &lt; horzMid &amp;&amp; aabb.getY() + aabb.getHeight() &lt; horzMid; // Fits in botom bool bottomQuadrant = aabb.getY() &gt; horzMid &amp;&amp; aabb.getY() + aabb.getHeight() &lt; bounds.getY() + bounds.getHeight(); // Fits in left if (aabb.getX() &lt; vertMid &amp;&amp; aabb.getX() + aabb.getWidth() &lt; vertMid) { if (topQuadrant) { index = 1; } else if (bottomQuadrant) { index = 2; } } // Fits in right else if (aabb.getX() &gt; vertMid &amp;&amp; aabb.getX() + aabb.getWidth() &lt; bounds.getX() + bounds.getWidth()) { if (topQuadrant) { index = 0; } else if (bottomQuadrant) { index = 3; } } return index; } </code></pre> <p><code>-1</code> indicates it cannot be subdivided<br> <code>1</code> indicates top right<br> <code>2</code> indicates top left<br> <code>3</code> indicates bottom left<br> <code>4</code> indicates bottom right </p> <p>How can I speed it up/make it cleaner? At the moment it is quite slow and I feel like there is an easier way to do it.</p>
[]
[ { "body": "<p>Note, you indicate in the text that you have quadrants:</p>\n\n<pre><code> 2 1\n 3 4\n</code></pre>\n\n<p>But your code has the quadrants:</p>\n\n<pre><code> 1 0\n 2 3\n</code></pre>\n\n<p>I recommend you have a function that works on just one point at a time. There are two points, the 'bottom left', and the 'top right'.</p>\n\n<p>So, calculate the quadrant of each point. If they are both in the same quadrant, return the quadrant, otherwise return -1;</p>\n\n<pre><code>int getPointIndex(double horzMid, double vertMid , double x, double y) {\n int quad = 0;\n if (y &lt; horzMid) {\n quad = x &lt; vertMid ? 2 : 3;\n } else {\n quad = x &lt; vertMid ? 1 : 0;\n }\n return quad;\n}\n</code></pre>\n\n<p>Then, using this function you can:</p>\n\n<pre><code>int getIndex(AABB aabb) {\n\n double vertMid = bounds.getX() + (bounds.getWidth() / 2);\n double horzMid = bounds.getY() + (bounds.getHeight() / 2);\n\n // Quadrant of bottom-left point.\n int blQuad = getPointIndex(horzMid, vertMid, aabb.getX(), aabb.getY())\n // Quadrant of top-right point.\n int trQuad = getPointIndex(horzMid, vertMid, aabb.getX() + aabb.getWidth(), aabb.getY() + aabb.getHeight())\n\n if (blQuad == trQuad) {\n return blQuad;\n }\n\n return -1;\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T00:56:51.207", "Id": "45174", "ParentId": "45172", "Score": "8" } }, { "body": "<p>Assuming that getHeight is a non-negative number, this statement ...</p>\n\n<pre><code>bool topQuadrant = aabb.getY() &lt; horzMid &amp;&amp; aabb.getY() + aabb.getHeight() &lt; horzMid;\n</code></pre>\n\n<p>... can be reduced to ...</p>\n\n<pre><code>bool topQuadrant = aabb.getY() + aabb.getHeight() &lt; horzMid;\n</code></pre>\n\n<p>Similarly ...</p>\n\n<pre><code>bool bottomQuadrant = aabb.getY() &gt; horzMid;\n</code></pre>\n\n<p>If the <code>aabb.getY() + aabb.getHeight() &lt; bounds.getY() + bounds.getHeight();</code> expression is necessary in the latter, then perhaps you need to add <code>&amp;&amp; aabb.getY() &gt; bounds.getY()</code> to your test for <code>topQuadrant</code>.</p>\n\n<hr>\n\n<p>A similar comment for your horizontal tests.</p>\n\n<hr>\n\n<p>You can add ...</p>\n\n<pre><code>if (!topQuadrant &amp;&amp; !bottomQuadrant)\n return -1;\n</code></pre>\n\n<p>... before you do the horizontal test (to avoid time spent doing the horizontal test if it's in neither the top nor bottom).</p>\n\n<p>After that (if it's in the top or bottom) then if it's in the left quadrant you can do ...</p>\n\n<pre><code>return (topQuadrant) ? 1 : 2;\n</code></pre>\n\n<hr>\n\n<p>You won't need the index variable any more.</p>\n\n<hr>\n\n<p>Consider precomputing/cacheing vertMid and horzMid inside the bounds structure.</p>\n\n<hr>\n\n<p><code>AABB</code> is a nasty name for a type.</p>\n\n<p>Also you should pass it by const reference instead of by value (passing by value passes a copy of it, which is slower than passing by reference).</p>\n\n<hr>\n\n<p><code>getIndex</code> should perhaps be a method of whatever type your <code>bounds</code> is.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T01:17:20.593", "Id": "78681", "Score": "0", "body": "@Tips48 You can also precompute/cache `getY() + getHeight()` and `getX() + getWidth()` ... name them getLeft(), getRight(), getTop(), and getBottom()." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T01:02:33.217", "Id": "45176", "ParentId": "45172", "Score": "6" } } ]
{ "AcceptedAnswerId": "45176", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T00:34:15.153", "Id": "45172", "Score": "7", "Tags": [ "c++", "performance", "tree" ], "Title": "Determine quadrant of code" }
45172
<p>I have some triggers placing and sizing elements for video controls. It works well enough but mostly through trial and error and I am not sure if there is a better pattern:</p> <p>The full source can be found <a href="http://jsfiddle.net/Xa93a/" rel="nofollow">here</a> and webpage <a href="https://media.themetacity.com/3/" rel="nofollow">here</a>.</p> <p>My biggest issue I think is when is it appropriate to have an element listen (e.g. on the specific element or on window) and when should I call the reposition trigger (each time or only once at the end).</p> <pre><code>$(document).ready(function () { "use strict"; var videos = $("video"), doc = document, fsVideoTime, fsVideo; Number.prototype.leftZeroPad = function (numZeros) { var n = Math.abs(this), zeros = Math.max(0, numZeros - Math.floor(n).toString().length), zeroString = Math.pow(10, zeros).toString().substr(1); if (this &lt; 0) { zeroString = '-' + zeroString; } return zeroString + n; }; function isVideoPlaying(video) { return !(video.paused || video.ended || video.seeking || video.readyState &lt; video.HAVE_FUTURE_DATA); } // Pass in object of the video to play/pause and the control box associated with it function playPause(video) { var $playPauseButton = $("#playPauseButton", video.parent); if (isVideoPlaying(video)) { video.pause(); $playPauseButton[0].src = "/static/images/smallplay.svg"; $playPauseButton[0].alt = "Button to play the video"; $playPauseButton[0].title = "Play"; } else { video.play(); $playPauseButton[0].src = "/static/images/smallpause.svg"; $playPauseButton[0].alt = "Button to pause the video"; $playPauseButton[0].title = "Pause"; } } function rawTimeToFormattedTime(rawTime) { var chomped, seconds, minutes; chomped = Math.floor(rawTime); seconds = chomped % 60; minutes = Math.floor(chomped / 60); return minutes.leftZeroPad(2) + ":" + seconds.leftZeroPad(2); } $(videos).each(function () { var video = this, $videoContainer = $("#vidContainer"), $controlsBox = $("#videoControls"), $playProgress = $("#playProgress", $controlsBox), $poster, customStartPoster, $endPoster, customEndPoster, errorPoster, $currentTimeSpan = $(".currentTimeSpan", $controlsBox), $durationTimeSpan = $(".durationTimeSpan", $controlsBox), $trackMenu = $("#trackMenu"), $tracksButton = $("#tracksButton"), $loadingProgress = $("#loadProgress"), $playPauseButton = $("#playPauseButton", $controlsBox), $soundButton = $("#soundButton", $controlsBox), $soundVolume = $("#soundLevel", $controlsBox); if (this.controls) { this.controls = false; } $(video).on("timeupdate", function () { $playProgress[0].value = (video.currentTime / video.duration) * 1000; $currentTimeSpan.text(rawTimeToFormattedTime(video.currentTime)); }).on("play", function () { if ($poster.length !== 0) { $poster.remove(); } }).on("loadedmetadata", function () { var canPlayVid = false; $("source", $(video)).each(function () { if (video.canPlayType($(this).attr("type"))) { canPlayVid = true; } }); if (!canPlayVid) { errorPoster = "/static/images/movieerror.svg"; $.get(errorPoster, function (svg) { errorPoster = doc.importNode(svg.documentElement, true); $(errorPoster).attr("class", "poster errorposter"); $(errorPoster).attr("height", $(video).height()); $(errorPoster).attr("width", $(video).width()); $("source", $(video)).each(function () { var newText = doc.createElementNS("http://www.w3.org/2000/svg", "tspan"), link = doc.createElementNS("http://www.w3.org/2000/svg", "a"); newText.setAttributeNS(null, "x", "50%"); newText.setAttributeNS(null, "dy", "1.2em"); link.setAttributeNS("http://www.w3.org/1999/xlink", "href", this.src); link.appendChild(doc.createTextNode(this.src)); newText.appendChild(link); $("#sorrytext", errorPoster).append(newText); }); $videoContainer.append(errorPoster); $($videoContainer).trigger("reposition"); }); } else { $($currentTimeSpan).text(rawTimeToFormattedTime(this.currentTime)); $($durationTimeSpan).text(rawTimeToFormattedTime(this.duration)); } }).on("click", function () { playPause(video); }).on("ended", function () { $playPauseButton[0].src = "/static/images/smallplay.svg"; $playPauseButton[0].alt = "Button to play the video"; $playPauseButton[0].title = "Play"; // Poster to show at end of movie if (video.dataset.endposter) { customEndPoster = video.dataset.endposter; } else { customEndPoster = "/static/images/endofmovie.svg"; // If none supplied, use our own, generic one } // Get the poster and make it inline // File is SVG so usual jQuery rules may not apply // File needs to have at least one element with "playButton" as class $.get(customEndPoster, function (svg) { $endPoster = doc.importNode(svg.documentElement, true); $endPoster = $($endPoster); $endPoster.attr("class", "poster endposter"); $endPoster.attr("height", $(video).height()); $endPoster.attr("width", $(video).width()); $("#playButton", $endPoster).on("click", function () { playPause(video); $endPoster.remove(); // done with poster forever }); $videoContainer.append($endPoster); $($videoContainer).trigger("reposition"); }); }); // Setup the div container for the video, controls and poster $videoContainer.on("reposition", function () { // Move posters and controls back into position after video position updated var $poster = $(".poster", this); $poster.offset({top: $("video", this).offset().top, left: $("video", this).offset().left}); $poster.attr("height", $(video).height()); $poster.attr("width", $(video).width()); $trackMenu.css({top: $tracksButton.offset().top + $tracksButton.height() + "px", left: $tracksButton.offset().left + $tracksButton.width() - $trackMenu.width() + "px"}); $soundVolume.css({top: $soundButton.offset().top - $soundVolume.height() + "px", left: $soundButton.offset().left + "px"}); $loadingProgress.css({top: $loadingProgress.parent().offset().top + "px", left: $loadingProgress.parent().offset().left + "px"}); }); // Setup play/pause button $playPauseButton.on("click", function () { playPause(video); }); // Setup progress bar $playProgress.on("change", function () { video.currentTime = video.duration * (this.value / 1000); }).on("mousedown", function () { video.pause(); }).on("mouseup", function () { video.play(); }); // Full screen $("#fullscreenButton").on("click", function () { if (video.requestFullScreen) { video.requestFullScreen(); fsVideo = video; } else if (video.webkitRequestFullScreen) { video.webkitRequestFullScreen(); fsVideo = video; } else if (video.mozRequestFullScreen) { video.mozRequestFullScreen(); fsVideo = video; } }); // Work out if there is audio to control // Not the greatest way but doesnt look like there is much other option (if any?)... $("source", video).each(function () { if (this.src === video.currentSrc) { if (this.type.split(',').length === 1) { // Split happens on the: codecs="vp8,vorbis"' part $soundButton[0].src = "/static/images/nosound.svg"; $soundButton[0].alt = "Icon showing no sound is available"; $soundButton[0].title = "No sound available"; $soundVolume.remove(); } else { // If it DOES have sound $soundVolume.css({top: $soundButton.offset().top - $soundVolume.height() + "px", left: $soundButton.offset().left + "px"}); } return false; } return true; }); // Check if there needs to be an option menu for tracks made if (video.textTracks.length === 0) { $tracksButton.attr("src", $tracksButton.attr("src").replace("tracks.svg", "notracks.svg")); $tracksButton.attr("alt", "No tracks are available"); $tracksButton.attr("Title", "No tracks are available"); } else { $(video.textTracks).each(function () { this.mode = "hidden"; }); } if ($trackMenu.length) { $("li", "#trackMenu").on("click", function () { $(this).parent().children("li").removeClass("activeTrack"); $(this).addClass("activeTrack"); // 'None' &lt;li&gt; is clicked so disable all the tracks if ($(this).text().toLowerCase() === "none") { $(video.textTracks).each(function () { this.mode = "hidden"; }); // Find the track referred to and activate it } else { var kind = $(this).text().split(":")[0].toLowerCase(), srclang = $(this).text().split("(")[1].slice(0, -1); $(video.textTracks).each(function () { if (this.kind === kind &amp;&amp; this.language === srclang) { this.mode = "showing"; // change to this track } else { this.mode = "hidden"; // Turn off other tracks } }); } }); $trackMenu.css({top: $tracksButton.offset().top + $tracksButton.height() + "px", left: $tracksButton.offset().left + $tracksButton.width() - $trackMenu.width() + "px"}); } $loadingProgress.width($controlsBox.width()); $loadingProgress.css({top: $controlsBox.offset().top + "px", left: $controlsBox.offset().left + "px"}); (function () { var progressInterval = setInterval(function () { var totalBuffered = 0, i; $loadingProgress[0].value = (video.duration / video.buffered.end(0)) * 100; for (i = 0; i &lt; video.buffered.length; i += 1) { totalBuffered += video.buffered.start(i) + video.buffered.end(i); } if (totalBuffered === video.duration) { $loadingProgress.fadeOut(); clearInterval(progressInterval); } }, 1000); }()); $soundVolume.css({top: $soundButton.offset().top - $soundVolume.height() + "px", left: $soundButton.offset().left + "px"}); $soundVolume.on("change", function (){ video.volume = (this.value / 100); }); // Posters to show before the user plays the video customStartPoster = this.dataset.startposter; if (!customStartPoster) { customStartPoster = "/static/images/genericstartposter.svg"; // If none supplied, use our own, generic one } // Get the poster and make it inline // File is SVG so usual jQuery rules may not apply // File needs to have at least one element with "playButton" as class $.get(customStartPoster, function (svg) { $poster = doc.importNode(svg.documentElement, true); $poster = $($poster); $poster.attr("class", "poster"); $poster.attr("height", $(video).height()); $poster.attr("width", $(video).width()); $("#playButton", $poster).on("click", function () { video.load(); // Initial data and metadata load events may have fired before they can be captured so manually fire them playPause(video); $poster.remove(); // done with poster forever }); $videoContainer.append($poster); $($videoContainer).trigger("reposition"); }); $($videoContainer).trigger("reposition"); //Get its position right. }); // Handle coming out of fullscreen $(doc).on("webkitfullscreenchange mozfullscreenchange fullscreenchange", function () { var isFullScreen = doc.fullScreen || doc.mozFullScreen || doc.webkitIsFullScreen; if (isFullScreen) { // Now in full screen fsVideo = doc.fullscreenElement || doc.mozFullScreenElement || doc.webkitFullscreenElement; fsVideoTime = fsVideo.currentTime; $("source", fsVideo).each(function () { // .dataset.fullscreen is is treated a boolean, but it is just truthy string // This function uses a standard format of names of full screen appropriate vids as shown below: // original: originalvid.xyz full screen: originalvid.fullscreen.xyz // N.B. Can not have period (".") in original file same except for filetype if (this.dataset.fullscreen) { var splitSrc = this.src.split("."); this.src = splitSrc[0] + "." + splitSrc[1] + "." + splitSrc[2] + ".fullscreen." + splitSrc[3]; } fsVideo.load(); //Reload with the new source }); } else { // Have left full screen and need to return to lower res video fsVideoTime = fsVideo.currentTime; $("source", fsVideo).each(function () { // Remove the full screen and go back to the original file if (this.dataset.fullscreen) { var splitSrc = this.src.split("."); this.src = splitSrc[0] + "." + splitSrc[1] + "." + splitSrc[2] + "." + splitSrc[4]; } // Nothing was changed if data-fullscreen is false so no need to do anything $(this).parent().load(); // The video $(this).parent().trigger("reposition"); // The video container box }); } $(fsVideo).on("loadedmetadata", function () { this.currentTime = fsVideoTime; // Skip to the time before we went full screen playPause(fsVideo); }); }); $(window).on("resize", function () { $(videos).each(function () { $(this).parent().trigger("reposition"); }); }); $(window).trigger("reposition"); }); </code></pre> <p>The second trigger comes in at the end of a big loop and the first on a specific event. Is one way better than another or are both appropriate in this situation?</p> <p>This is by far the biggest JS project I have worked on so please be brutal as need be and help me make it better.</p>
[]
[ { "body": "<p>This small snippet makes it hard to review.</p>\n\n<p>Your question:</p>\n\n<ul>\n<li><p>My biggest issue I think is when is it appropriate to have an element listen (eg on the specific element or on window) </p>\n\n<ul>\n<li>Let the element emit the event, the day that you need 2 video controls, you will be pleased</li>\n</ul></li>\n<li><p>When should I call the re-position trigger (each time or only once at the end).</p>\n\n<ul>\n<li>You should call <code>trigger(\"reposition\");</code> as little as possible, consider delegating the responsibility of calling it to the user of your object ?</li>\n</ul></li>\n</ul>\n\n<p>Other than that</p>\n\n<ul>\n<li><p>You could chain your jQuery functions: </p>\n\n<pre><code>$poster.attr(\"class\", \"poster\");\n .attr(\"height\", $(video).height());\n .attr(\"width\", $(video).width());\n</code></pre></li>\n<li><p><code>importNode</code> is not such a commonly used function, consider passing a <code>deepCopy = true</code> variable which would then auto document the function.</p></li>\n<li>Fair amount of commenting, good style.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-02T01:25:43.983", "Id": "80256", "Score": "0", "body": "Thanks for taking the time to help with this.\n\nA couple of quick questions:\n\nHow do you mean let the element emit the event? Looking at pages like: http://stackoverflow.com/questions/13438924/what-is-an-event-emitter and http://new-bamboo.co.uk/blog/2010/07/14/custom-event-emitters-in-javascript look like what I am doing already and I am not sure of the difference/significance. Can you point me in a better direction?\n\nN.B. for someone reading this later: importNode behaviour has changed with regards to deep copying, read https://developer.mozilla.org/en-US/docs/Web/API/document.importNode" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-04T13:51:52.173", "Id": "80767", "Score": "0", "body": "I answered your question, and indeed you are doing the right thing. I am sorry about communicating that poorly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T19:47:17.547", "Id": "45879", "ParentId": "45175", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T01:00:49.770", "Id": "45175", "Score": "4", "Tags": [ "javascript", "jquery", "html", "dom", "video" ], "Title": "Triggers placing and sizing elements for video controls" }
45175
<p>I'm currently implementing my own QuadTree in C++. It runs well with 100 items, but once you start adding more it slows down. <code>remove</code>, <code>getAll</code>, and <code>insert</code> have all been profiled as taking a while. Any advice is appreciated! </p> <pre><code>class QuadTree { private: const static int MAX_OBJECTS = 20; AABB bounds; std::vector&lt;QuadTree&gt; children; std::set&lt;Locatable*&gt; entities; std::set&lt;Locatable*&gt; allEntities; // Internal methods void split() { children.clear(); double width = (bounds.getWidth() / 2); double height = (bounds.getHeight() / 2); double x = bounds.getX(); double y = bounds.getY(); children.push_back(QuadTree(AABB(x + width, y, width, height))); children.push_back(QuadTree(AABB(x, y, width, height))); children.push_back(QuadTree(AABB(x, y + height, width, height))); children.push_back(QuadTree(AABB(x + width, y + height, width, height))); } int getIndex(AABB&amp; aabb) { double vertMid = bounds.getVertMid(); double horzMid = bounds.getHorzMid(); // Fits in top bool topQuadrant = aabb.getY() + aabb.getHeight() &lt; horzMid; // Fits in botom bool bottomQuadrant = aabb.getY() &gt; horzMid; // Fits in left if (aabb.getX() + aabb.getWidth() &lt; vertMid) { if (topQuadrant) { return 1; } else if (bottomQuadrant) { return 2; } } // Fits in right else if (aabb.getX() &gt; vertMid) { if (topQuadrant) { return 0; } else if (bottomQuadrant) { return 3; } } return -1; } void merge(std::set&lt;Locatable*&gt;&amp; one, std::set&lt;Locatable*&gt; two) { one.insert(two.begin(), two.end()); } // End Internal methods public: QuadTree(AABB bounds) : bounds(bounds) { children.reserve(4); } // Base void clear() { entities.clear(); allEntities.clear(); for (auto it = children.begin(); it != children.end(); it++) { it-&gt;clear(); } children.clear(); } void insert(Locatable* object) { AABB aabb = object-&gt;getAABB(); allEntities.insert(object); if (entities.size() &gt; MAX_OBJECTS) { if (children.empty()) { split(); auto it = entities.begin(); while (it != entities.end()) { int index = getIndex((*it)-&gt;getAABB()); if (index != -1) { children.at(index).insert(*it); it = entities.erase(it); } else { it++; } } } int index = getIndex(aabb); if (index != -1) { children.at(index).insert(object); } else { entities.insert(object); } } else { entities.insert(object); } } void remove(Locatable* object, AABB aabb) { auto it = allEntities.find(object); if (it == allEntities.end()) { return; } allEntities.erase(it); it = entities.find(object); if (it == entities.end()) { if (!children.empty()) { int index = getIndex(aabb); if (index != -1) { children.at(index).remove(object, aabb); } } } else { entities.erase(it); } } QuadTree* getLowestRoot(AABB aabb) { int index = getIndex(aabb); if (index == -1 || children.empty()) { return this; } return children.at(index).getLowestRoot(aabb); } std::set&lt;Locatable*&gt; getAll() { std::set&lt;Locatable*&gt; result; if (children.empty()) { return entities; } result = entities; for (auto it = children.begin(); it != children.end(); it++) { merge(result, it-&gt;getAll()); } return result; } // End Base }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T03:56:29.707", "Id": "78696", "Score": "0", "body": "I was about to say/add that in my answer. Is your insert performance improved now? Do you have any performance problem remaining?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T03:56:31.323", "Id": "78697", "Score": "0", "body": "A big problem was that I was attempting 70 updates for second. I have dropped that number to 30." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T03:57:16.540", "Id": "78698", "Score": "0", "body": "Yeah, `getAll` and `remove` are still a little on the slow side" } ]
[ { "body": "<p><code>getAll</code> returns a <code>set</code>, which is an ordered set. The ordering will be done by comparing Location*. I doubt you care about the order of Location* and it would be faster to use <code>std::unordered_set</code> instead.</p>\n\n<p>Similarly, <code>remove</code> and <code>insert</code> might be faster if <code>entities</code> and <code>allEntities</code> were of type <code>std::unordered_set</code> instead of <code>std::set</code>.</p>\n\n<p>Use the <code>reserve</code> method, or the size_t argument passed to the constructor, to specify a size of unordered_set that's big enough for the expected number of objects in it.</p>\n\n<hr>\n\n<p>I don't understand why allEntities exists. The only way it's used is in remove, where it implements an early return if the object isn't in the Quadtree.</p>\n\n<p>If that's what it's for then you don't need it in every level: you only need it on the top-level Quadtree. Therefore you should have two types of Quadtree:</p>\n\n<ul>\n<li>A more complicated, top-level one which includes allEntities</li>\n<li>A simpler one used for children which doesn't include allEntities</li>\n</ul>\n\n<hr>\n\n<p>Beware that remove uses allEntities to test for existence in the tree, but the getLowestRoot method does not.</p>\n\n<p>And the getLowest Root should (to optimize performance) verify whether is has children before it calls getIndex.</p>\n\n<hr>\n\n<p>The remove method, as coded, should throw an exception if getIndex returns -1 (because that would be unexpected/theoretically impossible/a bug).</p>\n\n<hr>\n\n<p>split should call <code>children.reserve(4)</code> not <code>children.clear()</code> because it's only called once.</p>\n\n<hr>\n\n<blockquote>\n <p>Yeah, getAll and remove are still a little on the slow side.</p>\n</blockquote>\n\n<p>getAll just needs to return the contents of allEntities, instead of recursing into children.</p>\n\n<p>remove should be faster if you use unordered_set instead of set (see for example <a href=\"https://stackoverflow.com/q/1349734/49942\">Why on earth would anyone use set instead of unordered_set?</a>).</p>\n\n<p>remove would also be (slightly) faster if AABB were passed by reference instead of by value.</p>\n\n<p>I suspect that Locatable::getAABB should return a const reference, and that you shouldn't have statements like ...</p>\n\n<pre><code>AABB aabb = object-&gt;getAABB();\n</code></pre>\n\n<p>... but should instead prefer ...</p>\n\n<pre><code>const AABB&amp; aabb = object-&gt;getAABB();\n</code></pre>\n\n<hr>\n\n<p>The code is a bit careless with its use of comparisons; in the following code ...</p>\n\n<pre><code> bool topQuadrant = aabb.getY() + aabb.getHeight() &lt; horzMid;\n // Fits in botom\n bool bottomQuadrant = aabb.getY() &gt; horzMid;\n</code></pre>\n\n<p>... I would have expected <code>&lt;=</code> in the 1st comparison or <code>&gt;=</code>in the second.</p>\n\n<hr>\n\n<p>The insert method was buggy (very buggy and slightly buggy) until I commented and you fixed it twice. It now has a new problem:</p>\n\n<ul>\n<li>Immediately after you split, you no longer have 20 objects in entities</li>\n<li>Therefore the next several elements will be stored in entities instead of being assigned to a quadrant</li>\n</ul>\n\n<p>IMO you may want code like this:</p>\n\n<pre><code>// In the top-level type of Quadtree, which has allEntities member\n// assuming this type has Quadtree as a private superclass\nvoid insert(Locatable* object) {\n // only if this is the top-level type of Quadtree\n allEntities.insert(object);\n Quadtree::insert(object);\n}\n\n// In the type of Quadtree used for children and as a superclass of above\nvoid insert(Locatable* object) {\n\n if (children.empty()) {\n if (entities.size() &lt;= MAX_OBJECTS)) {\n // don't split\n entities.insert(object);\n return;\n }\n // else split existing elements\n // before inserting object into children\n split();\n\n auto it = entities.begin();\n while (it != entities.end()) {\n int index = getIndex((*it)-&gt;getAABB());\n if (index != -1) {\n children.at(index).insert(*it);\n // https://stackoverflow.com/q/15662412/49942\n it = entities.erase(it);\n }\n else {\n it++;\n }\n }\n }\n // else insert into children\n int index = getIndex(aabb-&gt;getAABB());\n if (index != -1) {\n children.at(index).insert(object);\n }\n else {\n entities.insert(object);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:12:46.060", "Id": "79071", "Score": "0", "body": "I understand, thank you. I've adapted my code to be similar to your suggestion." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T02:19:27.373", "Id": "45180", "ParentId": "45178", "Score": "2" } }, { "body": "<h2>General Notes</h2>\n\n<ul>\n<li>Pass references rather than values if you don't need a copy of the object. Use const references if you don't want the function to change the object.</li>\n<li>Declare member functions to be const if they don't change the state of the object.</li>\n<li>Range-based loops are easier to read than explicitly using iterators.</li>\n<li>Separate header and implementation files makes it easier to see an overview of a class without having to wade through the gory details.</li>\n<li>Compare the performance of unordered_set to set.</li>\n<li>In the code posted below I changed the coding style. Your coding style isn't wrong. I'm just very anal and was too lazy to change it back.</li>\n</ul>\n\n<h2>AABB</h2>\n\n<ul>\n<li>Defining an AABB by its corners is more intuitive than one corner and a size. The latter isn't wrong, but you might want to consider this alternative.</li>\n<li>I moved getIndex() to the AABB class because it is more logical.</li>\n<li>I made getIndex() simpler.</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>class AABB\n{\npublic:\n AABB(double minX,double minY,double maxX,double maxY);\n double getMinX() const;\n double getMinY() const;\n double getMaxX() const;\n double getMaxY() const;\n double getMidX() const;\n double getMidY() const;\n int getQuad(const AABB&amp; aabb) const;\nprivate:\n int getQuad(double x,double y) const;\nprivate:\n double minX;\n double minY;\n double maxX;\n double maxY;\n double midX;\n double midY;\n};\n\nAABB::AABB(double minX_,double minY_,double maxX_,double maxY_)\n :minX(minX_),\n minY(minY_),\n maxX(maxX_),\n maxY(maxY_),\n midX((minX_+maxX_)/2.0),\n midY((minY_+maxY_)/2.0)\n{}\n\ndouble AABB::getMinX() const\n{\n return minX;\n}\n\ndouble AABB::getMinY() const\n{\n return minY;\n}\n\ndouble AABB::getMaxX() const\n{\n return maxX;\n}\n\ndouble AABB::getMaxY() const\n{\n return maxY;\n}\n\ndouble AABB::getMidX() const\n{\n return midX;\n}\n\ndouble AABB::getMidY() const\n{\n return midY;\n}\n\nint AABB::getQuad(const AABB&amp; aabb) const\n{\n int tl = getQuad(aabb.getMinX(),aabb.getMinY());\n int br = getQuad(aabb.getMaxX(),aabb.getMaxY());\n if(tl==br)\n return tl;\n return -1;\n}\n\nint AABB::getQuad(double x,double y) const\n{\n if(y&lt;getMidY())\n {\n if(x&lt;getMidX())\n return 1;\n else\n return 0;\n }\n else\n {\n if(x&lt;getMidX())\n return 2;\n else\n return 3;\n }\n}\n</code></pre>\n\n<h2>Locatable</h2>\n\n<pre><code>const AABB&amp; getAABB() const;\n</code></pre>\n\n<h2>clear()</h2>\n\n<ul>\n<li>You don't need to call clear() on all of the children. The children will be destroyed when you clear() the vector.</li>\n</ul>\n\n<h2>insert() / split()</h2>\n\n<ul>\n<li>Your improved insert() is much better than your original version.</li>\n<li>Don't make a copy of the AABB just pass it by reference.</li>\n<li>In insert(), the code that reinserts the entities is only run after split(). Move that code into split() so we can make insert() a little simpler.</li>\n</ul>\n\n<h2>remove()</h2>\n\n<ul>\n<li>Does the AABB passed to this function differ from object->getAABB()?</li>\n<li>You can optimistically call erase() and read the return value rather than using iterators.</li>\n</ul>\n\n<h2>getAll()</h2>\n\n<ul>\n<li>You are doing a huge amount of work by maintaining allEntities. It has everything you need.</li>\n<li>Don't make a copy unless necessary.</li>\n</ul>\n\n<h2>getLowestRoot()</h2>\n\n<ul>\n<li>This function is great, but do you do anything with the object returned other than call getAll()? If not, replace it with getAllIn().</li>\n</ul>\n\n<h2>Eliminate entities or allEntities</h2>\n\n<p>These variables are redundant and maintaining them both is too much overhead. The one you should eliminate depends on how often you call insert()/remove() compared to getAll(). Both versions are below. I did very little testing for correctness so you probably want to ensure that these have the same output as your current version.</p>\n\n<pre><code>class QuadTree\n{\nprivate:\n static const int MAX_OBJECTS = 20;\npublic:\n QuadTree(const AABB&amp; bounds);\n void clear();\n void insert(Locatable* object);\n void remove(Locatable* object);\n void remove(Locatable* object,const AABB&amp; aabb);\n QuadTree* getLowestRoot(const AABB&amp; aabb);\n const std::unordered_set&lt;Locatable*&gt;&amp; getAll() const;\n const std::unordered_set&lt;Locatable*&gt;&amp; getAllIn(const AABB&amp; aabb) const;\nprivate:\n void split();\nprivate:\n AABB bounds;\n std::vector&lt;QuadTree&gt; children;\n std::unordered_set&lt;Locatable*&gt; allEntities;\n};\n\nQuadTree::QuadTree(const AABB&amp; bounds)\n :bounds(bounds)\n{\n children.reserve(4);\n}\n\nvoid QuadTree::clear()\n{\n allEntities.clear();\n children.clear();\n}\n\nvoid QuadTree::insert(Locatable* object)\n{\n allEntities.emplace(object);\n if(children.empty())\n {\n if(allEntities.size() &gt; MAX_OBJECTS)\n split();\n }\n else\n {\n int index = bounds.getQuad(object-&gt;getAABB());\n if(index!=-1)\n children.at(index).insert(object);\n }\n}\n\nvoid QuadTree::remove(Locatable* object)\n{\n if(allEntities.erase(object)!=0 &amp;&amp; !children.empty())\n {\n int index = bounds.getQuad(object-&gt;getAABB());\n if (index != -1)\n children.at(index).remove(object);\n }\n}\n\nvoid QuadTree::remove(Locatable* object,const AABB&amp; aabb)\n{\n if(allEntities.erase(object)!=0 &amp;&amp; !children.empty())\n {\n int index = bounds.getQuad(aabb);\n if (index != -1)\n children.at(index).remove(object),aabb;\n }\n}\n\nQuadTree* QuadTree::getLowestRoot(const AABB&amp; aabb)\n{\n if(children.empty())\n return this;\n int index = bounds.getQuad(aabb);\n if(index == -1)\n return this;\n return children.at(index).getLowestRoot(aabb);\n}\n\nconst std::unordered_set&lt;Locatable*&gt;&amp; QuadTree::getAll() const\n{\n return allEntities;\n}\n\nconst std::unordered_set&lt;Locatable*&gt;&amp; QuadTree::getAllIn(const AABB&amp; aabb) const\n{\n if(children.empty())\n return allEntities;\n int index = bounds.getQuad(aabb);\n if(index == -1)\n return allEntities;\n return children.at(index).getAllIn(aabb);\n}\n\nvoid QuadTree::split()\n{\n children.emplace_back(AABB(bounds.getMidX(),bounds.getMinY(),bounds.getMaxX(),bounds.getMidY()));\n children.emplace_back(AABB(bounds.getMinX(),bounds.getMinY(),bounds.getMidX(),bounds.getMidY()));\n children.emplace_back(AABB(bounds.getMinX(),bounds.getMidY(),bounds.getMidX(),bounds.getMaxY()));\n children.emplace_back(AABB(bounds.getMidX(),bounds.getMidY(),bounds.getMaxX(),bounds.getMaxY()));\n\n for(Locatable* l : allEntities)\n {\n int index = bounds.getQuad(l-&gt;getAABB());\n if(index!=-1)\n children.at(index).insert(l);\n }\n}\n</code></pre>\n\n<p>.</p>\n\n<pre><code>class QuadTree\n{\nprivate:\n static const int MAX_OBJECTS = 20;\npublic:\n QuadTree(const AABB&amp; bounds);\n void clear();\n void insert(Locatable* object);\n void remove(Locatable* object);\n void remove(Locatable* object,const AABB&amp; aabb);\n QuadTree* getLowestRoot(const AABB&amp; aabb);\n void getAll(std::unordered_set&lt;Locatable*&gt;&amp; all) const;\n void getAllIn(std::unordered_set&lt;Locatable*&gt;&amp; all,const AABB&amp; aabb) const;\nprivate:\n void split();\nprivate:\n AABB bounds;\n std::vector&lt;QuadTree&gt; children;\n std::unordered_set&lt;Locatable*&gt; entities;\n};\n\nQuadTree::QuadTree(const AABB&amp; bounds)\n :bounds(bounds)\n{\n children.reserve(4);\n}\n\nvoid QuadTree::clear()\n{\n entities.clear();\n children.clear();\n}\n\nvoid QuadTree::insert(Locatable* object)\n{\n if(children.empty())\n {\n entities.emplace(object);\n if(entities.size() &gt; MAX_OBJECTS)\n split();\n }\n else\n {\n int index = bounds.getQuad(object-&gt;getAABB());\n if(index==-1)\n entities.emplace(object);\n else\n children.at(index).insert(object);\n }\n}\n\nvoid QuadTree::remove(Locatable* object)\n{\n if(entities.erase(object)==0 &amp;&amp; !children.empty())\n {\n int index = bounds.getQuad(object-&gt;getAABB());\n if(index!=-1)\n children.at(index).remove(object);\n }\n}\n\nvoid QuadTree::remove(Locatable* object,const AABB&amp; aabb)\n{\n if(entities.erase(object)==0 &amp;&amp; !children.empty())\n {\n int index = bounds.getQuad(aabb);\n if(index!=-1)\n children.at(index).remove(object,aabb);\n }\n}\n\nQuadTree* QuadTree::getLowestRoot(const AABB&amp; aabb)\n{\n if(children.empty())\n return this;\n int index = bounds.getQuad(aabb);\n if(index == -1)\n return this;\n return children.at(index).getLowestRoot(aabb);\n}\n\nvoid QuadTree::getAll(std::unordered_set&lt;Locatable*&gt;&amp; all) const\n{\n for(Locatable* l : entities)\n all.emplace(l);\n if(!children.empty())\n {\n children.at(0).getAll(all);\n children.at(1).getAll(all);\n children.at(2).getAll(all);\n children.at(3).getAll(all);\n }\n}\n\nvoid QuadTree::getAllIn(std::unordered_set&lt;Locatable*&gt;&amp; all,const AABB&amp; aabb) const\n{\n if(children.empty())\n {\n getAll(all);\n return;\n }\n int index = bounds.getQuad(aabb);\n if(index == -1)\n {\n getAll(all);\n return;\n }\n return children.at(index).getAllIn(all,aabb);\n}\n\nvoid QuadTree::split()\n{\n children.emplace_back(AABB(bounds.getMidX(),bounds.getMinY(),bounds.getMaxX(),bounds.getMidY()));\n children.emplace_back(AABB(bounds.getMinX(),bounds.getMinY(),bounds.getMidX(),bounds.getMidY()));\n children.emplace_back(AABB(bounds.getMinX(),bounds.getMidY(),bounds.getMidX(),bounds.getMaxY()));\n children.emplace_back(AABB(bounds.getMidX(),bounds.getMidY(),bounds.getMaxX(),bounds.getMaxY()));\n\n auto cit = entities.cbegin();\n while(cit!=entities.cend())\n {\n int index = bounds.getQuad((*cit)-&gt;getAABB());\n if(index!=-1)\n {\n children.at(index).insert(*cit);\n cit = entities.erase(cit);\n }\n else\n ++cit;\n }\n}\n</code></pre>\n\n<h2>Other Optimizations</h2>\n\n<ul>\n<li>Consider other data structures such as a k-d tree. You can make the tree more balanced by moving the pivot points.</li>\n<li>Tune MAX_OBJECTS.</li>\n<li>Restructure your code so that insert(), remove(), and getAll() are called less often.</li>\n<li>After splitting, if an entity cannot be inserted into any children, put it in a different data structure.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T09:43:56.043", "Id": "45189", "ParentId": "45178", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T01:55:15.967", "Id": "45178", "Score": "-1", "Tags": [ "c++", "performance", "tree" ], "Title": "QuadTree can't handle many elements" }
45178
<p>I am trying to implement ugly number sequence generation in Scala.</p> <p><strong>Ugly numbers</strong> are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15...</p> <p>I have implemented using var keyword like java implementation and it is working fine. Here is the <a href="http://ideone.com/qxMEBw" rel="nofollow">ideone link</a> of complete code.</p> <p>Can someone suggest better of implementing it using Scala idioms and without using mutable values?</p> <pre><code>/** * Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence * 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, * shows the first 11 ugly numbers. By convention, 1 is included. * Write a program to find and print the 150th ugly number. * */ object UglyNumbers extends App { var uglyNumbers = List(1) val n = 11 var i2 = 0; var i3 = 0; var i5 = 0; // initialize three choices for the next ugly numbers var next_multiple_2 = uglyNumbers(i2) * 2; var next_multiple_3 = uglyNumbers(i3) * 3; var next_multiple_5 = uglyNumbers(i5) * 5; for (i &lt;- 0 to n) { val nextUglyNumber = min(next_multiple_2, next_multiple_3, next_multiple_5) uglyNumbers = uglyNumbers :+ nextUglyNumber if (nextUglyNumber == next_multiple_2) { i2 = i2 + 1 next_multiple_2 = uglyNumbers(i2) * 2 } if (nextUglyNumber == next_multiple_3) { i3 = i3 + 1 next_multiple_3 = uglyNumbers(i3) * 3 } if (nextUglyNumber == next_multiple_5) { i5 = i5 + 1 next_multiple_5 = uglyNumbers(i5) * 5 } } for (uglyNumber &lt;- uglyNumbers) print(uglyNumber + " ") def min(a: Int, b: Int, c: Int): Int = (a, b, c) match { case _ if (a &lt;= b &amp;&amp; a &lt;= c) =&gt; a case _ if (b &lt;= a &amp;&amp; b &lt;= c) =&gt; b case _ =&gt; c } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:12:13.903", "Id": "78734", "Score": "0", "body": "I got very good response here. pls check this link\n[to my cross-post on Stack Overflow](http://stackoverflow.com/questions/22601215/ugly-number-implementation-in-scala/22605264?noredirect=1#22605264)" } ]
[ { "body": "<p>First off, I'd like to mention, that my Scala experience is limited, so please do point out any errors.</p>\n\n<p>You should implement your algorithm in it's own class implementing an appropriate interface/trait (probably <code>Iterator</code>, but there may be better ones).</p>\n\n<p>That would also avoid having the awkward hard-coded limit to 11 elements in the main algorithm.</p>\n\n<p>I'm not a fan of the repeated code for the three base numbers. Off the top of my head I'm not sure how to avoid it, but would assume it would include using case classes.</p>\n\n<p>You should also have a look at your variable names. You have a mixture of short cryptic names (<code>n</code>, <code>i3</code>, etc.) and two different styles (camel case and underlines). You should always use descriptive names (<code>maxIterations</code>, <code>index3</code>) and use a single style (preferably camel case as this is the convention for Scala).</p>\n\n<p>BTW, List has a <code>min</code> method, so there is no need to roll your own:</p>\n\n<pre><code>val nextUglyNumber = List(next_multiple_2, next_multiple_3, next_multiple_5).min;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:29:15.067", "Id": "45200", "ParentId": "45184", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T04:45:51.983", "Id": "45184", "Score": "4", "Tags": [ "scala" ], "Title": "Ugly number implementation in Scala" }
45184
<p>I am using this code in a lot of places:</p> <pre><code>if (ParameterName == null) { throw new ArgumentNullException("ParameterName"); } </code></pre> <p>But I think this is not DRY. The only difference here is <code>ParameterName</code>. Is it ok to use these lines everywhere, or is there a way to make it DRY?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T22:34:34.053", "Id": "78846", "Score": "1", "body": "This is where you wish you had C macros" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:21:07.070", "Id": "79339", "Score": "0", "body": "@Demetri no, it really isn't! Even if you did, there's nothing to stop you using the C preprocessor on C# files." } ]
[ { "body": "<p>You could try to extract it to a method, but you'd still have to call it for every parameter and you will lose the information, what the parameter's name is....</p>\n\n<pre><code>CheckNull(object ParameterName){\n if(parameterName == null){\n throw new ArgumentNullException(\"some param was null, no clue which...\");\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T10:42:05.640", "Id": "45195", "ParentId": "45191", "Score": "5" } }, { "body": "<p>Looks pretty DRY to me. :) You can use expressions to somewhat reduce the amount of code you need to write:</p>\n\n<pre><code> public static void ThrowIfNull(Expression&lt;Func&lt;object&gt;&gt; expression)\n {\n var res = expression.Compile();\n if (res.Invoke() == null)\n {\n var lambda = (LambdaExpression) expression;\n var member = (MemberExpression) lambda.Body;\n throw new ArgumentNullException(member.Member.Name);\n }\n }\n\n public void SomeMethod(object someParameter)\n {\n ThrowIfNull(() =&gt; someParameter);\n }\n</code></pre>\n\n<p>but frankly i'd go with Re-sharper templates (or VS code snippets) instead.</p>\n\n<p><strong>Edit:</strong> A quick test on my machine shows, that on average it takes about 0.22 milliseconds per call to execute <code>ThrowIfNull</code> 1000000 times with different (not null) arguments. With first call being ~20 times slower (perhaps repeated compilation is optimized and/or cached in some way, tho i am not competent enough on that subject to make any claims). Is it slower then one equality check? Well, obviously. But it is still unlikely to become any kind of a bottleneck in real life scenario, unless overused. As i said, however, i would not use it. The original code looks clear and short enough to me, even shorter, when templated. So i always go with simple explicit <code>null</code> check.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:02:50.207", "Id": "78719", "Score": "0", "body": "You mean the condition checking is DRY itself. Yes, I have found these lines a lot in ASP.NET MVC 5 source which led me to think this is not bed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:58:49.517", "Id": "78743", "Score": "8", "body": "Won't that be quite slow, compiling an expression each time? A null check should be cheap so you can do lots of them - compiling code for each one seems like it might slow things down a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:57:49.103", "Id": "78809", "Score": "0", "body": "Why are you using an expression for this? Seems a little overkill to me, unless of course I'm missing something blindingly obvious." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T05:03:06.710", "Id": "78868", "Score": "0", "body": "@MrKWatkins, slow compared to what? To the original solution? Yes, of course. See my edit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T05:06:19.057", "Id": "78869", "Score": "0", "body": "@Joe, to get a parameter name without manually typing a string :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T07:48:32.677", "Id": "78879", "Score": "0", "body": "It strikes me as quite a bit awkward to depend on the structure of the body of the lambda, and only in the null-case. I think I'd rather just supply the parameter name and thus abstract just the null-comparison of the original code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T08:58:02.310", "Id": "78884", "Score": "0", "body": "@plc, you can do that, Joe's answer provides a nice implementation of this approach. I'm simply providing an alternative solution. Being said, i am not convinced by your reasoning. Such \"dependencies\" are not uncommon. Actually you can find them all over the .Net. Take `String.Format` for example. Does the fact that you have to pass the correct number of arguments strickes you the same way? Is it good enough reason not to use it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:00:39.963", "Id": "78893", "Score": "0", "body": "@NikitaBrizhak It's not the slowness for a single call I'm worried about as it may well be cached. But you'll have calls like this all over the app you'll be compiling extra code to memory all over the place. Seems overkill to me when you could just type in the parameter name. And if you use ReSharper you could even add an [InvokerParameterName] annotation to help ensure the correct name is being passed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:02:41.830", "Id": "78894", "Score": "1", "body": "@NikitaBrizhak If you did want to tie the name in with an expression then I'd probably pass the value *and* the expression. Check the value for null (which wouldn't involve compilation) and only then parse the expression to get the parameter name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:57:53.480", "Id": "79374", "Score": "0", "body": "@NikitaBrizhak Ugh, obviously! Sorry for a dumb comment." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T10:50:23.433", "Id": "45196", "ParentId": "45191", "Score": "10" } }, { "body": "<p>Google Guava's <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html#checkNotNull%28T,%20java.lang.String,%20java.lang.Object...%29\"><code>Precondition</code></a> class contains good patterns for this problem. For example, the <code>checkNotNull</code> method is the following:</p>\n\n<pre><code>T checkNotNull(T reference, String errorMessageTemplate, Object... errorMessageArgs)\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>checkNotNull(parameter, \"parameter cannot be null\");\n</code></pre>\n\n<p>Note its return value. If the value is not <code>null</code> it returns the <code>referencce</code>, so you can use it in the following way:</p>\n\n<pre><code>public MyClass(MyObject dependency) {\n this.dependency = checkNotNull(dependency, \"dependency cannot be null\");\n}\n</code></pre>\n\n<p>It also supports error message templates with <code>%s</code>.</p>\n\n<p>Although it's a Java library, you can implement the same methods in C# too, they are really simple.</p>\n\n<p>See also: <a href=\"https://code.google.com/p/guava-libraries/wiki/PreconditionsExplained\">Preconditions Explained</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:17:20.657", "Id": "78721", "Score": "0", "body": "+1 for mentioning preconditions. This seems like a good time to introduce code contracts (and the DbC principle in general)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:29:29.570", "Id": "78722", "Score": "0", "body": "I am using C#.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:35:49.077", "Id": "78724", "Score": "0", "body": "@user960567: \"Although it's a Java library, you can implement the same methods in C# too, they are really simple.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:49:07.967", "Id": "78741", "Score": "2", "body": "As of Java 7, you could use the built-in `Objects.requireNotNull` method. But then again... this is a C# question :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T10:55:04.990", "Id": "45197", "ParentId": "45191", "Score": "13" } }, { "body": "<p>I would go for a generic extension method for this:</p>\n\n<pre><code>public static void ThrowIfNull&lt;T&gt;(this T parameter, string name) where T : class\n{\n if (data == null)\n throw new ArgumentNullException(name);\n}\n</code></pre>\n\n<p>This way, you can call</p>\n\n<pre><code>Parameter.ThrowIfNull(\"Name\");\n</code></pre>\n\n<p>If you're calling this on a property, you could use <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx\" rel=\"nofollow\">CallerMemberNameAttribute</a>, this won't work from a method though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-15T08:23:52.913", "Id": "191560", "Score": "0", "body": "If you have access to the new C# 6.0 features, you can could use the new nameof(...) operator\n\n`if (data == null) throw new ArgumentNullException(nameof(data));`\n\nThe compiler will catch any parameter name mismatchs which may occur if you rename a parameter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-15T11:57:43.890", "Id": "191593", "Score": "1", "body": "@JoeKing would `nameof(data)` just come back with `\"data\"`? I don't think it will cascade down. I could be wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-15T13:39:13.563", "Id": "191631", "Score": "0", "body": "Yes, it really only helps in the case where you rename a parameter. On a side note, the `nameof()` operator can also come in very handy when implementing the `INotifyPropertyChanged` interface, as property renaming has to be one of the main sources of data binding bugs." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T16:19:22.287", "Id": "45236", "ParentId": "45191", "Score": "8" } }, { "body": "<p>If you just want a short syntax, you could use Code Contracts.</p>\n\n<p>Either</p>\n\n<pre><code>Contract.Requires( x != null );\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Contract.Requires&lt;ArgumentNullException&gt;( x != null, \"x\" )\n</code></pre>\n\n<p>depending on whether the exact exception type is important to you. There is also some configuration to be done, depending on if you want these checks only for debug, or also for release.</p>\n\n<p>I should point out, however, that Code Contracts are really about much more than simple argument checks, and it has its own pros and cons. More information <a href=\"http://msdn.microsoft.com/en-us/library/dd264808(v=vs.110).aspx\" rel=\"nofollow\">here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-23T13:50:09.253", "Id": "148146", "Score": "0", "body": "Note that `Contract.Requires(` does *not* necessarily throw any exception." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-23T14:48:39.863", "Id": "148167", "Score": "0", "body": "Could you elaborate on that?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T07:04:42.163", "Id": "45285", "ParentId": "45191", "Score": "10" } } ]
{ "AcceptedAnswerId": "45196", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T10:29:20.080", "Id": "45191", "Score": "15", "Tags": [ "c#" ], "Title": "DRY the throwing of ArgumentNullException(\"ParameterName\")?" }
45191
<p>I was wondering if any of you know any best practices or design patterns so that I can have good logging in my programs without them looking messy or bloated.</p> <p>I am currently using C# and NLog, however I guess any advice here would be language and tool agnostic.</p> <p>The problem we have is that we want to have good logging, however we can't seem to find a way around having many lines which just log operations, which can turn a simple method like this:</p> <pre><code>void Foo() { Bar bar = dbContext().Bars.First(); bool someCondition = bar.DoSomething(); if (someContition) { dbContext().FooBars.Add(new FooBar()); } } </code></pre> <p>Into something which looks like this:</p> <pre><code>void Foo() { _logger.Info("Getting first bar from database..."); Bar bar = dbContext().Bars.First(); _logger.Info("First bar returned from database, id = {0}", bar.Id); _logger.Info("Doing something on bar with id = {0}", bar.Id); bool someCondition = bar.DoSomething(); _logger.Info("Something done on bar with id = {0}, response = {1}", bar.Id, someCondition); if (someContition) { _logger.Warn("Adding new FooBar to database"); dbContext().FooBars.Add(new FooBar()); _logger.Warn("Added new FooBar to database successfully"); } } </code></pre> <p>Here we now have more logging lines than code lines. </p> <p>However I am being told by operations that this level of logging is required, and at the moment is still too coarse.</p> <p>Is there any way around this ugly manual logging, or am I stuck with it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:31:32.933", "Id": "79117", "Score": "2", "body": "What you want is not `logging`, *operations* actually either want an **audit trail** or **event sourcing**. Logs are not reliable: You logged `\"Something done on bar with id=...\"`, but what if changes to `dbContext` never saved?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:47:30.647", "Id": "79119", "Score": "0", "body": "I noticed UriAgassi italicized *operations* too, in my case it was because it's not clear who *operations* is. Requirements coming from COO or IT Operations have different goals, different solutions that address them and they might have different priorities." } ]
[ { "body": "<p>This kind of trace logging could conceivably be solved with an <a href=\"http://en.wikipedia.org/wiki/Aspect-oriented_programming\">Aspect</a>. </p>\n\n<p>Aspect oriented programming allows you to add boilerplate-style code to your program without actually writing the boilerplate inline. You could, for example, add an aspect than logged a method name and parameters every time a program entered a method, and then logged the method name and return value every time a method returned.</p>\n\n<p>Of course, you don't necessarily want to log <em>every</em> method. Instead, most aspect frameworks allow you to indicate which code you want the boilerplate added to.</p>\n\n<p>I don't know enough about C# to recommend a specific aspect-oriented framework to use, or appropriate syntax for you. Sorry.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T10:16:06.853", "Id": "78715", "Score": "2", "body": "[Aspect-Oriented Programming with the RealProxy Class](http://msdn.microsoft.com/en-us/magazine/dn574804.aspx) is quite a good read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:39:54.910", "Id": "78725", "Score": "2", "body": "A good tool for this kind of thing is [PostSharp](http://www.postsharp.net/)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T23:21:00.217", "Id": "78850", "Score": "0", "body": "I don't think we're actually calling it aspects, but we are applying something of that sort for the basics of our logging. There are certainly exceptions where we hand-code the logging instead, to better control what gets reported, but in many cases we do produce the entry/exit messages automatically." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T22:29:48.693", "Id": "79704", "Score": "0", "body": "I've used Castle DynamicProxy to accomplish this in the past: http://docs.castleproject.org/Default.aspx?Page=Introduction-to-AOP-With-Castle&NS=Windsor" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-28T14:35:24.933", "Id": "167097", "Score": "3", "body": "@AndyBrush, The PostSharp people lock you in to their product and their product gets baked in to your code since it rewrites the MSIL. PostSharp was in vogue for a short time at my firm a few years ago. Now we want to move away from it because it hides functionality from non-expert users complicating development and maintenance. We're locked in however because so many users use the code. Any tech questions we send to PostSharp are quickly shot down because they don't support the version we use anymore." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T10:00:04.870", "Id": "45194", "ParentId": "45193", "Score": "30" } }, { "body": "<p>Looking at your code, I believe that your problem is not only that the logging lines are ugly but they are a risk in costing you more than helping you:</p>\n\n<ul>\n<li>Like comments, log line maintenance is often forgotten, and might break your code upon changes, or - worse - confuse you when trying to troubleshoot by reading the log files (think of a situation where you change <code>Bar bar = dbContext().Bars.First();</code>, to <code>Bar bar = dbContext().Bars.Last();</code>, but not changing the log files - the log will tell you that the <em>first</em> bar returned is <code>X</code>, and now you'll be scratching your head how did that happen?)</li>\n<li>The logs in your code, if at all needed, are definitely not for level <code>Info</code>, not to talk about level <code>Warn</code> - these are <code>Debug</code> logs. Filling your files with debug logs will make your log files huge, and unusable. \n<ul>\n<li><code>Warn</code> logs should be logged <em>only</em> when something out of the expected behavior happens, so that troubleshooting production will be focused on that.</li>\n<li><code>Info</code> logs should be succinct, in linear proportion to the number of transactions, and convey <em>valuable</em> information.</li>\n<li><code>Debug</code> logs are usually added ad-hoc when you are trying to hunt down an elusive bug, and need more information inside specific code. In a production scenario, these logs should be turned <em>off</em>.</li>\n</ul></li>\n</ul>\n\n<p>It is implied from your post that you received this requirement from the <em>operations</em> team. I have a hard time understanding why the operations team will give you a requirement to log internal code behavior... They might require you to have <em>specific</em> logs on the feature level, but having a fine-grained logging requirement seems counter-intuitive and not in their domain of responsibility.</p>\n\n<p>Anyway, to solve the first bullet (and make your code cleaner), the best strategy AFAIK is using <a href=\"http://en.wikipedia.org/wiki/Aspect-oriented_programming\">Aspect-Oriented Programming</a> as @BillMichell has recommended.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T14:33:03.350", "Id": "78753", "Score": "0", "body": "I agree with you, the levels I had put above were just there as part of the pseudo code. The reason for the ops team wanting the logs like this is so that if a customer logs a support call, it is normally about a specific unit. This would marry to the id written in the logs. The support team then just opens the log files, filters by that id and they we see everything the system has done with that item. They can then see where/what last happened to it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T14:39:12.710", "Id": "78758", "Score": "3", "body": "I understand their logic, but you should argue that what the ops need is the user _activity_, not the user _trace_. This scope is much higher in level and should include, IMHO, at most every entry point the user had (which end-point and when), and every exit point (whether it was successful, and if not, why, and maybe some benchmark for how long it took)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:15:48.740", "Id": "78773", "Score": "0", "body": "Sorry, perhaps I should have included that it is a Windows Service. So there isn't really a user. Don't know if that makes a difference? I do agree that it feels wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:52:19.150", "Id": "78781", "Score": "0", "body": "I believe it's just a matter of terminology - replace \"user\" with \"customer\" or whatever, \"entry point\" with \"activity start\", \"exit point\" with \"activity end\"..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:22:28.200", "Id": "45205", "ParentId": "45193", "Score": "20" } }, { "body": "<p>At the level of logging you're describing a debugger seems to be far more sensible. Speaking at least for myself and my subfield we would use logging in two ways. </p>\n\n<ul>\n<li>General <code>INFO</code> and ad-hoc <code>DEBUG</code> level logging which let's one trace a bug to a specific part of the application and to provide meta data like <code>id</code>'s and similar information. </li>\n<li>And secondly logging of all (user) actions to make it possible to see what exactly a user did (both for bug fixing or when a client has a claim that he did something two months ago which supposedly didn't work).</li>\n</ul>\n\n<p>Next a debugger can be used to go through the code line by line, giving all the more detailed information that you're logging now, without all the explicit log lines describing what is happening (which, if necessary would be in comments, not logs).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T14:14:32.407", "Id": "45217", "ParentId": "45193", "Score": "1" } }, { "body": "<p>Logging when you're about to do something or when something goes right are good for development code. During development, you want to know the finest details of what goes on.</p>\n\n<p>In production code, you expect that everything will go fine. In fact, ideally you only want to be informed when something goes wrong: You get an exception from your code, a database call fails or a critical part of your code returns something unexpected. In those cases, you want to log what went wrong, and if possible log the variables you're working with to help reproduce the bug.</p>\n\n<p>In the case above, you don't want to log every time you get Bar, or that you got Bar with ID X, or that you're doing something on Bar, or that you've successfully done something on bar. You expect those to work properly, so you only want to log when something went wrong there, and then write away the bar variables you use in <code>doSomething()</code> and the ID of Bar. If someCondition is true, you want to log that you added something, but you don't want to log that it succeeded, only if it went wrong.</p>\n\n<p>If operations says that they really need those logging statements, they're viewing it wrong. They don't want those logging statements, they want THE INFORMATION those logging statements generate. They likely want statistics based on those logging statements, or something related to the logging statements. Discuss with Operations why they need those statements and provide them with what they need.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:05:40.573", "Id": "45226", "ParentId": "45193", "Score": "6" } }, { "body": "<p>It may be that for your particular example it may be useful to derive a subclass of dbContext (say, loggedDBContext) that wraps it's methods with code that logs whatever you need and then executes the 'true' method. Adding/removing logging then would consist in choice of using dbContext vs loggedDBContext at the constructor (or factory), but not changing anything else.</p>\n\n<p>In some languages there are ways to inject such aspects directly in the functions - change their behavior without requiring the calling code to even know that the functions have changed and now also do logging; but I'm not sure if that can be done in C# without explicit subclassing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:32:45.953", "Id": "45243", "ParentId": "45193", "Score": "1" } }, { "body": "<p>As others here have pointed out logging carries the same burden as comments - too much or too little does more harm than good.</p>\n\n<p>One practical approach to logging is to put a log line in most <em>key</em> branches - some branches do minor things and aren't worth logging. The most critical branch to log is a <code>catch(Exception x)</code> - <strong>always</strong> log exceptions</p>\n\n<p>As for the maintenance of logs I have somewhat of an unique approach: I've created addins for my favorite development environments (VS, Eclipse) that upon pressing a hotkey insert a short unique coded sequence of characters of predetermined length (10 letters, all caps) and I use these + runtime data instead of human-readable verbage.</p>\n\n<p>I call these \"debrix codes\" and they have multiple advantages, some of which:</p>\n\n<ul>\n<li>no messy elaborate wording</li>\n<li>you can always find the place in the code that produced a specific log</li>\n<li>you can easily count instances of a specific message or other stats: I have LinqPad scripts that take a log file name and a debrix\ncode to produce snapshots of the vicinity of each occurance</li>\n<li>By only using runtime data you can be sure your message is always up-to-date: if the object is refactored out you are forced to\nrefactor the log message as well.</li>\n<li>unique debrix codes throughout a complex system with multiple platforms will still lead you to the one place that produced the log\nmessage, regardless if it's javascript, server-side, client side (OSX\nSpotlight is very handy)</li>\n<li>the code can be included with client-visible error messages for customer support. Along with a timestamp it's all but guaranteed to uniquely identify an event</li>\n</ul>\n\n<p>This is how I would use this approach to log your code sample:</p>\n\n<pre><code>void Foo()\n{ \n try{\n log.I(\"[FFASREQEKT]\"); \n Bar bar = dbContext().Bars.First();\n\n bool someCondition = bar.DoSomething();\n\n if (someContition)\n {\n log.I(\"[FFGFAJNNBGB]\"); \n dbContext().FooBars.Add(new FooBar());\n }\n } catch (Exception x){\n // This catch is only for illustrative purpose. In real code it may be outside this method\n log.E(\"[FFGADJNANQ]\", x); \n }\n}\n</code></pre>\n\n<p>This allows you to have full insight into which code path was taken with the least amount of messages.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T22:07:04.063", "Id": "78840", "Score": "0", "body": "Is your \"debrix codes\"-'addin' for eclipse somewhere free to download?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T03:05:14.133", "Id": "78862", "Score": "0", "body": "This is the jar for Eclipse, it's rough around the edges because I mainly use VS, and installation is manual https://www.dropbox.com/s/oxx9efxhhh0n8ih/AidemaDebrix_1.0.0.6.jar | A manual for eclipse: http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.pde.doc.user%2Fguide%2Ftools%2Fproject_wizards%2Fplugin_from_archives.htm" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T03:06:30.873", "Id": "78863", "Score": "0", "body": "And here's the VS addin installer, tested on VS2008-2012: https://www.dropbox.com/s/idgvodomej1gbrk/VisualDebrixSetup.msi" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-04T02:53:22.233", "Id": "80669", "Score": "0", "body": "+1 This is a great idea. I take great pains to keep log messages up-to-date, often by creating typed methods to enforce the semantics. But the use of a unique message code makes filtering a breeze." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-04T13:45:33.547", "Id": "80765", "Score": "0", "body": "@DavidHarkness the VisualDebrix plugin actually takes the upper case letters from current file name as a prefix for the whole code, this way messages produced within the same class have the same prefix and the \"random\" code actually gives you a non-random clue. Useful for reading the neighboring log messages" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T20:58:29.447", "Id": "45257", "ParentId": "45193", "Score": "2" } }, { "body": "<p>As Bill Michell has pointed out aspect oriented programming is a good way of adding boilerplate logging code, however in this case I don't think its really necessary - I'd approach this problem with some good old fashioned refactoring.</p>\n\n<p>In your example the <code>Foo</code> method does all the logging, but if it is importantly to log that you are about to do something (or that you have done something), the its probably best to instead log this in the method which is doing that thing instead of the calling method. By refactoring the database calls into separate methods (which should probably be on a different class anyway) and refactoring the logging calls its easy enough to make the <code>Foo</code> method just as readable as it was before.</p>\n\n<pre><code>void Foo()\n{\n Bar bar = GetFirstBar();\n bool someCondition = bar.DoSomething();\n if (someContition)\n {\n AddFooBar();\n }\n}\n\nBar GetFirstBar()\n{\n _logger.Info(\"Getting first bar from database...\");\n return dbContext().Bars.First();\n _logger.Info(\"First bar returned from database, id = {0}\", bar.Id);\n}\n\nvoid AddFooBar()\n{\n _logger.Warn(\"Adding new FooBar to database\");\n dbContext().FooBars.Add(new FooBar());\n _logger.Warn(\"Added new FooBar to database successfully\");\n}\n\nbool DoSomething(this Bar bar)\n{\n _logger.Info(\"Doing something on bar with id = {0}\", bar.Id);\n // Implementation goes here\n _logger.Info(\"Something done on bar with id = {0}, response = {1}\", bar.\n Id, someCondition);\n}\n</code></pre>\n\n<p>So in answer to the more general question \"how do I add logging while keeping code readable?\", I refactor my methods into smaller methods until each method is as readable as it needs to be.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T02:41:57.027", "Id": "79283", "Score": "0", "body": "Yes, this. But ideally both. Every method that loads an entity from an ID should log the same information: id=x, found=y. This should be applied consistently across all entities. Once you do this, you can remove four lines of logging from client methods and shrink your code base considerably." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T00:28:40.200", "Id": "45450", "ParentId": "45193", "Score": "9" } } ]
{ "AcceptedAnswerId": "45194", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T09:48:12.737", "Id": "45193", "Score": "41", "Tags": [ "c#", "logging" ], "Title": "Logging without Code Bloat" }
45193
<p>I have more than 1000 items in my GridView. When scrolling though, it appears to make the app 'shutter'. Each time I load images from Picasso GC, it increases.</p> <pre><code>import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; public class BrandsItemAdapter extends BaseAdapter { public Activity activity; private static LayoutInflater inflater = null; public ArrayList&lt;HashMap&lt;String, String&gt;&gt; data; public HashMap&lt;String, String&gt; ITEM; public BrandsItemAdapter(Activity activity,ArrayList&lt;HashMap&lt;String, String&gt;&gt; data) { this.activity=activity; inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.data = data; } @Override public int getCount() { // TODO Auto-generated method stub return data.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder = null; ITEM = new HashMap&lt;String, String&gt;(); ITEM = data.get(position); if(convertView == null) { convertView = inflater.inflate(R.layout.department_viewadapter, parent, false); holder = new ViewHolder(); holder.mTitleView = (TextView) convertView.findViewById(R.id.textView1); holder.imageView1 = (ImageView) convertView.findViewById(R.id.imageView1); convertView.setTag(holder); }else { holder = (ViewHolder) convertView.getTag(); } try { holder.mTitleView.setText(ITEM.get("name")); Picasso.with(activity).load(ITEM.get("image")).placeholder(R.drawable.icon).resize(150, 150).error(R.drawable.icon).into(holder.imageView1); System.gc(); } catch(Exception e) { e.printStackTrace(); } return convertView; } private static class ViewHolder { TextView mTitleView; ImageView imageView1; } } </code></pre>
[]
[ { "body": "<h2>Easy things</h2>\n\n<ul>\n<li><p>auto-generated comments</p>\n\n<blockquote>\n<pre><code>@Override\npublic int getCount() {\n // TODO Auto-generated method stub\n return data.size();\n}\n</code></pre>\n</blockquote>\n\n<p>The method is not auto-generated any more, remove the comment. (this happens in a few places).</p></li>\n<li><p>brace-placement</p>\n\n<p>In Java, the opening brace <code>{</code> goes at the end of the line, not the start of a new line. Code like this:</p>\n\n<blockquote>\n<pre><code> }\n catch(Exception e)\n {\n e.printStackTrace();\n }\n</code></pre>\n</blockquote>\n\n<p>should look like:</p>\n\n<pre><code>} catch(Exception e) {\n e.printStackTrace();\n}\n</code></pre></li>\n</ul>\n\n<h2>Hard Stuff</h2>\n\n<p>This code is likely your problem:</p>\n\n<blockquote>\n<pre><code>holder.mTitleView.setText(ITEM.get(\"name\"));\nPicasso.with(activity).load(ITEM.get(\"image\"))\n .placeholder(R.drawable.icon).resize(150, 150)\n .error(R.drawable.icon).into(holder.imageView1);\nSystem.gc();\n</code></pre>\n</blockquote>\n\n<p>There are two things here.</p>\n\n<p>Firstly, <code>System.gc()</code> in any code that is not directly related to the system itself, is almost always a bug. There should never be a need for this. Let the system look after itself. It really does not need your help.</p>\n\n<p>The second item is that it may be taking <code>picasso</code> a long time to load the Images. If you are scrolling to unseen areas of the system then the code may need to be calling the <code>getView()</code> method a lot. You need this method to be fast.</p>\n\n<p>Convert the <code>Picasso</code> line to be an AsyncTask, and let it populate the imageView in the background. That will make populating the views a lot faster</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:10:03.310", "Id": "78732", "Score": "0", "body": "Hi rolfl, I think Picasso fetch images from background only using okhttp then why i need to change aynctask? sorry for my poor english" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:12:33.770", "Id": "78735", "Score": "0", "body": "@prasadthangavel - I cannot see anything else that stands out as being a problem, and the Picasso work appears to be the heavy-duty part of the code. I do not know Picasso and how it works. The System.gc() is still a problem too. Try to confirm that Picasso is working in the background, and I recommend you also try to make it an async-task... and see if there is a difference (it's really not that hard)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:36:42.390", "Id": "78739", "Score": "0", "body": "Maybe you need to suggest releasing an image when it scrolls out of view?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:00:15.797", "Id": "45203", "ParentId": "45201", "Score": "5" } }, { "body": "<p>Firstly, what is this?</p>\n\n<pre><code>public HashMap&lt;String, String&gt; ITEM;\n...\nITEM = new HashMap&lt;String, String&gt;();\nITEM = data.get(position);\n</code></pre>\n\n<p>This is what the <code>getItem(int position)</code> method is for. You're also creating a new HashMap every time a View is displayed (and immediately discarding it) which will be creating a lot of useless objects and lower performance. Your current implementation:</p>\n\n<pre><code>@Override\npublic Object getItem(int position) {\n // TODO Auto-generated method stub\n return position;\n}\n</code></pre>\n\n<p>Should actually return the item at that position in your data source; for example:</p>\n\n<pre><code>@Override\npublic HashMap&lt;String, String&gt; getItem(int position) {\n return data.get(position);\n}\n</code></pre>\n\n<p>Then in your <code>getView()</code> method, </p>\n\n<pre><code>ITEM = new HashMap&lt;String, String&gt;();\nITEM = data.get(position);\n</code></pre>\n\n<p>you can get rid of the <code>public HashMap&lt;String, String&gt; ITEM</code> instance, and just use:</p>\n\n<pre><code>Map&lt;String, String&gt; item = getItem(position);\n</code></pre>\n\n<p>So your <code>getView()</code> would start out more like:</p>\n\n<pre><code>@Override\npublic View getView(int position, View convertView, ViewGroup parent) {\n ViewHolder holder;\n Map&lt;String, String&gt; item = getItem(position);\n\n ...\n}\n</code></pre>\n\n<p>You also have, at the head of your adapter:</p>\n\n<pre><code>public Activity activity;\nprivate static LayoutInflater inflater = null;\n</code></pre>\n\n<p>There's no reason that the <code>Activity</code> instance should be public; and <em>certainly</em> no need for the <code>LayoutInflater</code> to be static. You're going to have a memory leak, since the <code>LayoutInflater</code> instance is tied to the Activity. <strong>NEVER</strong> store an Activity (or Fragment) in a static field. It's almost never necessary, and will almost always create a memory leak. In this case, after you finish the Activity, the adapter will retain a reference to it, and the Activity and all of its Views and their associated resources will be prevented from being garbage collected until the class is unloaded at some future time. </p>\n\n<p>Another minor tip for code cleanliness is that there are a few convenience methods for getting a <code>LayoutInflater</code>. Either of these will work, and prevent the need to make the ugly call/cast through <code>getSystemService()</code>:</p>\n\n<pre><code>inflater = LayoutInflater.from(activity);\ninflater = activity.getLayoutInflater();\n</code></pre>\n\n<p>Also, you could weaken the <code>ArrayList</code> and <code>HashMap</code> declarations to just <code>List</code> and <code>Map</code>, since you don't use any methods specific to those particular implementations.</p>\n\n<p>Lastly (aside from the points @rolfl has made), you have this:</p>\n\n<pre><code>private static class ViewHolder {\n TextView mTitleView;\n ImageView imageView1;\n}\n</code></pre>\n\n<p>You should pick a naming convention and stick with it. Typical Android convention is that private member variables are prefixed with <code>m</code> (statics with <code>s</code>). Public variables (like those in this ViewHolder) shouldn't be prefixed. Suggestion:</p>\n\n<pre><code>static class ViewHolder {\n final TextView title;\n final ImageView image;\n\n ViewHolder(View root) {\n title = (TextView) root.findViewById(R.id.textView1);\n image = (ImageView) root.findViewById(R.id.imageView1);\n }\n}\n</code></pre>\n\n<p>Then, you can replace:</p>\n\n<pre><code>holder = new ViewHolder();\n\nholder.mTitleView = (TextView) convertView.findViewById(R.id.textView1);\nholder.imageView1 = (ImageView) convertView.findViewById(R.id.imageView1);\n\nconvertView.setTag(holder);\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>holder = new ViewHolder(convertView);\nconvertView.setTag(holder);\n</code></pre>\n\n<hr>\n\n<p>The final result would be something like the following; although you should certainly keep in mind @rolfl's suggestion to put the image resizing in a background thread (which is almost certainly the primary source of your stuttering problems -- although you can and should learn to profile with traceview to find the exact bottleneck):</p>\n\n<pre><code>public final class BrandsItemAdapter extends BaseAdapter {\n private final Activity mActivity;\n private final LayoutInflater mInflater;\n private final List&lt;Map&lt;String, String&gt;&gt; mData;\n\n public BrandsItemAdapter(Activity activity, List&lt;Map&lt;String, String&gt;&gt; data) {\n mActivity = activity;\n mInflater = activity.getLayoutInflater();\n mData = new ArrayList&lt;Map&lt;String, String&gt;&gt;(data);\n }\n\n @Override public int getCount() {\n return mData.size();\n }\n\n @Override public Map&lt;String, String&gt; getItem(int position) {\n return mData.get(position);\n }\n\n @Override public long getItemId(int position) {\n return position;\n }\n\n @Override public View getView(int position, View convertView, ViewGroup parent) {\n if (convertView == null) {\n convertView = inflater.inflate(R.layout.department_viewadapter, parent, false);\n convertView.setTag(new ViewHolder(convertView));\n }\n\n final ViewHolder holder = (ViewHolder) convertView.getTag();\n final Map&lt;String, String&gt; item = getItem(position);\n\n holder.title.setText(item.get(\"name\"));\n Picasso.with(activity)\n .load(item.get(\"image\"))\n .placeholder(R.drawable.icon)\n .resize(150, 150)\n .error(R.drawable.icon)\n .into(holder.image);\n\n return convertView;\n }\n\n static class ViewHolder {\n TextView title;\n ImageView image;\n\n ViewHolder(View root) {\n title = (TextView) root.findViewById(R.id.textView1);\n image = (ImageView) root.findViewById(R.id.imageView1);\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T07:23:13.690", "Id": "48652", "ParentId": "45201", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T11:34:52.357", "Id": "45201", "Score": "2", "Tags": [ "java", "android", "garbage-collection" ], "Title": "Gridview shuttering when scrolling" }
45201
<p>Here is my Bubblesort code:</p> <pre><code>public static List&lt;int&gt; BubbleSort(List&lt;int&gt; _digitList) { List&lt;int&gt; digitList = _digitList; bool didSwap = true; while (didSwap) { didSwap = false; for (int i = 0; i &lt; digitList.Count - 1; i++) { if (digitList[i] &gt; digitList[i + 1]) { int temp = digitList[i]; digitList[i] = digitList[i + 1]; digitList[i + 1] = temp; didSwap = true; } } } return digitList; } </code></pre> <p>And here is my Quicksort Method, which is actually an implementation of the pseudocode on <a href="http://en.wikipedia.org/wiki/Quicksort" rel="nofollow">Wikipedia</a>:</p> <pre><code>public static List&lt;int&gt; Quicksort(List&lt;int&gt; array) { if (array.Count &lt;= 1) { return array; //An array of Zero ot one elements is already sorted } int pivot = 0; List&lt;int&gt; less = new List&lt;int&gt;(); List&lt;int&gt; greater = new List&lt;int&gt;(); for (int i = 1; i &lt; array.Count;i++ ) { if (array[i] &lt;= array[pivot]) { less.Add(array[i]); } else { greater.Add(array[i]); } } List&lt;int&gt; combined = Quicksort(less); combined.Add(array[pivot]); combined.AddRange(Quicksort(greater)); return combined; } </code></pre> <p>So for the <code>List = {211, 16, 42, 166, 192, 2, 13, 81, 6, 1, 5, 115, 17, 67};</code> I get following Stopwatch values.</p> <p><strong>Bubblesort</strong>: </p> <blockquote> <p>00:00:00.0002873</p> </blockquote> <p><strong>Quicksort</strong>: </p> <blockquote> <p>00:00:00.0003831</p> </blockquote> <p>Does this mean my Quicksort code is poor or did I misunderstand the Stopwatch concept?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T13:23:21.640", "Id": "78746", "Score": "4", "body": "If I were you, I'd write many test cases, with different kind of arrays (sorted, reversed, shuffled, all values different, a single value, etc) of different size (empty, small, huge) and ensure that data are properly sorted. Once you've done this, it will be easier to spot if something is wrong in either the correctness or the performances and understand why things do not work the way is it expected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T13:37:16.427", "Id": "78749", "Score": "2", "body": "Also: don't run a performance test only once – you are still in the millisecond range. Instead: Try counting the number of iterations during a three-second run for a better benchmark. Notice also that your bubblesort works in-place, whereas the quicksort copies each item multiple times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:10:43.017", "Id": "78765", "Score": "0", "body": "The code to set pivot to a reasonble value seem to be missing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-21T12:17:22.930", "Id": "218523", "Score": "5", "body": "I'm voting to close this question as off-topic because Questions asking for explanations of code *behavior* is off topic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-21T12:53:55.587", "Id": "218530", "Score": "0", "body": "please read this article : https://www.quora.com/Which-is-faster-quicksort-or-bubble-sort" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-21T15:42:09.193", "Id": "218577", "Score": "0", "body": "Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/34660/discussion-between-kasebrot-and-bruno-costa)." } ]
[ { "body": "<p>It is normal in production quality qsort code to switch to another sorting method (maybe a unrolled bubble sort) when the size of the input is small (often 8 is used). QSort has very high overheads, but scales well, for a small input size the overheads are much more important than the scaling.</p>\n\n<p>If you run your code on an input that is 1000 items long, then I expect that your qsort would be faster than your bubble sort. </p>\n\n<p>Try writing a test problem that increases your input size in steps of 100 and then graph the results with both sorting methods.</p>\n\n<p>The other way to look at it, is to find the largest input that each sort method can sort in say 5 seconds.</p>\n\n<hr>\n\n<hr>\n\n<p>Also your qSort could be written to be a lot faster by not creating 3 new <code>Lists</code>, it is also very important to quickly choose a good item to privet on. You do not even set the size of the list when you create them, hence each list will have to be reallocated and copied many times as you add items to it.</p>\n\n<p>You have a qSort that is implemented is an inefficient way compared to a boubleSort that is close to the best implementation for boubleSort.</p>\n\n<p>Yet as you confirmed in your comment the qSort does better when you have over 10000 items, slowing just how much better qSort scales.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T14:56:50.023", "Id": "78759", "Score": "0", "body": "You were right, the scaling became significant after an array size of ca. 10000 though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:12:19.360", "Id": "78769", "Score": "1", "body": "@bodycountPP, Also your qSort could be written to be a lot faster by not creating 3 new arrays, it is also very important to quickly choose a good item to privet on." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T13:42:33.447", "Id": "45214", "ParentId": "45209", "Score": "5" } } ]
{ "AcceptedAnswerId": "45214", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T13:12:44.587", "Id": "45209", "Score": "0", "Tags": [ "c#", "sorting", "quick-sort" ], "Title": "Why is my Bubblesort implementation faster than my Quicksort code?" }
45209
<p>I have a multi-threaded app (WCF) that writes to a MySQL db. I want to use MySQL's built in connection pooling abilities.</p> <p>As far as I can tell, to do that, I should set <code>MySqlConnectionStringBuilder.MinimumPoolSize</code> to some value approximately equal to the number of threads I connect. Then Open/Close the connection for each call to the db. Is this correct? If not, what is the proper way to use pooling?</p> <p>Here is the function I use to send data to the db. It gets called by many threads throughout the day. Hundreds, maybe thousands of times per day.</p> <pre><code>private static void execute(MySqlCommand cmd) { try { MySqlConnectionStringBuilder cnx = new MySqlConnectionStringBuilder(); cnx.Server = MySqlServer; cnx.Database = Database; cnx.UserID = UserId; cnx.Password = Pass; cnx.MinimumPoolSize = 100; cmd.Connection = new MySqlConnection(cnx.ToString()); cmd.Connection.Open(); cmd.ExecuteNonQuery(); } catch (MySqlException e) { System.Console.WriteLine(e.Message); } finally { if (null != cmd.Connection) { cmd.Connection.Close(); } } } </code></pre>
[]
[ { "body": "<p>Yes, your code will use pooling.</p>\n\n<p>You might, for the sake of server efficiency, use a smaller <code>MinimumPoolSize</code> (say, 20), and a larger <code>MaximumPoolSize</code> (something a little larger than your maximum number of threads).</p>\n\n<p>You probably don't need all those connections all the time. If your threads do anything significant between their uses of the function you've shown, a significant number of your connections will be idle.</p>\n\n<p>Unless you're sure you need all those connections all the time, you should reduce the RAM and thread burden on your server with a smaller <code>MinimumPoolSize</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-09T23:32:00.257", "Id": "46763", "ParentId": "45211", "Score": "3" } } ]
{ "AcceptedAnswerId": "46763", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T13:28:00.323", "Id": "45211", "Score": "5", "Tags": [ "c#", "mysql", "connection-pool" ], "Title": "Multithreaded app for writing to a MySQL database" }
45211
<p>Based on several different sources, I have compiled the following as my basic HTML email template. Please let me know if I have missed anything important. I am not sure if I am using <code>\n</code> and <code>\r\n</code> correctly.</p> <pre><code>$semi_rand = uniqid(); $mime_boundary = "==MULTIPART_BOUNDARY_$semi_rand"; $mime_boundary_header = chr(34) . $mime_boundary . chr(34); $boundary = "nextPart"; $headers = "From: ".$from."\n"; $headers .= "To: ". $to ."\n"; $headers .= "CC: ". $CC ." \r\n"; $headers .= "Reply-To: ".$from."\r\n"; $headers .= "Return-Path: &lt;". $data['from'] ."&gt;\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: multipart/alternative;\n boundary=" . $mime_boundary_header ; $headers .= "\n--$boundary\n"; // beginning \n added to separate previous content $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n"; $headers .= "\n--$boundary\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "Content-Transfer-Encoding:base64\r\n"; $body = " --$mime_boundary Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit ". strip_tags($message) ." --$mime_boundary Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding:base64 ". chunk_split(base64_encode( '&lt;html&gt;&lt;head&gt;&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;'. $style.'&lt;/head&gt;&lt;body&gt;'.$message.'&lt;/body&gt;&lt;/html&gt;' )) ." --$mime_boundary--"; mail(null,$subject,$body,$headers,"-f".$email); </code></pre> <p>Questions:</p> <ol> <li>Will switching <code>base64_encode()</code> to <code>quoted_printable_encode()</code> work or will I also need to convert the string to an 8-bit string somehow?</li> <li>Should I just remove these extra headers?</li> <li>Could/should I use <code>\r\n\</code> at every line break, including the ones in the multiline string?</li> </ol>
[]
[ { "body": "<p>Some notes:</p>\n\n<p><strong>base64</strong></p>\n\n<p>It's not usual to <code>base64_encode</code> HTML. While the way you've done it will work, you run the risk of being marked as spam as spam filters see attempts at obfuscating emails as shady. Consider Quoted-Printable instead.</p>\n\n<p><strong>$boundary?</strong></p>\n\n<p>This section doesn't make sense:</p>\n\n<pre><code>$headers .= \"\\n--$boundary\\n\"; // beginning \\n added to separate previous content\n$headers .= \"Content-type: text/plain; charset=iso-8859-1\\r\\n\";\n$headers .= \"\\n--$boundary\\n\";\n$headers .= \"Content-type: text/html; charset=iso-8859-1\\r\\n\";\n$headers .= \"Content-Transfer-Encoding:base64\\r\\n\";\n</code></pre>\n\n<p>You are correctly defining and using <code>$mime_boundary_header</code>, these extra headers are unnecessary and will break the email.</p>\n\n<p><strong>New Lines</strong></p>\n\n<p>You've ended 'To' and 'From' with <code>\"\\n\"</code>, these should be <code>\"\\r\\n\"</code>. You're also using a multiline string for <code>$body</code>. This is ok, but make sure your text editor is using <code>CRLF</code> (<code>\"\\r\\n\"</code>) for new lines.</p>\n\n<p><strong>To</strong></p>\n\n<p>You still need to pass <code>$to</code> into <code>mail()</code> as the email 'To' header and the recipient can technically be different:</p>\n\n<p><code>mail($to,$subject,$body,$headers,\"-f\".$email);</code></p>\n\n<p><strong>Extra Notes</strong>\n<em>(This is stuff that doesn't really matter)</em></p>\n\n<ul>\n<li>The way you generate <code>$semi_rand</code> is acceptable, but you might want to consider using <code>uniqid()</code> instead</li>\n<li>If your return-path and reply-to values are the same as your from, you don't need to specify them</li>\n</ul>\n\n<h1>Edits in Light of New Questions</h1>\n\n<p><strong>Base 64 to Quoted Printable</strong></p>\n\n<blockquote>\n <p>Will switching base64_encode() to quoted_printable_encode() or will I also need to convert the string to an 8-bit string somehow?</p>\n</blockquote>\n\n<p>The PHP function <code>quoted_printable_encode()</code> will do that for you - quoted printable is designed to produce 7bit output</p>\n\n<p>Make sure you also update the header to <code>Content-Transfer-Encoding:quoted-printable</code> as well</p>\n\n<p><strong>Removing Unnecessary headers</strong></p>\n\n<blockquote>\n <p>Should I just remove these extra headers?</p>\n</blockquote>\n\n<p>Yes, they aren't required for anything</p>\n\n<p><strong>New Lines</strong></p>\n\n<blockquote>\n <p>Could/Should I use \\r\\n\\ at every line break, including the ones in the multiline string?</p>\n</blockquote>\n\n<p>You don't <em>have</em> to if you're sure your text editor will use <code>CRLF</code>s, however I prefer to explicitly use <code>\"\\r\\n\"</code> for my emails, as you have done for the <code>$headers</code> variable, as it tends to be clearer and reduces the risk of the line endings being changed if you / someone else ever resaves the file with a different editor, etc</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-03T00:11:13.580", "Id": "46122", "ParentId": "45215", "Score": "6" } } ]
{ "AcceptedAnswerId": "46122", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T13:45:19.313", "Id": "45215", "Score": "2", "Tags": [ "php", "html", "email" ], "Title": "HTML email template" }
45215
<p>Unlike Perl, you can't to my knowledge match a regular expression inside an if statement in Python and assign the result to a varaible at the same moment. This leads to typical constructs like this:</p> <pre class="lang-py prettyprint-override"><code>match = re.search(REGEX, STRING) if match: # do something </code></pre> <p>So far, so Python. But what if I want to iterate through a file / array of lines, check each line for a few regexes, and fire a catch-all when none has matched? I can't think my way around a rather unwieldy and deeply nested if-else-if-else...-construction:</p> <pre class="lang-py prettyprint-override"><code>import re strings = ["abc zzz", "y", "#comment"] for s in strings: match = re.search("(\S+) (\S+)", s) if match: print "Multiword: %s+%s" % (match.group(1), match.group(2)) else: match = re.match("y$", s) if match: print "Positive" else: match = re.match("n$", s) if match: print "Negative" else: # a few more matches possible in real life script, # and then the last catch-all: print "No match found, line skipped" </code></pre> <p>Isn't there any way to put this in a much nicer looking elif-construction or something? The following doesn't work in Python, because if-clauses take only expressions, not statements. However, something along these lines would strike me as pythonic, or am I blind to something obvious here?</p> <pre class="lang-py prettyprint-override"><code>if match = re.search(" ", s): print "Multiword: %s+%s" % (match.group(1), match.group(2)) elif match = re.match("y$", s): print "Positive" else: print "No match found, line skipped" </code></pre>
[]
[ { "body": "<p>You can make flow of your application more linear by either <code>return</code>-ing from the method when failing or do it <code>Python way</code> using <code>Exceptions</code>, e.g.:</p>\n\n<pre><code>try:\n if not do_action_1:\n raise Exception('Action 1 failed')\n if not do_action_2:\n raise Exception('Action 2 failed')\n if not do_action_3:\n raise Exception('Action 3 failed')\n if not do_action_4:\n raise Exception('Action 4 failed')\n if not do_action_5:\n raise Exception('Action 5 failed')\nexcept Exception as e:\n print 'Whoops: %s' % e\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T14:58:13.280", "Id": "78760", "Score": "7", "body": "I'd rather call this an abuse of exceptions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:01:42.107", "Id": "78761", "Score": "0", "body": "Apart from feeling that I have to agree with @RemcoGerlich on this, I also have to admit I don't quite see how to apply this to my situation. Are the `do_action_x`-parts all supposed to be individual functions, one for each match I'm trying to check?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T14:50:16.393", "Id": "45221", "ParentId": "45220", "Score": "-2" } }, { "body": "<p>Why not using a list of tuple <code>(re, lambda match: action)</code>, that is something like</p>\n\n<pre><code>actions = [(\"(\\S+) (\\S+)\", lambda match: \"Multiword: %s+%s\" % (match.group(1), match.group(2))),\n (\"y$\", lambda match: \"Positive\"),\n (\"n$\", lambda match: \"Negative\")]\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>for rex, action in actions:\n match = re.match(rex, s)\n if match: \n print action(match)\n</code></pre>\n\n<p>If you need to mix search and match then you can use a list of tuple:</p>\n\n<pre><code>(matchmethod, rex, action)\n</code></pre>\n\n<p>as in </p>\n\n<pre><code>actions = [\n (re.search, \"(\\S+) (\\S+)\", lambda match: \"Multiword: %s+%s\"%(match.group(1), match.group(2)) ),\n (re.match, \"y$\", lambda match: \"Positive\"),\n (re.match, \"n$\", lambda match: \"Negative\")]\n</code></pre>\n\n<p>And of course:</p>\n\n<pre><code>for matchtype, rex, action in actions:\n match = matchtype(rex, s)\n if match: \n print action(match)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:04:01.157", "Id": "78762", "Score": "1", "body": "Misses the fact that one of the calls was to re.search, another to re.match." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:08:52.710", "Id": "78764", "Score": "0", "body": "@RemcoGerlich : The solution can be easily adapted. See my edit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:10:46.510", "Id": "78766", "Score": "0", "body": "I know, and it's a valid method. I think it'll depend on the number of tests and how much their code has in common, for deciding if this is a good idea. In general I think it makes the code less readable, but it has the potential to make it a lot shorter, and that's good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:15:49.247", "Id": "78774", "Score": "2", "body": "This is much more complex in understanding then I'm used to, but it seems pretty pythonic. I'll experiment with this, thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:20:31.213", "Id": "78775", "Score": "0", "body": "@thor: this is just pushing further [Python's switch statement](http://stackoverflow.com/questions/374239/why-doesnt-python-have-a-switch-statement)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:00:07.830", "Id": "45222", "ParentId": "45220", "Score": "15" } }, { "body": "<p>I'd put it in a function and <code>return</code> from it when a match was found, that way you don't have all the indents for the <code>else:</code> cases, just a list of tests and returns for them:</p>\n\n<pre><code>import re\nstrings = [\"abc zzz\", \"y\", \"#comment\"]\n\ndef run_tests(s)\n match = re.search(\"(\\S+) (\\S+)\", s)\n if match:\n print \"Multiword: %s+%s\" % (match.group(1), match.group(2))\n return\n\n if re.match(\"y$\", s):\n print \"Positive\"\n return\n\n if re.match(\"n$\", s):\n print \"Negative\"\n return\n\n # a few more matches possible in real life script,\n # and then the last catch-all:\n print \"No match found, line skipped\"\n\nfor s in strings:\n run_tests(s)\n</code></pre>\n\n<p>I'd try to put the list of tests into some data structure to loop over (like the messages and the patterns to test for), but because the code is slightly different (search vs match, simple print vs doing something with match) it's clearer just to keep it like this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:14:17.527", "Id": "78772", "Score": "0", "body": "This works fine until I want to fill different variables under the different matches - then I'd always have to pass the full list of possible variables back and forth between this function and the caller, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:30:22.097", "Id": "78802", "Score": "2", "body": "You can always make your code arbitrarily complex, yes :-). In such cases maybe all of your variables should be part of some sort of State class, and a state variable could be passed to a set of test_ functions, or they could be methods of that class, or et cetera." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:03:29.807", "Id": "45223", "ParentId": "45220", "Score": "13" } }, { "body": "<p>This is a known issue with regexps. But you can just put the options in a container, such as a list, and then use a for loop:</p>\n\n<pre><code>import re\nstrings = [\"abc zzz\", \"y\", \"#comment\"]\nregexps_and_messages = [\n (\"(\\S+) (\\S+)\", \"Multiword: %s+%s\"),\n (\"y$\", \"Positive\"),\n (\"n$\", \"Negative\"),\n]\n\nfor s in strings:\n for regexp, message in regexps_and_messages:\n m = re.match(regexp, s)\n if m is not None:\n print message % m.groups()\n break\n else: # if no break in above loop\n print \"No match found, line skipped\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:13:13.917", "Id": "78771", "Score": "0", "body": "Not that I particularly need the `re.match` vs `re.search` distinction, but this makes it impossible to retain it. Also, the `for ... else` construction is, to my experience, so rarely used that most maintainers wouldn't know right away what this does - or is that just my own ignorance speaking?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:07:52.393", "Id": "78798", "Score": "0", "body": "@Thor not really, if you do need the behavior of `match` just prepend `^` to the applicable regular expressions, e.g. `\"^y$\"` and `\"^n$\"`. The behavior will differ slightly from that of `match` when using the multiline regex flag (it will also match after every newline instead of only at the start of the string being searched), but as you're checking line-by-line anyway that shouldn't make a difference (and in those cases `$` will match before any newlines as well so you'd have to worry about that one too, unless such behavior is desirable)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:03:47.997", "Id": "45224", "ParentId": "45220", "Score": "5" } }, { "body": "<p>You can use the <code>continue</code> keyword to force advancement and move on to evaluating the next string.\nCode after each <code>if</code> statement will only execute if the test in the previous statement was false.</p>\n<pre><code>import re\nstrings = [&quot;abc zzz&quot;, &quot;y&quot;, &quot;#comment&quot;]\nfor s in strings:\n match = re.search(&quot;(\\S+) (\\S+)&quot;, s)\n if match:\n print &quot;Multiword: %s+%s&quot; % (match.group(1), match.group(2))\n continue\n match = re.match(&quot;y$&quot;, s)\n if match:\n print &quot;Positive&quot;\n continue\n match = re.match(&quot;n$&quot;, s)\n if match:\n print &quot;Negative&quot;\n continue\n \n # a few more matches possible in real life script,\n # and then the last catch-all:\n print &quot;No match found, line skipped&quot;\n</code></pre>\n<hr />\n<p><strong>Revisiting in 2021</strong></p>\n<p>Since Python 3.8 we now have assignment expressions! You can do something like this:</p>\n<pre><code>import re\nstrings = [&quot;abc zzz&quot;, &quot;y&quot;, &quot;#comment&quot;]\nfor s in strings:\n if match := re.search(&quot;(\\S+) (\\S+)&quot;, s):\n print &quot;Multiword: %s+%s&quot; % (match.group(1), match.group(2))\n\n elif match := re.match(&quot;y$&quot;, s):\n print &quot;Positive&quot;\n\n elif match := re.match(&quot;n$&quot;, s):\n print &quot;Negative&quot;\n\n # a few more matches possible in real life script,\n # and then the last catch-all:\n else:\n print &quot;No match found, line skipped&quot;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:11:14.990", "Id": "78768", "Score": "0", "body": "On the one hand, this doesn't look perfectly \"clean\" to me, on the other it's easy to understand and I'd say it'd keep easy to maintain. I'll have to check this a bit more in-depth tomorrow, but thanks for the reply!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:48:24.177", "Id": "78779", "Score": "0", "body": "@Thor the only problem with this structure, which I somehow like, is that it's so easy to forget to add a `continue` in a new clause you add later" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-03-24T15:03:58.030", "Id": "45225", "ParentId": "45220", "Score": "30" } }, { "body": "<p>I like @hivert's approach, but would formalize it a bit more:</p>\n\n<pre><code>import re\n\ntests = [\n (\"(\\S+) (\\S+)\", \"Multiword: {0}+{1}\"),\n (\"^y$\", \"Positive\"),\n (\"^n$\", \"Negative\")\n]\n\ndef get_first_match(s, tests=tests, none_match=\"No match found, line skipped\"):\n for reg,fmt in tests:\n match = re.search(reg, s)\n if match:\n return fmt.format(*match.groups())\n return none_match\n</code></pre>\n\n<p>then</p>\n\n<pre><code>strings = [\"abc zzz\", \"y\", \"#comment\"]\nfor s in strings:\n print(get_first_match(s))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:52:43.620", "Id": "79036", "Score": "0", "body": "The first one was `re.search`, the others are `re.match`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T20:01:49.877", "Id": "79041", "Score": "1", "body": "@Izkata: that is why I prepended a \"^\" to them - it forces .search to behave like .match (only match at start of line)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:09:43.860", "Id": "45227", "ParentId": "45220", "Score": "6" } }, { "body": "<p>To go even further on the approaches suggested that put the regexes in a list you could join the regexes together with | and then match the line against all possible patterns in one go. </p>\n\n<pre><code>import re\n\nclass LineMatcher(object):\n def __init__(self, patterns):\n # In order to match each string, we build a regex combining which can match\n # all the parts. \n # Something like: ((\\S+) (\\S+))|(y$)|(n$)|(.*))\n # When we match against it, we can figure out which pattern was matched\n self._groups = {}\n regexes = []\n\n # because groups could contain groups, we need to keep track of the current\n # group index so that we know which index each pattern will end up with.\n current_group_index = 1\n for pattern, handler in patterns:\n group_count = re.compile(pattern).groups\n self._groups[current_group_index] = (group_count, handler)\n regexes.append(\"(%s)\" % pattern)\n current_group_index += group_count + 1\n\n self._regex = re.compile(\"|\".join(regexes))\n\n def match(self, string):\n match = self._regex.match(string)\n group_count, handler = self._groups[match.lastindex]\n captures = match.groups()[match.lastindex:match.lastindex + group_count]\n return handler(*captures)\n\n\nmatcher = LineMatcher([\n (\"(\\S+) (\\S+)\", lambda first, second: \"Multiword: %s+%s\"),\n (\"y$\", lambda: \"Positive\"),\n (\"n$\", lambda: \"Negative\"),\n (\".*\", lambda: \"No match found, line skipped\")\n])\n\n\nstrings = [\"abc zzz\", \"y\", \"#comment\"]\nfor s in strings:\n print matcher.match(s)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:14:12.940", "Id": "78799", "Score": "0", "body": "I like this solution because it avoids having to re-execute the regular expression searches for each possibility; you will still have a similar number of conditionals, essentially, but short-circuited checks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:54:47.050", "Id": "78911", "Score": "0", "body": "I like this solution, it seems very pythonic, extensible, and \"cleaner\" than the `continue`-approach of @Calpratt. On the other hand, I can grasp that approach within the first glance of the code, whereas here I have to work my way through it. I guess my question now is: If you stumbled across something like this in code you have to maintain, which would make life easier for you? With this in mind, I'll choose the cruder but easier `continue`-approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:21:15.243", "Id": "78941", "Score": "0", "body": "It should be noted that this approach only works because the regexes are all mutually exclusive. If you needed it to be multi-word *and* end in a 'y', for example, this can't be used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T20:37:55.620", "Id": "79049", "Score": "0", "body": "@Gabe, actually in my code above its not mutually exclusive. Not that .* matches anything. I think that in the case of ambiguity it always returns the first match." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:40:19.720", "Id": "45231", "ParentId": "45220", "Score": "5" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/45225/31800\">Calpratt's answer</a> without <code>continue</code>:</p>\n\n<pre><code>import re\nstrings = [\"abc zzz\", \"y\", \"#comment\"]\nfor s in strings:\n match = re.search(\"(\\S+) (\\S+)\", s)\n if match:\n print \"Multiword: %s+%s\" % (match.group(1), match.group(2))\n elif re.match(\"y$\", s):\n print \"Positive\"\n elif re.match(\"n$\", s):\n print \"Negative\"\n else:\n print \"No match found, line skipped\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:49:53.777", "Id": "78909", "Score": "2", "body": "Yes, but this works only for exactly this situation. From the first `elif` onwards you have no chance to access the match result. There's even the danger of trying to access the `match` object in the `elif` branches, which would lead to working on wrong results. No downvote as this is not wrong per se, but it's not as flexible as the other approaches." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:41:23.340", "Id": "45244", "ParentId": "45220", "Score": "5" } }, { "body": "<p>Once you recognized the pattern in your code, you can wrap it as a base class to avoid boilerplates. This also makes the code more maintainable.</p>\n\n<pre><code>import re\n\nclass Handler:\n PATTERN = ''\n def __init__(self):\n self._pattern = re.compile(self.PATTERN)\n\n def match(self, *args, **kwargs):\n return self._pattern.match(*args, **kwargs)\n\n def handle(self, matched):\n pass\n\nclass MultiwordHandler(Handler):\n PATTERN = '(\\S+) (\\S+)'\n\n def match(self, *args, **kwargs):\n return self._pattern.search(*args, **kwargs)\n\n def handle(self, matched):\n print 'Multiword: %s+%s' % (matched.group(1), matched.group(2))\n\nclass PositiveHandler(Handler):\n PATTERN = 'y$'\n\n def handle(self, matched):\n print 'Positive'\n\nclass NegativeHandler(Handler):\n PATTERN = 'n$'\n\n def handle(self, matched):\n print 'Negative'\n</code></pre>\n\n<p>And use them like this:</p>\n\n<pre><code>handlers = [MultiwordHandler(), PositiveHandler(), NegativeHandler()]\n\nstrings = [\"abc zzz\", \"y\", \"#comment\"]\n\nfor s in strings:\n for handler in handlers:\n matched = handler.match(s)\n if matched:\n handler.handle(matched)\n break\n else:\n print \"No match found, line skipped\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:01:18.003", "Id": "45388", "ParentId": "45220", "Score": "3" } }, { "body": "<p>A hackish idea, defining a helper function <code>match</code> which at success overwrites itself with the result:</p>\n<pre><code>import re\nstrings = [&quot;abc zzz&quot;, &quot;y&quot;, &quot;#comment&quot;]\nfor s in strings:\n def match(result):\n if result:\n global match\n match = result\n return result\n if match(re.search(&quot;(\\S+) (\\S+)&quot;, s)):\n print &quot;Multiword: %s+%s&quot; % (match.group(1), match.group(2))\n elif match(re.match(&quot;y$&quot;, s)):\n print &quot;Positive&quot;\n elif match(re.match(&quot;n$&quot;, s)):\n print &quot;Negative&quot;\n else:\n print &quot;No match found, line skipped&quot;\n</code></pre>\n<p><a href=\"https://tio.run/##dVDBasMwDL3nK4S6QExDYT0W9gkbgx63HdJESc0c21jORvLzmROX1WPkHYT8pKf3sB391ejjPMveGufBUcbeSd0xPMEbVpcapmnCEnBcyq42fU/a40fWGgcMUsNt/5RBQEMt9JWvr4UjHpQXkV4gW4jcnVrQKXOpVBT9GaxMSBFFvyNHfnA6ZeXd8sBUudBh8X7eC1hryM0iyWFDXA/4HOTy27jmBDnvc0bIoVjvHDpnBls8ihLS91GI9Qap1DA2OD5s2Lwall5@EW5r9Zb2hboq1TL9XzG3f2rNoJsSlNQE/CmtpQbn@Qc\" rel=\"nofollow noreferrer\" title=\"Python 2 – Try It Online\">Try it online!</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T08:30:41.073", "Id": "528840", "Score": "1", "body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T10:12:12.813", "Id": "528845", "Score": "0", "body": "@TobySpeight Just like all other answers, including the accepted one with its 30 upvotes, no? How is mine any different? How did they \"review\" any more than I did?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T10:20:16.780", "Id": "528847", "Score": "0", "body": "Many of those answers are very old, and wouldn't be acceptable if posted today. Don't take low-quality _old_ posts as your benchmark. (OTOH, if you find _new_ posts that don't review the code, please do flag them for attention)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T10:21:03.127", "Id": "528848", "Score": "0", "body": "@TobySpeight Ah, ok. So I need to fake a review just because I'm late to the party. I'll try." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T10:24:08.863", "Id": "528850", "Score": "0", "body": "Or answer some newer questions (this question is arguably off-topic, as it seems to be example code rather than the real thing)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T09:49:05.563", "Id": "267991", "ParentId": "45220", "Score": "0" } } ]
{ "AcceptedAnswerId": "45225", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-03-24T14:45:21.080", "Id": "45220", "Score": "35", "Tags": [ "python" ], "Title": "Search for a multiword string in a list of strings" }
45220
<p>Here is a practice question I am solving:</p> <blockquote> <p>Write a function to find the first non-repeated character in a string. For instance, the first non-repeated character in 'total' is 'o' and the first non-repeated character in 'teeter' is 'r'.</p> </blockquote> <p>How can I improve the efficiency of this algorithm?</p> <pre><code>function repeater(string){ var charCount = {}; for(var i = 0; i &lt; string.length; i++){ if(charCount[string[i]]){ charCount[string[i]] = 'More Than One'; } else { charCount[string[i]] = 'One Time'; } } for(var j = 0; j &lt; string.length; j++){ if(charCount[string[j]] === 'One Time'){ return string.charAt(j); } } return 'Everything is repeated'; } </code></pre> <p><a href="http://repl.it/QUf/1" rel="nofollow">http://repl.it/QUf/1</a></p> <p>I also solved this using a nested loop: </p> <pre><code>var nonRepeater = function(str) { var index = []; var count; str.split('').forEach(function(letter, i) { count = 0; str.split('').forEach(function(latter) { if (letter === latter) { count += 1; } }); index.push(count); }); // console.log(index.indexOf(1)); return str[index.indexOf(1)]; }; </code></pre> <p><a href="http://repl.it/QVI/2" rel="nofollow">http://repl.it/QVI/2</a></p> <p>I am trying to find a way to increase the efficiency of this algorithm. I am toying with ways to use a RegEx. </p> <p>Does anyone know how to write this more efficiently in JavaScript? I have found a few guides in C but I do not know the language well.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T18:16:49.843", "Id": "78810", "Score": "0", "body": "first solution is O(n) so as good as it gets, but instead of 'More than one' and 'One Time' I would change the values to a boolean or int, checking if `charCount[string[j]] === 'One Time'` on each index is probable slower than `multiple[string[j]] === true`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T19:07:06.593", "Id": "78818", "Score": "0", "body": "Interesting: in a higher-level language (`R` example here), this would be (rle is \"run-length encoder\" ) `foo<- rle(sort(my.data)); bar<- foo$values[foo$lengths==1][1]; which(my.data==bar) `" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T11:48:12.470", "Id": "78916", "Score": "0", "body": "You probably should use `hasOwnProperty` to check for the presence on a key in the set." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:51:17.080", "Id": "79061", "Score": "0", "body": "Is the search case sensitive? i.e., does \"taTer\" still match t as the first non-repeater, or would it be a?" } ]
[ { "body": "<p>The runtime of the 1st solution you posted is not O(n<sup>2</sup>).\nYou are just traversing the string twice, which makes it O(2n) => O(n).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:54:54.813", "Id": "78782", "Score": "1", "body": "This doesn't look like a solution - it's more a comment" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T16:10:00.583", "Id": "78787", "Score": "3", "body": "@Antonio I'd consider this an allowable answer under the [\"your code seems fine\"](http://meta.codereview.stackexchange.com/q/94/9357) rule." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T16:13:19.463", "Id": "78789", "Score": "2", "body": "@200_success I thought the reviewer then ought to state why the code is fine ? http://meta.codereview.stackexchange.com/questions/850/what-to-do-with-good-code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T16:17:49.977", "Id": "78790", "Score": "0", "body": "@konijn That would have made a better answer, but I had to comment in defense to save it from deletion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T16:41:39.260", "Id": "78792", "Score": "0", "body": "@200_success Fair, though personally I would have voted to convert this to a comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T20:16:57.227", "Id": "78825", "Score": "0", "body": "To be precise, the first solution *is* also `O(n²)`. O is (informally speaking) just an upper bound. See also [this more thorough explanation](http://stackoverflow.com/a/471206/603003)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T22:55:39.820", "Id": "78849", "Score": "1", "body": "@ComFreek - the first solution is *O(n)* . If you double the length of the string, it takes twice as long, not 4 times as long. The performance is proportional to the length of the string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:41:07.960", "Id": "78930", "Score": "0", "body": "@rolfl I think you misunderstood me. My point was that the first solution is *also* contained in the set `O(n²)`. `O(n)` is a subset of `O(n²)`. It is therefore *not* wrong to say `f(x) ∈ O(n²)` if `f(x) ∈ O(n)` also applies. They are both correct. See also [here](http://www.cs.berkeley.edu/~jrs/61b/lec/20) or [here](http://en.wikipedia.org/wiki/Big_O_notation#Use_in_computer_science)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:44:33.267", "Id": "78931", "Score": "7", "body": "@ComFreek - I understand you now. You are right, of course... just like it would be accurate to say the upper-bound of the speed Hussein Bolt runs is the speed of light. Accurate, but useless." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:40:56.967", "Id": "45232", "ParentId": "45228", "Score": "5" } }, { "body": "<p>I'm proposing a solution that <strong>in some cases</strong> can be better than your first algorithm, but not always - <strong>it mostly depends on the input string</strong>. I think that on average they have similar performance.</p>\n\n<p>The idea is to use a regex to search and replace with an empty string all occurrences of the first character. If the resulting string has length equal to the length at the previous iteration <em>minus 1</em>, then that character is not repeated. The search is case <em>insensitive</em></p>\n\n<p>The advantage of this code is that it's more compact and readable, plus it immediately breaks as soon as a non repeating character is found.</p>\n\n<pre><code>var repeater = function(string) {\n var result = false;\n\n while (string) {\n var len = string.length;\n var char = string[0];\n var regex = new RegExp(char, \"gi\");\n string = string.replace(regex, \"\");\n if (string.length == len - 1) {\n result = char;\n break;\n }\n }\n return result;\n}\n</code></pre>\n\n<p><strong>Update</strong>: I ran a few benchmarks, and on average it takes less than your first algorithm (using code runner and node.js). This is the benchmarking code:</p>\n\n<pre><code>var start = Date.now();\n\nfor (var count = 0; count &lt; 10000; ++count) {\n repeater('toTal');\n repeater('teEter');\n repeater('erttreert');\n repeater('repeaterqetyhgerdfcvvgfnk');\n}\n\nvar end = Date.now();\n\nconsole.log(\"\\nTime: \" + (end - start) + \"ms\");\n</code></pre>\n\n<p>and the results are around 60ms for my algorithm, 110-120ms for yours.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:31:11.860", "Id": "78803", "Score": "0", "body": "http://jsperf.com/first-non-repeated I dont think so, it would not make sense, the regex is O(n), so unless the first non-repeater is the first or the second character, your code should be slower." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:38:04.710", "Id": "78805", "Score": "0", "body": "Hmm... tested that, but it tells me repeater2 is better. repeater1 is reported as 56% slower. I'm on mac, using chrome. Are you using a different browser?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:41:24.190", "Id": "78806", "Score": "0", "body": "Also tried with Safari, FF and IE, same outcome (but ofc with different numbers)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:43:54.523", "Id": "78807", "Score": "0", "body": "Chrome, windows (
Chrome 35.0.1897 (1)), which is funny, the only combo where the OP code is faster, most interesting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T19:20:48.287", "Id": "78821", "Score": "0", "body": "To add more fuel to the fire, I tried Chrome on windows and the result is the opposite than yours. I swear I did not hack jsperf.com ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T20:43:00.423", "Id": "78829", "Score": "1", "body": "I think it would be more fair if the OP used 1 and 2 instead of \"More than One\" and \"One Time\"" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:16:07.527", "Id": "45240", "ParentId": "45228", "Score": "5" } }, { "body": "<p>After playing a lot with jsperf and having to admit that the regex solution is actually faster, which annoys me.</p>\n\n<ul>\n<li><p>Your first approach is far superior than your second approach (O(2n) -> O(n^2)) as per Venu</p></li>\n<li><p>you should cache <code>string.length</code>, looking up the value of a property slows things down</p>\n\n<pre><code>for(var i = 0, length = string.length; i &lt; length; i++){\n</code></pre></li>\n<li><p>You can assign <code>More than one</code> and <code>One time</code> with a ternary, also you should cache string[i] and not look it up 3 times:</p>\n\n<pre><code>charCount[c] = charCount[c] ? 'More Than One' : 'One Time';\n</code></pre></li>\n<li><p>You do not need <code>var j</code>, just use <code>i</code> again</p></li>\n<li><p>You used <code>string[i]</code> everywhere else, your return statement should be <code>return string[i];</code></p></li>\n<li><p><code>repeater</code> is a terrible name if you are planning to return a non-repeater ;)</p></li>\n<li><p>from a design perspective, I would return <code>''</code> instead of <code>'Everything is repeated'</code>, because really, <code>''</code> aka nothing is repeating</p></li>\n</ul>\n\n<p>On the whole I think your code is fine, I am not sure ( besides the magical regex ) how it could be done much faster. You need something to track the character count and I am not sure how you can avoid the second loop.</p>\n\n<p>Update: books.google.com/books?isbn=1118169387 &lt;- This pretty much agrees that your first approach is as fast as it gets ( except for the mind boggling regex ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T18:23:49.643", "Id": "45247", "ParentId": "45228", "Score": "8" } }, { "body": "<p>This solution has an upper bound of O(n^2) and an lower bound of O(n). It has a good average performance for short strings and strings with many repeated characters.</p>\n\n<pre><code>function repeater(string)\n{\n if(string.length==0)\n return false;\n\n var char = string.charAt(0);\n if(string.lastIndexOf(char) == 0)\n return char;\n\n for(var i = 1; i &lt; string.length-1; ++i)\n {\n char = string.charAt(i);\n if(string.lastIndexOf(char)==i &amp;&amp; string.indexOf(char)==i)\n return char;\n }\n\n char = string.charAt(string.length-1);\n if(string.indexOf(char)==string.length-1)\n return char;\n\n return false;\n}\n</code></pre>\n\n<h2>Edit</h2>\n\n<p>I found a faster solution. This solution has an upper bound of O(n^2-n/2) and a lower bound of O(n). It is about 25 times faster than the original and 3 times faster than my previous version. See <a href=\"http://jsperf.com/first-non-repeated/7\" rel=\"nofollow\">jsperf</a>.</p>\n\n<pre><code>var g_string = new Uint32Array(100);\nfunction repeater(string)\n{\n if(string.length==0)\n return false;\n if(string.length&gt;g_string.length)\n g_string = new Uint32Array(string.length);\n\n var length = 0;\n var char = string.charCodeAt(0);\n for(var i=1;i&lt;string.length;++i)\n {\n var chari = string.charCodeAt(i);\n if(chari != char)\n g_string[length++] = chari;\n }\n if(length == string.length-1)\n return String.fromCharCode(char);\n\n while(length)\n {\n var char = g_string[0];\n var length_new = 0;\n for(var i=1;i&lt;length;++i)\n {\n if(g_string[i] != char)\n g_string[length_new++] = g_string[i];\n }\n if(length_new == length-1)\n return String.fromCharCode(char);\n length = length_new;\n }\n\n return false;\n}\n</code></pre>\n\n<p>This function removes the first character from the string and copies in-place all characters that don't match the first character into an array. This is repeated until no duplicates are found for a character or the array is empty. What makes this version so fast is that the array is allocated in the global namespace. It only needs to be reallocated when you pass a string longer than the array.</p>\n\n<h2>Edit 2</h2>\n\n<p>Okay last one I swear. This version is only about 10% faster than the previous solution, but I think it is notable because it is O(n) in every case. Note that this one will not work for character codes > 255, which makes it bad for most real world applications.</p>\n\n<pre><code>var g_string = new Uint32Array(100);\nvar g_char = new Uint32Array(256);\nfunction repeater(string)\n{\n if(string.length&gt;g_string.length)\n g_string = new Uint32Array(string.length);\n for(var i=0;i&lt;string.length;++i)\n {\n g_string[i]=string.charCodeAt(i)&amp;0xFF;\n ++g_char[g_string[i]];\n }\n var ret = false;\n for(var i=0;i&lt;string.length;++i)\n {\n if(g_char[g_string[i]]==1)\n {\n ret = string[i];\n break;\n }\n }\n for(var i=0;i&lt;string.length;++i)\n g_char[g_string[i]] = 0;\n return ret;\n}\n</code></pre>\n\n<p>It increments a character frequency table for each character in the string. Then it iterates over the string again until it finds a character with a frequency of 1. It iterates over the string one final time and zeros the character frequency table so that we can reuse it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T21:48:27.873", "Id": "45258", "ParentId": "45228", "Score": "4" } }, { "body": "<p>This is actually a pretty interesting question, and it shows that big O notation can be misleading.</p>\n\n<p>Your first attempt is pretty good. It does loop through the string twice, so you might think that it's O(n), but each iteration is doing a lookup on the <code>charCount</code> dictionary. Now <code>charCount</code> can have at most <code>i</code> entries each time through, how does that effect our complexity? It's hard to say; the JS engine can implement this in several ways, but it's probably <a href=\"https://stackoverflow.com/questions/7700987/performance-of-key-lookup-in-javascript-object\">not constant time</a>. Lookups like this tend to be O(log n) so I'd say overall your first implementation is O(n log n) (worst case).</p>\n\n<p>The regular expression solution that seems to be fastest (in clock time) is far less \"efficient\". We know that applying regular expressions is O(n) and doing it in a loop will end up being O(n<sup>2</sup>) worst case. But the regex engine is written in C and is a core part of the js engine, so it's very believable that applying a regex can be much faster than looping through a string in JavaScript. So from an algorithmic standpoint, it's O(n<sup>2</sup>), but you would not expect the performance graph to look anything like a parabola.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:09:53.473", "Id": "45321", "ParentId": "45228", "Score": "1" } }, { "body": "<p>This is an interesting problem. I added one which seems to perform a bit better (though it might just be on Chrome + Windows, it performs just a hair better than repeater2).</p>\n\n<p>It is O(n).</p>\n\n<pre><code>function repeater4(test) {\n while (test &amp;&amp; /^(.)(?:.*\\1)/.test(test)) {\n test = test.replace(new RegExp(test[0], 'g'), '');\n }\n\n return test ? ('Matched: ' + test[0]) : 'No matches';\n}\n</code></pre>\n\n<p>JSPerf: <a href=\"http://jsperf.com/first-non-repeated/3\" rel=\"nofollow\">http://jsperf.com/first-non-repeated/3</a></p>\n\n<p>I feel like there is an O(1) solution to this using regex though. I'm mucking around to see if I can come up with something.</p>\n\n<h1>Edit</h1>\n\n<p>Upon thinking, I realized that regex is O(n) (at best), so really there isn't an O(1) method that is possible. Interesting problem, and there is probably some really clever way of speeding it up even more, but I think the solution I came up with seems to be both relatively quick and elegant, so I'll leave it at that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:47:58.937", "Id": "79075", "Score": "0", "body": "This function function assumes the input will only contain letters and it does a case insensitive match. You can change the regex to /^(.)(?:.*\\1)/ to make it behave more like the original and a tiny bit faster. Also, I don't think the fastest solution is a RegExp see the updated jsperf. http://jsperf.com/first-non-repeated/5" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:52:25.063", "Id": "79076", "Score": "0", "body": "I wasn't sure if it was supposed to be case sensitive or insensitive, so I opted for insensitive, though obviously it is a simple change either way. Also, good catch. When I first read it I was thinking letter, but that's a requirement I just made up in my head. I'll update my code example. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:54:22.587", "Id": "79079", "Score": "0", "body": "@Bob65536 Nice solution using lastIndex. That is substantially faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T23:06:58.630", "Id": "79082", "Score": "0", "body": "Thanks. Removing duplicates as they are found would make subsequent searches faster, but unfortunately strings in javascript are immutable. I found that creating a new string or converting the string to an array is too much overhead for small inputs. I like your idea of using a regex to check if the first character is unique." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:49:57.677", "Id": "45352", "ParentId": "45228", "Score": "3" } } ]
{ "AcceptedAnswerId": "45247", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:15:03.897", "Id": "45228", "Score": "13", "Tags": [ "javascript", "algorithm", "strings" ], "Title": "Write a function to find the first non-repeated character in a string" }
45228
<p>I have done some research about intentions of UnitOfWork pattern. In short, what I understood is that UoW is needed for transactions. But I saw some code examples where people use UoW as factory for Repository objects as well, one example is DbContext from EF. My first thought about it doesn't it break single responsibility principle? In my current project I am using both UoW and Repository patterns. Here are my interfaces:</p> <p>UnitOfWork:</p> <pre><code>public interface IUnitOfWork : IDisposable { void Commit(); void Rollback(); IRepository&lt;T&gt; GetRepository&lt;T&gt;() where T : class; } </code></pre> <p>Repository interface:</p> <pre><code>public interface IRepository&lt;T&gt; where T : class { IQueryable&lt;T&gt; FindAll(); IQueryable&lt;T&gt; Find(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); T FindById(Id id); void Add(T newEntity); void Remove(T entity); } </code></pre> <p>My concern is <code>GetRepository&lt;T&gt;</code> method in <code>IUnitOfWork</code> interface. Should this method be here at all? Or should I move it somewhere else? What would you suggest?</p> <p><strong>PS</strong> I am using NHibernate as my ORM tool, but I think this should not make any difference</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:32:25.897", "Id": "78776", "Score": "0", "body": "Are you using [Linq-to-NHibernate](http://stackoverflow.com/questions/624609/linq-to-nhibernate)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:39:00.717", "Id": "78778", "Score": "0", "body": "I am still in architecturing state. But, yes, I am thinking about using Linq to Nhibernate" } ]
[ { "body": "<h3>Leaky abstractions</h3>\n<p>A specific implementation should not <em>leak</em> into an abstraction. By making <code>IUnitOfWork</code> extend <code>IDisposable</code>, that's what you're doing:</p>\n<blockquote>\n<pre><code>public interface IUnitOfWork : IDisposable\n</code></pre>\n</blockquote>\n<p>The goal of the abstraction, is to <em>abstract</em> implementation details away - in this case, the fact that you're using NHibernate. You had a <em>specific implementation</em> in mind when you created this interface, and that implementation <em>leaked</em> into the abstraction. What if you wanted to implement an <code>IUnitOfWork</code> that worked off a <code>List&lt;T&gt;</code>, for testing purposes?</p>\n<p>Not <em>all</em> implementations of <code>IUnitOfWork</code> need to implement <code>IDisposable</code> - better leave that up to the implementation:</p>\n<pre><code>public class NHibernateUnitOfWork : IUnitOfWork, IDisposable\n{\n private readonly ISession _session;\n\n /* implementation */\n\n public void Dispose()\n {\n _session.Dispose();\n }\n}\n</code></pre>\n\n<pre><code>public class TestUnitOfWork : IUnitOfWork\n{\n /* implementation */\n}\n</code></pre>\n<hr />\n<h3>IQueryable</h3>\n<p>Every single implementation of the <em>Repository &amp; Unit of Work</em> patterns I have seen, were different. Every single one.</p>\n<p>Without seeing what your implementations and client code looks like (/how you're using these interfaces), it's very hard to tell whether you've done something wrong.</p>\n<p>For one thing, exposing <code>IQueryable&lt;T&gt;</code> is <em>leaking</em> the query outside your repository, making it possible for client code to call <code>IRepository&lt;T&gt;.FindAll()</code> and then from there, add a <code>Where</code> clause or <code>Join</code> on another repository, which means the repository completely loses control of query materialization, which [unless I missed something] defeats its purpose.</p>\n<p>By exposing a <code>IRepository&lt;T&gt; GetRepository&lt;T&gt;()</code> method on your <code>IUnitOfWork</code>, you're also making it possible for the <em>unit of work</em>'s clients to own the materialization of the query.</p>\n<p>Whether that's good or bad, entirely depends on your architecture; I cannot tell just from the interfaces... I can only raise a flag.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T16:16:09.787", "Id": "45235", "ParentId": "45229", "Score": "5" } } ]
{ "AcceptedAnswerId": "45235", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T15:23:05.107", "Id": "45229", "Score": "2", "Tags": [ "c#", "design-patterns" ], "Title": "UnitOfWork as Repository object factory" }
45229
<p>I'm very new to learning PHP &amp; MySQL (I've got past experience with Java) and I'm doubting whether my code is organised well. I've got an index page which has two forms; the first is a form to login and the second is a form to sign up a user. So far I've only completed the signing up of a user. Please comment on my code in general and what I can improve.</p> <p>The form (table tags removed):</p> <pre><code>&lt;form action='php/signup.php' method='post' name='signup'&gt; &lt;input name='username' type='text' /&gt; &lt;input name='password' type='password' /&gt; &lt;input name='signin' type='submit' value='Sign up' /&gt; &lt;/form&gt; </code></pre> <p>signup.php:</p> <pre><code>&lt;?php try { $db = new PDO(...); $db -&gt; setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); foreach ($db-&gt;query("SELECT username FROM usertable") as $row) { if ($row == $username) { header("Location: http://example.com/#"); return; } } $user = $db-&gt;prepare("INSERT INTO users (username, password) VALUES (:username, :password)"); $user-&gt;execute(array(":username" =&gt; $_POST["username"], ":password" =&gt; $_POST["password"])); $db = null; header("Location: http://example.com/anotherpage.html"); } catch ( PDOException $e ) { echo $e -&gt; getMessage(); } ?&gt; </code></pre>
[]
[ { "body": "<ol>\n<li><p>Iterating through the whole user table could be ineffective:</p>\n\n<blockquote>\n<pre><code>foreach ($db-&gt;query(\"SELECT username FROM usertable\") as $row) {\n</code></pre>\n</blockquote>\n\n<p>You could use a <code>WHERE username LIKE :username</code> condition here. (And you might need a database index for the attribute as well)</p></li>\n<li><p>The code does not check the password. I guess you should do that.</p></li>\n<li><p>You should <a href=\"https://security.stackexchange.com/q/36833/4959\">hash your passwords</a>.</p></li>\n<li><p>Calling a table <code>usertable</code> is a little bit redundant. I'd use simply <code>users</code>.</p></li>\n<li><p>The following is hard to read because it needs horizontal scanning:</p>\n\n<blockquote>\n<pre><code>$user-&gt;execute(array(\":username\" =&gt; $_POST[\"username\"], \":password\" =&gt; $_POST[\"password\"]));\n</code></pre>\n</blockquote>\n\n<p>I would introduce an explanatory variable and some line breaks:</p>\n\n<pre><code>$newuser_parameters = array(\n \":username\" =&gt; $_POST[\"username\"], \n \":password\" =&gt; $_POST[\"password\"]\n);\n$user-&gt;execute($newuser_parameters);\n</code></pre>\n\n<p>From <em>Code Complete, 2nd Edition</em>, p761:</p>\n\n<blockquote>\n <p><strong>Use only one data declaration per line</strong></p>\n \n <p>[...]</p>\n \n <p>It’s easier to find specific variables because you can scan a single\n column rather than reading each line. It’s easier to find and fix\n syntax errors because the line number the compiler gives you has \n only one declaration on it.</p>\n</blockquote>\n\n<p>See also: <em>Chapter 6. Composing Methods, Introduce Explaining Variable</em> in <em>Refactoring: Improving the Design of Existing Code</em> by <em>Martin Fowler</em>; <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>.</p></li>\n<li><p>I would validate at least the maximum length of the username.</p></li>\n<li><p>This probably isn't too useful for your clients:</p>\n\n<blockquote>\n<pre><code>echo $e -&gt; getMessage();\n</code></pre>\n</blockquote>\n\n<p>See #3 in <a href=\"https://codereview.stackexchange.com/a/45075/7076\">my former answer</a>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:31:40.627", "Id": "78804", "Score": "0", "body": "Regarding #2, #3, #6 and #7, I'm too concerned about them because this is for a basic assignment, though I'll implement all of your suggestions anyway. Regarding #1, I was thinking that my implementation wasn't efficient. Thanks a lot. Oh and regarding #5, I'm too used to pressing CRTL-F in eclipse..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T02:28:32.233", "Id": "78859", "Score": "0", "body": "@Someone: I'm glad that it helped. #5: Autoformat is great, I guess you can configure it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T13:29:25.837", "Id": "79166", "Score": "0", "body": "Just one minor hint: You can drop the colons from your user parameter array and it still works fine. array('username' => ... Still use the colon in your prepared statement sql." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:21:23.673", "Id": "45241", "ParentId": "45234", "Score": "3" } } ]
{ "AcceptedAnswerId": "45241", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T16:14:46.043", "Id": "45234", "Score": "4", "Tags": [ "php", "mysql" ], "Title": "Am I organising my PHP code effectively?" }
45234
<p>The code is an implementation of the <a href="http://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method" rel="nofollow">Gauss–Seidel method</a>. I would like a general review of the code.</p> <p>PS: I use code::blocks IDE</p> <pre><code>//generalized code for gauss seidal iteration method #include&lt;stdio.h&gt; #include&lt;malloc.h&gt; #define chk_end 0.01 int row_lim=0,col_lim=0; float** partial_pivot(float** mat,int row,int col);//finds the pivot of matrix int condition(float* result,float* temp,int row);//checks the terminating condition float* final_result(float** mat,float* result,int row,int col);//calculates final result float** create_mat(float** mat,int row,int col);//creates a matrix of row X col float** feed_mat(float** mat,int row,int col);//inputs value in matrix void disp_mat(float** mat,int row,int col);//displays matrix float** partial_pivot(float** mat,int row,int col) { float pivot; int i=0,j=0,k=0,l=0; if(row_lim&lt;row) { for(i=0,j=col_lim;i&lt;row-1;i++) { for(l=row_lim;l&lt;row-i-1;l++) { if(mat[l][j]&lt;mat[l+1][j]) { for(k=0;k&lt;col;k++) { pivot=mat[l+1][k]; mat[l+1][k]=mat[l][k]; mat[l][k]=pivot; } } } } row_lim++; col_lim++; partial_pivot(mat,row,col); } return mat; } int condition(float* result,float* temp,int row) { int i=0,flag = 0; for(i=0;i&lt;row;i++) { if(result[i] &gt; temp[i]) { if((result[i]-temp[i]) &lt; chk_end) { flag = 1; } else { flag = 0; break; } } else { if((temp[i]-result[i]) &lt; chk_end) { flag = 1; } else { flag = 0; break; } } } return flag; } float* final_result(float** mat,float* result,int row,int col) { int k=0,i=0,j=0; float T = 0; float *temp; temp=(float*)malloc((row)*sizeof(float));//Edit: row-1 changed to row for(i=0;i&lt;row;i++) { temp[i] = 0; } printf("Processing result ... \n"); do { for(k=0;k&lt;row;k++) temp[i] = result[i]; //was a logical error, sorry { for(i=0;i&lt;row;i++) { for(j=0;j&lt;(col-1);j++) { if(i==j) { } else { T += (mat[i][j])*(temp[j]); } } result[i] = ((mat[i][col-1] - T)/(mat[i][i])); //temp[i] = result[i]; T=0; } } } while(condition(result,temp,row) == 0); free(temp); return result; } float** create_mat(float** mat,int row,int col) { int i=0; mat=(float**)malloc((row)*sizeof(float*));//Edit: row-1 changed to row if(mat) { for(i=0;i&lt;row;i++) { mat[i]=(float*)malloc((col)*sizeof(float));//Edit: col-1 changed to col } } return mat; } float** feed_mat(float** mat,int row,int col) { int i=0,j=0; for(i=0;i&lt;row;i++) { for(j=0;j&lt;col;j++) { printf("Enter mat[%d][%d] element:\n",i,j); scanf("%f",&amp;mat[i][j]); } } return mat; } void disp_mat(float** mat,int row,int col) { int i=0,j=0; for(i=0;i&lt;row;i++) { for(j=0;j&lt;col;j++) { printf("\t%f",mat[i][j]); } printf("\n"); } } int main() { float **mat,*result; int i=0,row=0,col=0; mat=NULL; printf("Enter the number of Equations :\n"); scanf("%d",&amp;row); col=row+1; result = (float*)malloc((row)*sizeof(float));//Edit: row-1 changed to row for(i=0;i&lt;row;i++) { result[i] = 0; } mat=create_mat(mat,row,col); printf("Enter the values in the %d x %d matrix:\n",row,col); mat=feed_mat(mat,row,col); printf("matrix entered by you:\n"); disp_mat(mat,row,col); mat=partial_pivot(mat,row,col); printf("pivoted matrix entered:\n"); disp_mat(mat,row,col); result = final_result(mat,result,row,col); printf("\nResult is : \n"); for(i=0;i&lt;row;i++) { printf(" x[%d] %f",i,result[i]); } for(i=0;i&lt;row;i++) { free(mat[i]); } free(mat); free(result); return 0; } </code></pre>
[]
[ { "body": "<p>A word of warning: I am very much a C newbie myself, so it may be good to take my advice with a grain of salt.</p>\n\n<h2>Formatting</h2>\n\n<p>The only good thing I can say about your formatting is that it's consistent. But a 1-space indent really isn't readable. I recommend 4 spaces instead. Please put some whitespace around your operators: a space after every comma, a space on each side of <code>=</code>, <code>-</code>, <code>+</code>, <code>*</code>, …. Don't cram multiple assignments on one line: I find</p>\n\n<pre><code>int i, j, k;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>int i = 0;\nint j = 0;\nint k = 0;\n</code></pre>\n\n<p>acceptable, but not <code>int i=0,j=0,k=0;</code>.</p>\n\n<p>If you are targetting a C89-compatible environment, this is as far as we can go. I recommend you move on (e.g. to C++ or C99), where we can put the declaration of <code>for</code>-loop variables inside the loop itself:</p>\n\n<pre><code>for (int i = 0; i &lt; whatever; i++)\n</code></pre>\n\n<p>… and we also don't have to put all declarations at the top of each scope – just declare your variables at the point of first use.</p>\n\n<h2><code>malloc</code> and error handling</h2>\n\n<p>Always check the return value of malloc:</p>\n\n<pre><code>float *temp = (float*) malloc(row * sizeof(float));\nif (temp == NULL)\n{\n /* return some error code */\n}\n</code></pre>\n\n<h2>C isn't object oriented, but whatever</h2>\n\n<p>You always bundle the three variables <code>mat</code>, <code>row</code>, <code>col</code>. I suggest you put those into a struct, and pass this single struct around instead:</p>\n\n<pre><code>typedef struct {\n float **mat;\n int rows;\n int cols;\n} Matrix;\n</code></pre>\n\n<p>I would then create a <code>Matrix_new</code> function that creates and populates an instance, e.g.</p>\n\n<pre><code>// this code assumes C99. Ignore my more compact brace style.\n\n/**\n * Allocates a new `Matrix` instance. Returns a pointer to the instance on\n * success, a `NULL` pointer on failure.\n *\n * A Matrix must always be freed via `Matrix_destroy(instance)`!\n */\n\nMatrix*\nMatrix_new(int rows, int cols) {\n\n Matrix* matrix = (Matrix*) malloc(sizeof(Matrix));\n if (matrix == NULL) {\n return NULL;\n }\n\n float** mat = (float**) malloc(rows * sizeof(float*));\n if (mat == NULL) {\n free(matrix);\n return NULL;\n }\n\n for (int i = 0; i &lt; rows; i++) {\n float* row = (float*) malloc(cols * sizeof(float));\n if (row == NULL) {\n // if a row allocation fails, we have to `free` the previous rows.\n i--;\n for (; i &gt;= 0; i--) {\n free(mat[i]);\n }\n free(mat);\n free(matrix);\n return NULL;\n }\n\n }\n\n matrix-&gt;mat = mat;\n matrix-&gt;rows = rows;\n matrix-&gt;cols = cols;\n return matrix;\n}\n</code></pre>\n\n<p>and of course, a mirroring <code>Matrix_destroy</code>:</p>\n\n<pre><code>/**\n * Safely frees a Matrix instance.\n */\n\nint\nMatrix_destroy(Matrix* matrix) {\n\n if (matrix == NULL) {\n return 0;\n }\n\n float** mat = matrix-&gt;mat;\n int rows = matrix-&gt;rows;\n\n for (int i = 0; i &lt; rows; i++) {\n free(mat[i]);\n }\n\n free(mat);\n free(matrix);\n\n return 1;\n}\n</code></pre>\n\n<p>Then, you can rewrite your other methods to take advantage of this bundling.</p>\n\n<h2>Return values</h2>\n\n<p>Very often (e.g. in <code>final_result</code>, <code>create_mat</code>, <code>feed_mat</code>), you return a pointer from your function even when that pointer was an argument to that function. It is generally preferable to return an error code, and to return values via pointers/out-arguments.</p>\n\n<p>For example, <code>final_result</code> could be changed to:</p>\n\n<pre><code>/**\n * Calculates the final result.\n *\n * Returns an error code.\n *\n * After successful execution, the `out_result` pointer will point to the \n * result, which is a `float*` of `self-&gt;rows` length. The caller owns the\n * result, and is responsible for calling `free(*out_result)`.\n *\n * Example usage:\n *\n * float *result;\n * if (! final_result(matrix, &amp;result)) {\n * // abort with error\n * }\n * // do something with `result`:\n * for (int i = 0; i &lt; matrix-&gt;rows; i++) {\n * printf(\"%f\\n\", result[i]);\n * }\n * free(result);\n */\n\nint\nfinal_result(Matrix* self, float** out_result) {\n if (self == NULL) {\n return 0;\n }\n\n float* temp = (float*) malloc(self-&gt;rows * sizeof(float));\n if (temp == NULL) {\n return 0;\n }\n\n float* result = (float*) malloc(self-&gt;rows * sizeof(float));\n if (result == NULL) {\n free(temp);\n return 0;\n }\n\n for (int i = 0; i &lt; self-&gt;rows; i++) {\n temp[i] = 0;\n result[i] = 0;\n }\n\n printf(\"Processing result...\\n\");\n\n do {\n for (int i = 0; i &lt; self-&gt;rows; i++) {\n float T = 0;\n for (int j = 0; j &lt; self-&gt;cols - 1; j++) {\n if (i != j) {\n T += self-&gt;mat[i][j] * temp[j];\n }\n }\n result[i] = (self-&gt;mat[i][self-&gt;cols - 1] - T) / self-&gt;mat[i][i];\n temp[i] = result[i];\n }\n } while (condition(result, temp, self-&gt;rows) == 0);\n\n free(temp);\n *out_result = result;\n return 1;\n}\n</code></pre>\n\n<h2>Miscellaneous Helper Functions</h2>\n\n<h3><code>memset</code></h3>\n\n<p>When zeroing all elements in some data structure, you can often use <code>memset</code> from <code>string.h</code> instead:</p>\n\n<pre><code>temp=(float*)malloc((row)*sizeof(float));//Edit: row-1 changed to row\nfor(i=0;i&lt;row;i++)\n{\n temp[i] = 0;\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>float* temp = (float*) malloc(row * sizeof(float));\nif (temp == NULL) {\n // return error code\n}\nmemset(temp, 0, row * sizeof(float));\n</code></pre>\n\n<h3><code>fabsf</code></h3>\n\n<p>If you are interested in an absolute value of a float, use the <code>fabsf</code> function from <code>math.h</code>. With it, your <code>condition</code> function simplifies to:</p>\n\n<pre><code>int\ncondition(float* result, float* temp, int row) {\n int flag = 0;\n\n for (int i = 0; i &lt; row; i++) {\n if (fabsf(temp[i] - result[i]) &lt; chk_end) {\n flag = 1;\n }\n else {\n flag = 0;\n break;\n }\n }\n\n return flag;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T03:03:49.573", "Id": "78861", "Score": "0", "body": "dude heartly thanks a highly detailed way of making my program optimized and thanks for spending time on it,, i am having one doubt on your point please just elaborate what you want to say through it i.e. /*Return values\n\nVery often (e.g. in final_result, create_mat, feed_mat), you return a pointer from your function even when that pointer was an argument to that function. It is generally preferable to return an error code, and to return values via pointers/out-arguments. */ //what do you mean by return values via pointers/out-arguments//" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:13:42.703", "Id": "78896", "Score": "0", "body": "@Amitesh I added an example rewrite of `final_result` that showcases this: The return value is a status code, whereas the result is returned via a pointer argument. In this simple case, this isn't really necessary, but quite often you'll want to return multiple values from a function: pointer arguments are the best way to do that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T15:09:54.860", "Id": "78958", "Score": "0", "body": "thanks dude got your point and will optimize my code by using your tips thanks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T20:41:08.993", "Id": "45255", "ParentId": "45237", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T16:36:34.463", "Id": "45237", "Score": "10", "Tags": [ "c", "mathematics", "matrix" ], "Title": "Gauss-Seidal implementation" }
45237