body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have strong feeling that the code below is ugly at least as there are 2 same "cons".<br> I would appreciate if you advise me ways to improve it. </p> <p>The code produces all allocation by n items from list lst. </p> <pre><code>(defun allocations (lst n) (if (= n 1) (loop for i in lst collect (cons i nil)) (loop for i in lst append (mapcar #'(lambda (l) (cons i l)) (allocations (remove i lst) (- n 1)))))) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T13:08:34.600", "Id": "31402", "Score": "1", "body": "To make sure I understood you: you are trying to do permutations based on an assumption that the elements of the list are unique non-negative integers? In that case, I'd rather use a general purpose permutation algorithm instead. Actually, complexity-wise you'd only gain from that. Also variable names like `lst` and `l` can be improved by expanding them to the full length. The first branch in the `if` is equivalent to `(mapcar #'list lst)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T13:27:53.943", "Id": "31403", "Score": "0", "body": "thanks @wvxvw! Yes, you are right. List elements are unique and non-negative integers. I will try to use general purpose permutation algorithm." } ]
[ { "body": "<pre><code>(defun allocations (source length)\n (if (= 1 length)\n (list (list (car source)))\n (loop for processed = nil then (cons (car i) processed)\n for i on source\n for todo = (cdr i)\n appending\n (loop for intermediate\n in (allocations\n (append (reverse processed) todo)\n (1- length))\n appending\n (loop for prefix = nil then (cons (car suffix) prefix)\n for suffix on intermediate\n collect (append prefix (list (car i)) suffix))))))\n</code></pre>\n\n<p>This should be a more general case of the problem (i.e. it makes no assumption of the nature of the elements in the list), but it doesn't verify that there is enough of the elements in the source list to build the required number of permutations.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T14:14:48.497", "Id": "19615", "ParentId": "19614", "Score": "2" } } ]
{ "AcceptedAnswerId": "19615", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T12:51:58.993", "Id": "19614", "Score": "3", "Tags": [ "combinatorics", "common-lisp" ], "Title": "Producing all allocations by n items from a list" }
19614
<pre><code>def get_all_friends(uid, client) friends = client.friendships.friends(uid: uid) total = friends.total_number get_friends(total, 0, uid, client) end def get_friends(total, cursor, uid, client) left = total count = [200, left].min friends = client.friendships.friends(uid: uid, count: count, cursor: cursor) left -= count next_cursor = friends.next_cursor return friends if (left == 0 || next_cursor == 0) more_firends = get_friends(left, next_cursor, uid, client) more_firends.users &lt;&lt; friends.users return more_firends end get_all_friends(uid, observer.client).users.map do |info| user = User.find_or_create_by_uid_and_name(uid: info.id, name: info.name) follow(user) user end </code></pre> <p>This code is written in a functional style. Maybe there is a more natural way to structure it with Block.</p> <p>And how can I reuse the code when <code>client.friendships.friends(uid: uid, count: count, cursor: cursor)</code> differs?</p> <hr> <p>Update:</p> <p>I reconstruct the code. It now looks more clean and general.</p> <pre><code>def get_all_friends(client, uid) fetch_all do |count, cursor| client.friendships.friends(uid: uid, count: count, cursor: cursor) end end def fetch_all(&amp;fetch_proc) res = fetch_proc.call(10, 0) total = res.total_number return res if total &lt;= 10 fetch(total, 0, &amp;fetch_proc) end def fetch(total, cursor, &amp;fetch_proc) left = total count = [200, left].min res = fetch_proc.call(count, cursor) left -= count next_cursor = res.next_cursor if (left == 0 || next_cursor == 0) return res end more_res = fetch(left, next_cursor, &amp;fetch_proc) more_res.users &lt;&lt; res.users more_res end </code></pre>
[]
[ { "body": "<p>It looks pretty good to me. Some notes: </p>\n\n<ul>\n<li>I'd avoid return on the last expression</li>\n<li>I'd avoid the \"-=\" (not very functional)</li>\n<li>I'd avoid inline returns (write a full-fledged conditional instead) </li>\n<li>I have my doubts about this <code>more_friends.users &lt;&lt;</code>, is this a side-effect you are doing behind the caller's back? </li>\n</ul>\n\n<p>As a general note, Ruby is an OOP language, you can strive for functional style (I do whenever possible), but still, use also an OOP structure or you'll end up with weird undiomatic code. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T14:11:06.277", "Id": "31429", "Score": "0", "body": "I do want the side-effect of `more_friends.users <<`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T21:52:21.147", "Id": "31436", "Score": "0", "body": "+1 re inline returns. I used to use them a lot but now I prefer an `if/else` structure." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T11:28:39.913", "Id": "19631", "ParentId": "19620", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T18:10:52.230", "Id": "19620", "Score": "1", "Tags": [ "ruby", "functional-programming", "recursion" ], "Title": "How to rewrite recursion in a more ruby way" }
19620
<p>The code above is a implementation of a lock-free queue that makes the assumption that there is exactly one Consumer thread and one Producer thread. This works as intended? The memory barriers is used in the right place? The code has race points?</p> <p>PS: I know about the existence of lock-free queue implementation in .NET 4.0+.</p> <pre><code>using System; using System.Threading; using System.Collections.Generic; using Nohros.Resources; namespace Nohros.Concurrent { /// &lt;summary&gt; /// &lt;see cref="YQueue{T}"/&gt; is an efficient queue implementation ported from /// the zeromq library. &lt;see cref="YQueue{T}"/&gt; allows one thread to use the /// &lt;see cref="Enqueue"/&gt; function while another one use the /// &lt;see cref="Dequeue(out T)"/&gt; function without locking. /// &lt;typeparam name="T"&gt; /// The type of the objects in the queue. /// &lt;/typeparam&gt; /// &lt;/summary&gt; public class YQueue&lt;T&gt; { class Chunk { public long distance; public volatile int head_pos; public volatile Chunk next; public volatile int tail_pos; public T[] values; #region .ctor /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="Chunk"/&gt; class by using /// the specified capacity. /// &lt;/summary&gt; /// &lt;param name="capacity"&gt; /// The number of elements that the chunk can hold. /// &lt;/param&gt; public Chunk(int capacity) { values = new T[capacity]; head_pos = 0; tail_pos = 0; next = null; distance = 0; } #endregion } const int kDefaultCapacity = 32; volatile Chunk divider_; readonly int granularity_; volatile Chunk tail_chunk_; #region .ctor /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="YQueue{T}"/&gt; class /// that has the default capacity. /// &lt;/summary&gt; public YQueue() : this(kDefaultCapacity) { } /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="YQueue{T}"/&gt; class /// by using the specified granularity. /// &lt;/summary&gt; /// &lt;param name="granularity"&gt; /// A number that defines the granularity of the queue(how many pushes /// have to be done till actual memory allocation is required). /// &lt;/param&gt; public YQueue(int granularity) { granularity_ = granularity; divider_ = new Chunk(granularity); // make sure that the divider will not be used to store elements. divider_.tail_pos = granularity - 1; divider_.head_pos = granularity; tail_chunk_ = divider_; } #endregion /// &lt;summary&gt; /// Adds an element to the back end of the queue. /// &lt;/summary&gt; /// &lt;param name="element"&gt; /// The element to be added to the back end of the queue. /// &lt;/param&gt; public void Enqueue(T element) { int tail_pos = tail_chunk_.tail_pos; // If either the queue is not empty or the tail chunk is not full, adds // the specified element to the back end of the current tail chunk. if (tail_chunk_ != divider_ &amp;&amp; ++tail_pos &lt; granularity_) { tail_chunk_.values[tail_pos] = element; // Prevents any kind of instruction reorderring or caching. Thread.MemoryBarrier(); // "Commit" the newly added item and "publish" it atomically // to the consumer thread. tail_chunk_.tail_pos = tail_pos; return; } // Create a new chunk if a cached one does not exists and links it // to the current last node. Chunk chunk = new Chunk(granularity_); tail_chunk_.next = chunk; // Reset the chunk and append the specified element to the first slot. chunk.tail_pos = 0; // An unconsumed element is added to the first slot. chunk.head_pos = 0; chunk.next = null; chunk.values[0] = element; chunk.distance = tail_chunk_.distance + 1; // Make sure that the new chunk is fully initialized before it is // assigned to the tail chunk. Thread.MemoryBarrier(); // At this point the newly created chunk(or the last cached chunk) is // not yet shared, but still private to the producer; the consumer will // not follow the linked chunk unless the value of |tail_chunk_| says // it may follow. The line above "commit" the update and publish it // atomically to the consumer thread. tail_chunk_ = tail_chunk_.next; } /// &lt;summary&gt; /// Removes all elements from the &lt;see cref="YQueue{T}"/&gt;. /// &lt;/summary&gt; /// &lt;remarks&gt; /// &lt;para&gt; /// &lt;see cref="Clear"/&gt; removes the elements that are not currently /// present in the queue. Elements added to the queue after /// &lt;see cref="Clear"/&gt; is called and while &lt;see cref="Clear"/&gt; is running, /// will not be cleared. /// &lt;/para&gt; /// This operation should be sychronized with the &lt;see cref="Dequeue()"/&gt; /// and &lt;see cref="Dequeue(out T)"/&gt; operations. /// &lt;/remarks&gt; public void Clear() { // Save the current tail chunk to ensure that the future elements are // not cleared. Chunk current_tail_chunk = tail_chunk_; while (divider_ != current_tail_chunk) { divider_ = divider_.next; } } /// &lt;summary&gt; /// Removes and returns the object at the beginning of the /// &lt;see cref="YQueue{T}"/&gt;. /// &lt;/summary&gt; /// &lt;returns&gt;&lt;typeparamref name="T"/&gt; The object that is removed from the /// &lt;see cref="YQueue{T}"/&gt;&lt;/returns&gt; /// &lt;exception cref="InvalidOperationException"&gt;The /// &lt;see cref="YQueue{T}"/&gt; is empty.&lt;/exception&gt; public T Dequeue() { T t; bool ok = Dequeue(out t); if (!ok) { throw new InvalidOperationException( StringResources.InvalidOperation_EmptyQueue); } return t; } /// &lt;summary&gt; /// Removes and returns the object at the beginning of the /// &lt;see cref="YQueue&amp;lt;T&amp;gt;"/&gt;. /// &lt;/summary&gt; /// &lt;param name="t"&gt;When this method returns, contains the object that was /// removed from the beginning of the &lt;see cref="YQueue&amp;lt;T&amp;gt;"/&gt;, if /// the object was successfully removed; otherwise the default value /// of the type &lt;typeparamref name="T"/&gt;.&lt;/param&gt; /// &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if the queue is not empty and the object at the /// beginning of it was successfully removed; otherwise, false. /// &lt;/returns&gt; public bool Dequeue(out T t) { // checks if the queue is empty while (divider_ != tail_chunk_) { // The chunks that sits between the |divider_| and the |tail_chunk_|, // excluding the |divider_| and including the |tail_chunk_|, are // unconsumed. Chunk current_chunk = divider_.next; // We need to compare the current chunk |tail_pos| with the |head_pos| // and |granularity|. Since, the |tail_pos| can be modified by the // producer thread we need to cache it instantaneous value. int tail_pos; tail_pos = current_chunk.tail_pos; if (current_chunk.head_pos &gt; tail_pos) { if (tail_pos == granularity_ - 1) { // we have reached the end of the chunk, go to the next chunk and // frees the unused chunk. divider_ = current_chunk; //head_chunk_ = head_chunk_.next; } else { // we already consume all the available itens. t = default(T); return false; } } else { // Ensure that we are reading the freshness value from the chunk // values array. Thread.MemoryBarrier(); // Here the |head_pos| is less than or equals to |tail_pos|, get // the first unconsumed element and increments |head_pos| to publish // the queue item removal. t = current_chunk.values[current_chunk.head_pos]; // keep the order between assignment and publish operations. Thread.MemoryBarrier(); current_chunk.head_pos++; return true; } } t = default(T); return false; } /// &lt;summary&gt; /// Gets a value indicating whether the &lt;see cref="YQueue{T}"/&gt; is empty. /// &lt;/summary&gt; /// &lt;remarks&gt; /// Since this collection is intended to be accessed concurrently by two /// threads in a producer/consumer pattern, it may be the case that another /// thread will modify the collection after &lt;see cref="IsEmpty"/&gt; returns, /// thus invalidatind the result. /// &lt;/remarks&gt; public bool IsEmpty { get { Chunk divider = divider_; Chunk tail = tail_chunk_; return (divider.next == tail || divider == tail) &amp;&amp; tail.head_pos &gt; tail.tail_pos; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T12:17:32.300", "Id": "31751", "Score": "0", "body": "Could you link to the original that your ported this from?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-25T18:21:27.593", "Id": "104088", "Score": "0", "body": "It is based on the following code \"https://github.com/zeromq/libzmq/blob/master/src/yqueue.hpp\"" } ]
[ { "body": "<ol>\n<li><p>I've never see a naming convention that would use <code>_</code> <em>suffix</em> for private fields in C#. The most often used conventions use <code>m_</code>, <code>_</code> as a prefix, or nothing at all.</p>\n\n<p>Similarly, the <code>k</code> prefix is not usual for constants in C#.</p>\n\n<p>Also, using <code>underscore_names</code> is not usual in C#.</p></li>\n<li><p>It's usually better if an expression is used for its value <em>or</em> its side-effects, but not both. So, you should avoid using <code>++</code> inside an <code>if</code> expression.</p></li>\n<li><p>I don't see any reason why you would want to set the fields of a new <code>Chunk</code> twice to the same values. Especially since <code>0</code> and <code>null</code> are the default values anyway.</p></li>\n<li><p>The comments about “cached chunks” are confusing, since you don't seem to cache chunks at all.</p></li>\n<li><p>I don't understand the existence of <code>divider_</code>. Why do you need an empty chunk at the start of the list? Considering that everything else is commented extensively, this seems like a weird oversight.</p></li>\n<li><p>What is the reason for the <code>distance</code> field? You don't seem to use it anywhere.</p></li>\n<li><p><code>Clear()</code> can easily clear items that were added while it was executing, if they were added to the last chunk (and not a new one). You can see this by adding <code>Thread.Sleep(1)</code> before the <code>while</code> and enqueueing some items while calling <code>Clear()</code> on another thread. (You should also add some logging for this, so you can see the order of events.)</p></li>\n<li><p><code>t</code> is not a very good variable name. Something like <code>result</code> would be much better.</p></li>\n<li><p>I'm not sure <code>while</code> is necessary in <code>Dequeue()</code> since it will always have at most two iterations. I think getting rid of the <code>while</code> would make your code easier to understand.</p></li>\n</ol>\n\n<p>Otherwise, I didn't find any threading issues, but that doesn't mean there aren't any. Lock-free programming can be very tricky.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T08:12:43.173", "Id": "31789", "Score": "0", "body": "Agree with all points, I didn't find threading issues here as well. Just to add that thread safety in this code heavily relies on the fact of single consumer and producer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T12:10:04.647", "Id": "32144", "Score": "0", "body": "The divider exists to ensure that producer and consumer is not using the same node at the same time; otherwise read/write operations on head and tail should be synchronized." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T12:12:17.293", "Id": "32145", "Score": "0", "body": "The while is necessary because the divider should be advanced to the next chunk if all the slots of the current chunk is already consumed." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T13:02:32.737", "Id": "19869", "ParentId": "19625", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T21:08:50.663", "Id": "19625", "Score": "2", "Tags": [ "c#", "multithreading", "thread-safety", "lock-free" ], "Title": "Publisher/Consumer thread-safe lock-free queue with a single publisher/consumer" }
19625
<p>I have a GiftCard class where I have method can_deliver? and deliver! that I think can be refactored to better looking code :</p> <pre><code> def can_deliver? (self.sent_at.nil? &amp;&amp; self.scheduled_at.nil?) || (self.sent_at.nil? &amp;&amp; self.scheduled_at &amp;&amp; self.scheduled_at &lt; Time.now) end def deliver! return unless self.can_deliver? begin Notifier.gift_card_code_mail(self).deliver self.sent_at = Time.now self.save rescue Exception logger.error "Could not send email gift card ##{self.id}" self.line_item.order.comments.create!(:content =&gt; "Can not send gift card mail") end begin Notifier.gift_card_delivered(self).deliver rescue Exception logger.error "Could not send deliver confirmation email gift card #{self.id}" self.line_item.order.comments.create!(:content =&gt; "Can not send confirmation delivery of gift card") end end </code></pre>
[]
[ { "body": "<p>Some notes:</p>\n\n<ul>\n<li><p><code>self</code>: You write <code>self.attribute</code> to access attributes. I won't say that's bad practice, not at all, mainly because it's easier to see if you're accessing local variables or instance methods. However, in Ruby it's idiomatic not to use <code>self</code> in this case.</p></li>\n<li><p><code>variable.nil?</code>: this is something we often see but 99% of the time is unnecessary verbose. You want to know if a variable is not set? write <code>!variable</code>. The only case a explicit <code>nil?</code> is needed is when you want to tell <code>false</code> from <code>nil</code>, not the case here.</p></li>\n<li><p>Layout: Don't write long lines, 80/100 is a sound limit. It usually pays off in form of clarity also: in <code>can_deliver?</code> for example, if you break on the <code>||</code> operator the boolean expression is much more clear.</p></li>\n<li><p>Early returns: <code>return unless self.can_deliver?</code>. Again, I won't say that's bad, in a language that has no syntax for guards (like other languages have), it's a handy way to do early returns when pre-conditions are not met. As a rule of thumb, however, I'd recommend to write a full conditional. Yeah, I know, it's more verbose and you get an extra indentation level, but on the other hand the layout of the function/method helps understanding what the method it's doing. </p></li>\n<li><p>The cool thing about the way you wrote <code>can_deliver?</code> (using an expression instead of a bunch of imperative returns) is that you can apply boolean algebra. Notice here than <code>(!p &amp;&amp; !q) || (!p &amp;&amp; q &amp;&amp; q &lt; t)</code> -> <code>!p &amp;&amp; (!q || q &lt; t)</code>. Of course this kind of simplifications must only be done when the resulting expression is at least as declarative as the original (we are not trying to save some NAND gates here). If you read it out loud and it makes sense then it's ok.</p></li>\n<li><p>You have two (and probably more throughout the code) almost identical <code>begin</code>/<code>rescue</code> blocks. That's a call for abstraction (it this case an abstraction using block wrappers).</p></li>\n<li><p>Don't write <code>rescue Exception</code>, that's a common pitfall. Check <a href=\"https://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby\">this SO question</a>.</p></li>\n<li><p>Shouldn't <code>deliver!</code> return something? how would the caller know if it was successful? you should always return something, either a value (a boolean seems fit in this case) or, yes, return <code>nil</code> but raise an exception on error. Personally I like to return values and leave exceptions for really exceptional things (like, I don't know, the hard disk exploded).</p></li>\n</ul>\n\n<p>Applying all these points, and with a declarative approach in mind, I'd write:</p>\n\n<pre><code>class GiftCard\n def can_deliver?\n !sent_at &amp;&amp; (!scheduled_at || scheduled_at &lt; Time.now)\n end\n\n def deliver!\n can_deliver? &amp;&amp; send_card_code_email &amp;&amp; send_gift_card_email\n end\n\nprivate\n\n def comment_on_exception(msg) \n yield\n rescue =&gt; exc\n logger.error(msg)\n line_item.order.comments.create!(:content =&gt; msg)\n false\n end\n\n def send_card_code_email\n comment_on_exception(\"Could not send email gift card #{id}\") do\n Notifier.gift_card_code_mail(self).deliver\n update_attribute(:sent_at, Time.now)\n end\n end\n\n def send_gift_card_email\n comment_on_exception(\"Could not send deliver confirmation email gift card\") do\n Notifier.gift_card_delivered(self).deliver\n end\n end\nend\n</code></pre>\n\n<p>If you found some of these advices useful, take a look at the <a href=\"https://code.google.com/p/tokland/wiki/RubyIdioms\" rel=\"nofollow noreferrer\">RubyIdioms</a> page I maintain (and its <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow noreferrer\">RubyFunctionalProgramming</a> companion). Comments most welcome.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T11:03:33.413", "Id": "19630", "ParentId": "19626", "Score": "3" } } ]
{ "AcceptedAnswerId": "19630", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T22:48:40.517", "Id": "19626", "Score": "1", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Refactor or simple code RoR" }
19626
<p>Pythonic way of expressing the simple problem:</p> <blockquote> <p>Tell if the list <code>needle</code> is sublist of <code>haystack</code></p> </blockquote> <hr> <pre><code>#!/usr/bin/env python3 def sublist (haystack, needle): def start (): i = iter(needle) return next(i), i try: n0, i = start() for h in haystack: if h == n0: n0 = next(i) else: n0, i = start() except StopIteration: return True return False </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T03:27:04.163", "Id": "31422", "Score": "0", "body": "So, what's the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T12:30:16.977", "Id": "31427", "Score": "0", "body": "@JeffVanzella: Fair point. That's \"code review\". The question is: \"what do you think in general?\"." } ]
[ { "body": "<h3>1. Bug</h3>\n\n<p>Here's a case where your function fails:</p>\n\n<pre><code>&gt;&gt;&gt; sublist([1, 1, 2], [1, 2])\nFalse\n</code></pre>\n\n<p>this is because in the <code>else:</code> case you go back to the beginning of the needle, but you keep going forward in the haystack, possibly skipping over a match. In the test case, your function tries matching with the alignment shown below, which fails at the position marked <code>X</code>:</p>\n\n<pre><code> X\nhaystack 1,1,2\nneedle 1,2\n</code></pre>\n\n<p>Then it starts over from the beginning of the needle, but keeps going forward in the haystack, thus missing the match:</p>\n\n<pre><code> X\nhaystack 1,1,2\nneedle 1,2\n</code></pre>\n\n<p>So after a mismatch you need to go <em>backward</em> an appropriate distance in the haystack before starting over again from the beginning of the needle.</p>\n\n<h3>2. A better algorithm</h3>\n\n<p>It turns out to be better to start matching from the <em>end</em> of the needle. If this fails to match, we can skip forward several steps: possibly the whole length of the needle. For example, in this situation:</p>\n\n<pre><code> X\nhaystack 1,2,3,4,6,1,2,3,4,5\nneedle 1,2,3,4,5\n</code></pre>\n\n<p>we can skip forward by the whole length of the needle (because <code>6</code> does not appear in the needle). The next alignment we need to try is this:</p>\n\n<pre><code> O O O O O\nhaystack 1,2,3,4,6,1,2,3,4,5\nneedle 1,2,3,4,5\n</code></pre>\n\n<p>However, we can't always skip forward the whole length of the needle. The distance we can skip depends on the item that fails to match. In this situation:</p>\n\n<pre><code> X\nhaystack 1,2,3,4,1,2,3,4,5\nneedle 1,2,3,4,5\n</code></pre>\n\n<p>we should skip forward by 4, to bring the <code>1</code>s into alignment.</p>\n\n<p>Making these ideas precise leads to the <a href=\"http://en.wikipedia.org/wiki/Boyer-Moore-Horspool_algorithm\" rel=\"nofollow\">Boyer–Moore–Horspool</a> algorithm:</p>\n\n<pre><code>def find(haystack, needle):\n \"\"\"Return the index at which the sequence needle appears in the\n sequence haystack, or -1 if it is not found, using the Boyer-\n Moore-Horspool algorithm. The elements of needle and haystack must\n be hashable.\n\n &gt;&gt;&gt; find([1, 1, 2], [1, 2])\n 1\n\n \"\"\"\n h = len(haystack)\n n = len(needle)\n skip = {needle[i]: n - i - 1 for i in range(n - 1)}\n i = n - 1\n while i &lt; h:\n for j in range(n):\n if haystack[i - j] != needle[-j - 1]:\n i += skip.get(haystack[i], n)\n break\n else:\n return i - n + 1\n return -1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T02:11:56.267", "Id": "31416", "Score": "0", "body": "@Lattyware: Generally I'd agree that you should use iterators wherever it makes sense, but this is one of the exceptional cases where iterators don't make much sense. A pure-iterator search runs in O(*nm*) whereas Boyer–Moore-Horspool is O(*n*). (In the average case on random text.) Sometimes you just have to get your hands grubby." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T02:29:05.937", "Id": "31420", "Score": "0", "body": "Scratch all my arguments, it's impossible to do this correctly the way I was doing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T12:38:21.643", "Id": "31428", "Score": "0", "body": "Accepted. The source is strong with this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T03:14:56.147", "Id": "70305", "Score": "0", "body": "Does the dict comprehension overwrite previous values? If not you'll skip too far when you see `e` while searching for `seven`. I'd bet it does but am not sure. I do miss Python for its elegance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T10:17:39.237", "Id": "70369", "Score": "0", "body": "Yes, later items in the dict comprehension override previous items, and so `find('seven', 'even')` → `1` as required." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T02:00:44.667", "Id": "19629", "ParentId": "19627", "Score": "5" } } ]
{ "AcceptedAnswerId": "19629", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T22:54:25.417", "Id": "19627", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Finding sub-list" }
19627
<p>I've written the following program as a submission to the German Federal Computer Science Competition for highschool students. The program makes the following simulation with a given number of days and a given <em>α</em>. In order to simplify my code, I use a shellscript to run multiple simulations in parallel. You can get all of the code from <a href="https://github.com/fuzxxl/bwinf2012" rel="nofollow">GitHub</a>: (in directory 5).</p> <p>I know that my implement correctly the fact that the happiness is calculated <em>once a day</em>. I calculate it just when needed.</p> <h2>Question</h2> <p>(Translated from German, see <a href="http://www.bundeswettbewerb-informatik.de/fileadmin/templates/bwinf/aufgaben/bwinf31/Aufgabenblatt311_simple.pdf" rel="nofollow">source</a>)</p> <blockquote> <p>The CEO of Nash Ltd. wants to see her workers happy. Thus, she likes to provide them with free coffee. [...] After a period of ten days where the CEO's assistant makes coffee, the workers have to make coffee on their own. Every evening, the remaining coffee is poured away.</p> <p>The carafe can contain up to ten cups of coffee, there are 15 workers. Each worker likes to drink three cups a day, one in the morning (8 to 10 AM), one at noon (12 to 2 PM) and one in the afternoon (3 to 5 PM). I each of these timeslots the workers arrive in a random order and behave like this:</p> <p>If there is coffee left in the carafe they pour one cup and leave. If the carafe is empty, the behavior depends on whether they are happy or not. If they are, they brew a new carafe and take one cup. If not, the leave in anger without drinking any coffee.</p> <p>Whether a worker is happy on a certain day is decided right after they get up. It depends on how often they drank coffee in the last ten days and on how often they brew coffee in that time. The exact definition reads:</p> <p>If a person drank <em>n</em> cups in the last ten days and brew coffee for <em>m</em> times, he or she is happy iff <em>n</em> >= 10 and <em>m/n</em> &lt; <em>α</em>; <em>α</em> is a personal threshold.</p> <p>Write a program that simulates the worker where <em>α</em> is equal for all of them. How many cups of coffee is a worker drinking on the long-term average every day depending on <em>α</em>?</p> </blockquote> <h2>stats.c</h2> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdint.h&gt; #define STAT_DAYS 10 /* days in statistical window */ #define INTRO_DAYS 10 /* Amount of days the assistant refills the can */ #define WORKER_COUNT 15 /* number of worker in the company */ #define CAN_CAPACITY 10 /* Cups per can */ #define SERVINGS 3 /* Coffee servings per worker per day */ /* data for one worker */ typedef struct { int cups; int cans; } worker_t[STAT_DAYS]; /* data for the whole company at a given point */ typedef struct { double threshold; int day_number; int total_cups; /* total number of cups drunk by the workers */ int can_state; worker_t workers[WORKER_COUNT]; } company_t; /* xorshift random number generator for random number generation with good * statistical properties. See http://en.wikipedia.org/wiki/Xorshift */ static uint32_t xor_state[4], xor_now; static int xor_entropy = 0; static uint32_t xor128(int bits) { uint32_t t; /* use remaining entropy if possible */ if (xor_entropy &lt; bits) { xor_entropy = 32; t = xor_state[0] ^ (xor_state[1] &lt;&lt; 11); xor_state[0] = xor_state[1]; xor_state[1] = xor_state[2]; xor_state[2] = xor_state[3]; xor_state[3] ^= (xor_state[3] &gt;&gt; 19) ^ (t ^ ( t &gt;&gt; 8)); xor_now = xor_state[3]; } xor_entropy -= bits; t = xor_now &amp; ((1&lt;&lt;bits)-1); xor_now &gt;&gt;= bits; return t; } /* initialize the random number generator. Return 0 on success. */ static uint32_t init_xor128(void) { FILE *entropy = fopen("/dev/urandom","rb"); size_t items_read; if (entropy == NULL) { perror("Can't open /dev/random"); return 1; } setbuf(entropy,NULL); /* We don't need any buffering */ items_read = fread(xor_state,sizeof xor_state[0],4,entropy); fclose(entropy); if (items_read != 4) { fprintf(stderr,"Can't initialize rng.\n"); return 1; } return 0; } /* number of bits used by i. __builtin_clz is an intrisic available on gcc * and clang. */ static int bits(uint32_t i) { return 32 - __builtin_clz(i); } /* Generate a permuted array of pointers to members of an array of workers. * Algorithm taken from http://en.wikipedia.org/wiki/Fisher–Yates_shuffle */ static void shuffle_array(int out[WORKER_COUNT]) { int i,j; out[0] = 0; for (i = 1; i &lt; WORKER_COUNT; i++) { /* get random numbers till you get one in range */ while (j = xor128(bits(i)), j &gt; i); out[i] = out[j]; out[j] = i; } } /* Is a worker happy? */ static bool happy(worker_t *worker,double threshold) { int i; int cup_count = 0, can_count = 0; /* get amount of cups drunk, cans brewed */ for (i = 0; i &lt; STAT_DAYS; i++) cup_count += (*worker)[i].cups; for (i = 0; i &lt; STAT_DAYS; i++) can_count += (*worker)[i].cans; /* I interprete n &gt;= 10 as "n &gt;= sliding window" */ return cup_count &gt;= STAT_DAYS &amp;&amp; 1.0L*can_count/cup_count &lt; threshold; } /* simulate one round of coffee for all workers */ static void coffee_round(company_t *company) { int order[WORKER_COUNT]; int i, day_mod = company-&gt;day_number % STAT_DAYS; shuffle_array(order); for (i = 0; i &lt; WORKER_COUNT; i++) { int j = order[i]; if (!company-&gt;can_state &amp;&amp; company-&gt;day_number &gt;= INTRO_DAYS) { if (!happy(&amp;company-&gt;workers[j],company-&gt;threshold)) continue; company-&gt;can_state = CAN_CAPACITY - 1; company-&gt;workers[j][day_mod].cans++; } company-&gt;can_state--; company-&gt;workers[j][day_mod].cups++; company-&gt;total_cups++; } } /* simulate one day of coffee */ static void day(company_t *company) { /* day_mod: index into the statistical tables */ int i, day_mod = company-&gt;day_number % STAT_DAYS; /* zero out statistics entry for today */ for (i = 0;i &lt; WORKER_COUNT; i++) { company-&gt;workers[i][day_mod].cups = 0; company-&gt;workers[i][day_mod].cans = 0; } company-&gt;can_state = 0; /* empty can */ for (i = 0;i &lt; SERVINGS; i++) coffee_round(company); company-&gt;day_number++; /* A day has passed */ } /* Main function */ int main(int argc,char **argv) { company_t *company; int day_count; if (argc != 3) { fprintf(stderr,"Usage: %s days threshold\n",argv[0]); return EXIT_FAILURE; } /* allocate and set to zero */ company = calloc(sizeof *company,1); if (!sscanf(argv[1],"%d",&amp;day_count) || day_count &lt;= 0) { fprintf(stderr,"%s is not a valid number of days.\n",argv[1]); return EXIT_FAILURE; } if (!sscanf(argv[2],"%lf",&amp;company-&gt;threshold)) { fprintf(stderr,"%s is not a valid threshold.\n",argv[2]); return EXIT_FAILURE; } if (init_xor128()) return EXIT_FAILURE; while (company-&gt;day_number &lt; day_count) day(company); /* print output */ printf("%.6lf\t%.6lf\n", company-&gt;threshold, ((double)company-&gt;total_cups/day_count)/WORKER_COUNT); free(company); return EXIT_SUCCESS; } </code></pre> <h2>stats.sh</h2> <pre><code>#!/bin/bash #shell script for statistics creation. This shell script generates a table of #statistics for a lot of happiness thresholds and saves them into happiness.csv #various parameters STATFILE=stats.tsv SIM=./stats JOBS=$(grep -ic ^processor /proc/cpuinfo) #number of processors available #search space START=0.0 STEP=0.0016 END=0.5 DAYS=$((1024*1024)) LC_NUMERIC=C #set numeric locale to C in order to get correct separators LC_COLLATE=C #set collating sequence to C in order to sort correctly #calculate results in parallel seq $START $STEP $END | xargs -n 1 -P $JOBS $SIM $DAYS &gt;$STATFILE sort -o $STATFILE $STATFILE #sort output as it might be unordered </code></pre> <h2>Makefile</h2> <pre><code>CFLAGS ?= -O3 -Wall XELATEX ?= xelatex GNUPLOT ?= gnuplot PYGMENTIZE ?= pygmentize PYGMENTIZE_STYLE ?= borland PYGMENTIZE_OPTS ?= -O linenos 5.pdf: 5.tex plot.tex stats.tex definitions.tex $(RM) *.aux $(XELATEX) -halt-on-error $&lt; &gt;/dev/null $(XELATEX) -halt-on-error $&lt; &gt;/dev/null definitions.tex: $(PYGMENTIZE) -f tex -S $(PYGMENTIZE_STYLE) &gt; $@ .c.tex: $(PYGMENTIZE) $(PYGMENTIZE_OPTS) -o $@ $&lt; plot.tex: stats.gp stats.tsv $(GNUPLOT) $&lt; stats.tsv: stats ./stats.sh clean: $(RM) *.pdf *.aux *.log definitions.tex stats.tex plot.tex *.tsv stats *.eps .PHONY: clean </code></pre>
[]
[ { "body": "<p>Overall, this is very clean and I have only a few small improvements.</p>\n\n<p>1) In <code>happy</code>:</p>\n\n<pre><code>/* get amount of cups drunk, cans brewed */\nfor (i = 0; i &lt; STAT_DAYS; i++) cup_count += (*worker)[i].cups;\nfor (i = 0; i &lt; STAT_DAYS; i++) can_count += (*worker)[i].cans;\n</code></pre>\n\n<p>could be a single for loop.</p>\n\n<p>2) In <code>day</code> (by the way, this should probably be <code>simulate_day</code> or something):</p>\n\n<pre><code>for (i = 0;i &lt; WORKER_COUNT; i++) {\n company-&gt;workers[i][day_mod].cups = 0;\n company-&gt;workers[i][day_mod].cans = 0;\n}\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>for (i = 0; i &lt; WORKER_COUNT; i++) {\n company-&gt;workers[i][day_mod] = {\n .cups = 0,\n .cans = 0;\n }\n}\n</code></pre>\n\n<p>3) In <code>main</code>, you calloc and free a variable; why not just allocate it on the stack?</p>\n\n<p>4) Comments like</p>\n\n<pre><code>/* Main function */\nint main(int argc,char **argv) {\n\n/* allocate and set to zero */\ncompany = calloc(sizeof *company,1);\n\n/* print output */\nprintf(\"%.6lf\\t%.6lf\\n\",\n</code></pre>\n\n<p>describe <em>what</em> the code is doing, not <a href=\"http://www.codinghorror.com/blog/2006/12/code-tells-you-how-comments-tell-you-why.html\"><em>why</em></a> it's doing it.</p>\n\n<p>5) There are a few small style inconsistencies (especially with regards to spaces after commas and semicolons). Consider using <a href=\"http://astyle.sourceforge.net/\">astyle</a> and writing an <code>.astylerc</code> file for yourself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T10:13:05.873", "Id": "31871", "Score": "1", "body": "Thank you really much for the feedback! I allocated the structure on the heap as it might be bigger than a few hundred bytes. People always suggest that one should allocate on the heap everything that is not really small." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T13:12:35.910", "Id": "31920", "Score": "0", "body": "Oh. I suppose if `WORKER_COUNT` goes up, that makes sense." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T00:12:07.030", "Id": "19934", "ParentId": "19633", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T13:18:53.580", "Id": "19633", "Score": "6", "Tags": [ "c", "bash", "simulation", "statistics" ], "Title": "Statistical simulation" }
19633
<pre><code>function C = convolve_slow(A,B) (file name is accordingly convolve_slow.m ) This routine performs convolution between an image A and a mask B. Input: A - a grayscale image (values in [0,255]) B - a grayscale image (values in [0,255]) serves as a mask in the convolution. Output: C - a grayscale image (values in [0,255]) - the output of the convolution. C is the same size as A. Method: Convolve A with mask B using zero padding. Assume the origin of B is at floor(size(B)/2)+1. Do NOT use matlab convolution routines (conv,conv2,filter2 etc). Make the routine as efficient as possible: Restrict usage of for loops which are expensive (use matrix multiplications and matlab routines such as dot etc). &lt;br&gt; To simplify and reduce ifs, you should pad the image with zeros before starting your convolution loop. Do not assume the size of A nor B (B might actually be larger than A sometimes). </code></pre> <p>here is my solution for this exercise. please elaborate on any change you have done or suggesting since i'm new to matlab and image processing.</p> <pre><code>function [ C ] = convolve_slow( A,B )&lt;br&gt; %This routine performs convolution between an image A and a mask B. % % Input: A - a grayscale image (values in [0,255]) % B - a grayscale image (values in [0,255]) serves as a mask in the convolution. % Output: C - a grayscale image (values in [0,255]) - the output of the convolution. % C is the same size as A. % % Method: Convolve A with mask B using zero padding. Assume the origin of B is at floor(size(B)/2)+1. % init C to size A with zeros C = zeros(size(A)); % make b xy-reflection and vector vectB = reshape(flipdim(flipdim(B,1),2)' ,[] , 1); % padding A with zeros paddedA = padarray(A, [floor(size(B,1)/2) floor(size(B,2)/2)]); % Loop over A matrix: for i = 1:size(A,1) for j = 1:size(A,2) startAi = i; finishAi = i + size(B,1) - 1; startAj = j; finishAj = j + size(B,2) - 1; vectPaddedA = reshape(paddedA(startAi :finishAi,startAj:finishAj)',1,[]); C(i,j) = vectPaddedA* vectB; end end end </code></pre>
[]
[ { "body": "<p>Rather than making four variables just to index the matrix, I would go for two in such a way:</p>\n\n<pre><code>paddedA(i :i_end,j:j_end)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T15:39:38.200", "Id": "19898", "ParentId": "19634", "Score": "2" } } ]
{ "AcceptedAnswerId": "19898", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T13:43:28.147", "Id": "19634", "Score": "3", "Tags": [ "matlab" ], "Title": "2D convolution in matlab" }
19634
<ul> <li>Purpose: Educational</li> <li>Requirement: Given 64KB of memory, implement your own <code>malloc</code> and <code>free</code></li> <li>Method: <a href="http://www.memorymanagement.org/articles/alloc.html#first.fit" rel="nofollow">First-Fit</a></li> </ul> <p></p> <pre><code>struct Header { unsigned short next; //in blocks of sizeof(Header) unsigned short size; //in blocks of sizeof(Header) }; static Header* _dBuffer; static Header* _dTail; static public void dInit() { _dBuffer = getMemBlock(64 * 1024); _dTail = _dBuffer; } static public void* dMalloc(unsigned short nbytes) { if (_dTail == NULL) //empty free list return NULL; Header* prev = NULL; Header* current = _dTail; // below is equivalent to ceil((nbytes + sizeof(Header)) / sizeof(Header)) int nblocks = (nbytes + sizeof(Header) - 1) / sizeof(Header) + 1; while (current-&gt;next != 0 &amp;&amp; current-&gt;size &lt; nblocks) { prev = current; current = _dBuffer + current-&gt;next; } if (current-&gt;size &lt; nblocks) //we've reached the end of the free list without finding a chunk big enough return NULL; if (current-&gt;size == nblocks) { //we've found an exact match, remove the chunk from the free list if (prev == NULL) //remove the first chunk _dTail = NULL; else prev-&gt;next = current-&gt;next; return current + 1; } //current-&gt;size &gt; nblocks current-&gt;size -= nblocks; current+= current-&gt;size; current-&gt;size = nblocks; return current + 1; } static bool coalesce(Header* block) { Header* nextBlock = _dBuffer + block-&gt;next; if (block + block-&gt;size != nextBlock) return false; block-&gt;size += nextBlock-&gt;size; block-&gt;next = nextBlock-&gt;next; return true; } static public void dFree(void* p) { Header* released = (Header*)p - 1; Header* before = NULL; Header* after = _dTail; if (_dTail == NULL) //the free list is empty { released-&gt;next = 0; _dTail = released; return; } //find where released is located in the free list while (after-&gt;next != 0 &amp;&amp; after &lt; released) { before = after; after = _dBuffer + after-&gt;next; } if (after &lt; released) //released chunk after the end of the free list { released-&gt;next = 0; after-&gt;next = released - _dBuffer; coalesce(after); return; } if (before == NULL) //released chunk before the beginning of the free list { released-&gt;next = _dTail - _dBuffer; _dTail = released; coalesce(released); return; } //released chunk is somewhere in the middle of the list released-&gt;next = before-&gt;next; before-&gt;next = released - _dBuffer; if (coalesce(before)) //before was coalesced with released coalesce(before); //now try to coalesce it with after else coalesce(released); //otherwise, try coalescing released with after } </code></pre>
[]
[ { "body": "<p>I think this is a bug:</p>\n\n<pre><code>if (current-&gt;size == nblocks) \n{\n //we've found an exact match, remove the chunk from the free list\n if (prev == NULL) //remove the first chunk\n _dTail = NULL;\n ^^^^^^^^^^^^^^^\n You are just removing the head of the list\n Not NULL(ing) the list.\n I think the line should be:\n\n _dTail = current-&gt;next;\n\n else\n prev-&gt;next = current-&gt;next;\n return current + 1;\n}\n</code></pre>\n\n<p>The only thing I don't like is:</p>\n\n<pre><code>unsigned short next; //in blocks of sizeof(Header)\n</code></pre>\n\n<p>This because you have to keep doing maths to covert it to/from a pointer. I think your code would become much simpler if you just convert this too:</p>\n\n<pre><code>Header* next; // next block in list\n</code></pre>\n\n<p>I would also remove the assert:</p>\n\n<pre><code>assert(nbytes % sizeof(Header) == 0);\n</code></pre>\n\n<p>and replace it with code to move the size up.</p>\n\n<pre><code>if (nbytes % sizeof(Header) != 0)\n{\n nbytes += (sizeof(Header) - (nbytes % sizeof(Header)));\n}\n</code></pre>\n\n<p>I think you can simplify your code by quite a bit by using sentinel values on your list. See <a href=\"https://codereview.stackexchange.com/a/13087/507\">this answer about lists</a> read the bit about sentinals and how it makes things easier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T18:21:42.053", "Id": "31434", "Score": "0", "body": "I don't like the `unsigned short next` either, but this way I can have a Header of size 4 (rather than 6 or 10 depending on x86/x64). I totally agree that if I were handling a general amount of memory (as opposed to 64KB) a pointer would have made life much easier (I could also use it to store NULL)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T18:29:54.003", "Id": "31435", "Score": "0", "body": "Also your bug report is spot on - though I believe the correct line would be `_dTail = (_dTail->next == 0) ? NULL : _dBuffer + _dTail->next`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T17:45:55.493", "Id": "19636", "ParentId": "19635", "Score": "7" } }, { "body": "<p>A few minor comments</p>\n\n<ul>\n<li><p>I don't like the use of a leading underscore on variable names (reserved for system use I think)</p></li>\n<li><p>I would add a little function to calculate the number of blocks instead of doing it twice (in <code>getMemBlock</code> and <code>dMalloc</code>). eg</p>\n\n<pre><code>static inline size_t nBlocks(size_t nbytes)\n{\n return (nbytes + sizeof(Header) - 1) / sizeof(Header);\n}\n</code></pre></li>\n<li><p>There are many implicit conversion and sign conversions warnings resulting from your mixing of signed and unsigned variables. These can often cause subtle problems.</p></li>\n<li><p>There are also various precision loss warnings resulting from the use of short integers in the header. </p></li>\n<li><p><code>dInit</code> needs a parameter list <code>(void)</code>. Perhaps better to pass in the size. Also needs to return success/failure.</p></li>\n<li><p>You have no record of the allocated area and no way of checking for validity in <code>dFree</code>. So I can do:</p>\n\n<pre><code>int main(int argc, char **argv)\n{\n void *mem;\n dFree(mem);\n ...\n</code></pre>\n\n<p>and it will work, adding some random location to the pool.</p></li>\n<li><p>Also, I can call <code>dFree</code> without calling <code>dInit</code> and it will not fail.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T14:39:52.730", "Id": "31565", "Score": "0", "body": "Thanks so much for the input ! *leading underscores* I'm used to it from C# but you may be right about using them in C/C++. *nBlocks* good idea *warnings* I don't recall seeing any warning but I'll chcek again. *dInit* the assumption is that we're given 64KB, otherwise using short fields in the header won't work anyway. *validity* I agree about calling to dFree without calling dInit, but the only way I could check for validity would be statistical (insert some magic word in the header that may appear in the user data anyway). I had max space efficiency in mind but it's a possible tradeoff." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T18:53:02.037", "Id": "31582", "Score": "0", "body": "For warnings, it depends upon your compiler and which warnings you have enabled. To check validity, I imagined you could keep a pinter to the base and limit of the allocated memory and check the dFree parameter lies between the two." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T19:04:32.927", "Id": "31583", "Score": "0", "body": "Thanks, I've increased the warning level and I do see some warnings like you predicted, I'll check them out. Regarding validity, I agree this range check would be useful. A user would still be able to mess things up by calling `dFree` on an address inside the range not returned by `dMalloc`, but why not make that extra check when it's possible. Thanks again!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T13:35:53.463", "Id": "19736", "ParentId": "19635", "Score": "3" } } ]
{ "AcceptedAnswerId": "19636", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T16:03:43.813", "Id": "19635", "Score": "7", "Tags": [ "c", "memory-management" ], "Title": "malloc / free implementation" }
19635
<p>This is a piece of C89 code testing a function titled <code>logging_function()</code>, which takes two arguments and uses them to log a bit of information. </p> <p>In this case, the first argument to the function is the string to be logged, and the second argument is a string holding a path in a filesystem to a log file. The first string is printed, with a timestamp, to stdout and the log file.</p> <p><strong>Note:</strong> although yes input on the <code>main()</code> function would be wonderful, I'd love it if you gave thoughts on the function <code>logging_function()</code> itself.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &lt;string.h&gt; #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 typedef struct tm tm; int logging_function(char input_string[], char log_file_string[]) { /*Initializations.*/ char output_string[32767]; FILE* log_file_stream; time_t current_time_epoch_format; tm* current_time_calandar_format; /*Creating timestamp in output string, amending first argument to output string, and logging.*/ if ((strlen(input_string) + 23) &gt; 32767) return EXIT_FAILURE; if ((current_time_epoch_format = time(&amp;current_time_epoch_format)) == -1) return EXIT_FAILURE; if ((current_time_calandar_format = localtime(&amp;current_time_epoch_format)) == NULL) return EXIT_FAILURE; if (strftime(output_string, 23, "[%d-%m-%Y %H:%M:%S] ", current_time_calandar_format) != 22) return EXIT_FAILURE; if ((log_file_stream = fopen(log_file_string, "a")) == NULL) return EXIT_FAILURE; if (printf("%s\n", strcat(output_string, input_string)) &lt; 1) return EXIT_FAILURE; if (fprintf(log_file_stream, "%s\n", output_string) &lt; 1) return EXIT_FAILURE; if (fclose(log_file_stream) == EOF) return EXIT_FAILURE; return EXIT_SUCCESS; } int main(int argc, char** argv) { /*Initializations.*/ int EXIT_CODE; /*Print the returned integer from logging_function and exit.*/ printf("%d\n", (EXIT_CODE = logging_function(argv[1], argv[2]))); exit(EXIT_CODE); } </code></pre>
[]
[ { "body": "<p>For one... I don't see any check of <code>argc == 3</code> to make sure the two arguments were actually passed on the command line.</p>\n\n<p>As to others, well, I'd have to study it some more (and frankly I'm not so sure I want to look that hard right now).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T00:40:04.643", "Id": "31445", "Score": "0", "body": "I actually had a line for that, but I deleted it during testing. ._. Meh, its irrelavent as the main focus should be on the function logging_function. Here, lemme edit my post to reflect such." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T00:47:52.030", "Id": "31448", "Score": "0", "body": "Okay, also sorry for wasting your time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T15:52:02.060", "Id": "31474", "Score": "0", "body": "Sorry, didn't meant to offend. If anything I couldn't find else obviously wrong and it'd take some work to find it (that's a good thing)!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T00:38:41.410", "Id": "19647", "ParentId": "19643", "Score": "1" } }, { "body": "<p><code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code> are defined by <code>stdlib.h</code>. I think you need not define them.</p>\n\n<p>You can add the <code>const</code> qualifier to arguments of <code>logging_function()</code>. Those strings are not going to be modified.</p>\n\n<p>You can call <code>fprintf()</code> twice, once with the <code>strftime()</code> output and then with <code>input_string[]</code> and avoid the <code>strcat()</code>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T14:07:19.717", "Id": "19660", "ParentId": "19643", "Score": "3" } }, { "body": "<p>Not sure I like all those <code>if statements</code> lined up like that it makes it hard to read. I have tried to make it more readable (at the end). Weather it works is a matter of opinion so I would not say mine is any better just an alternative.</p>\n\n<p>You also need to watch open()/close() on a file. You should always call close() even if the other functions fail. Otherwise there is potential for you to run out of file descriptors (though unlikely). In short it is a resorce leak and that can be a problem.</p>\n\n<pre><code>if ((log_file_stream = fopen(log_file_string, \"a\")) == NULL) return EXIT_FAILURE;\nif (printf(\"%s\\n\", strcat(output_string, input_string)) &lt; 1) {\n fclose(log_file_stream); // Need to close the fstream\n return EXIT_FAILURE;\n}\nif (fprintf(log_file_stream, \"%s\\n\", output_string) &lt; 1) {\n fclose(log_file_stream); // Need to close the fstream\n return EXIT_FAILURE;\n}\nif (fclose(log_file_stream) == EOF) return EXIT_FAILURE;\n</code></pre>\n\n<p>Your large number of if statements could be reduced (without reducing readability). I would not go to the extreme of putting it all in one if statement but you can definately combine a few.</p>\n\n<pre><code>if ( ((strlen(input_string) + 23) &gt; 32767)\n || ((current_time_epoch_format = time(&amp;current_time_epoch_format)) == -1)\n || ((current_time_calandar_format = localtime(&amp;current_time_epoch_format)) == NULL)\n || (strftime(output_string, 23, \"[%d-%m-%Y %H:%M:%S] \", current_time_calandar_format) != 22)\n || (strcat(output_string, input_string) != output_string)\n )\n{\n return EXIT_FAILURE;\n}\n\nprintf(\"%s\\n\", output_string); // If this fails I am still going to try and print\n // to the log file.\n // I will consider it success if the file printing\n // works correctly even if this fails.\n\nint result = 0;\nif ((log_file_stream = fopen(log_file_string, \"a\")) != NULL)\n{\n int printOk = fprintf(log_file_stream, \"%s\\n\", output_string) == 1;\n int closeOK = (fclose(log_file_stream) == 0);\n\n result = printOk &amp;&amp; closeOk;\n}\nreturn result != 0\n ? EXIT_SUCCESS\n : EXIT_FAILURE;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T21:22:03.023", "Id": "19674", "ParentId": "19643", "Score": "3" } }, { "body": "<p>Some note on your code as it stands:</p>\n\n<ul>\n<li>unnecessary redefinition of EXIT_*</li>\n<li>unnecessary typedef of struct tm</li>\n<li>your parameters should be <code>const</code></li>\n<li><code>localtime</code> is not thread safe - better to use <code>localtime_r</code></li>\n<li>printing of the message to the <code>output_string</code> is unnecessary. Better to print directly to stdout/file than to an intermediate buffer.</li>\n<li>the buffer is also too large to safely put on the stack (in particular in an embedded\nsystem). </li>\n<li>variable names are much too long</li>\n<li>the code is difficult to read</li>\n</ul>\n\n<p>Also, perhaps you should consider the design more carefully.</p>\n\n<p>How will you use the function? Do you really want everything logged to a\n file <strong>and</strong> to <code>stdout</code>? These are activities that I would argue should be\n kept separate. At times you might want to log to a file. If no file is\n specified you might want to log to <code>stdout</code> instead; or even to <code>stderr</code>\n depending upon the nature of the messages. So one function to do everything\n seems a bad design.</p>\n\n<p>Then there is the question of error handling. You have handled all sorts of\n errors without distinguishing between those which are likely and those which\n are not, and without considering what should be done if they occur. Let's\n look at what is likely to fail first:</p>\n\n<ol>\n<li><p>The most likely is that <code>fopen()</code> fails because the log file path doesn't\nexist or is protected.</p></li>\n<li><p>Once you've opened the file successfully, it is unlikely that closing it\nwill fail unless you pass <code>fclose()</code> the wrong pointer or maybe the\npreceding <code>fprintf()</code> failed.</p></li>\n<li><p><code>fprintf(stdout)</code> might fail if <code>stdout</code> is for some reason no longer\nopen.</p></li>\n<li><p><code>fprintf(file)</code> could fail if the filesystem has become full</p></li>\n<li><p>your calls to <code>time()</code>, <code>localtime()</code> or <code>strftime()</code> might conceivably\nfail but failure is really very unlikely.</p></li>\n</ol>\n\n<p>How should you respond to each faiure?</p>\n\n<p>For 1, 2, 3 and 4, propagate the error and use <code>perror</code> to print the error\n to <code>stderr</code> if and when appropriate. But note that failure 1 is most likely at the start of the program, so it makes sense to log a starting message from <code>main()</code> early on, with an exit on failure.</p>\n\n<p>Do you need to handle failure 5 in the same way? It is a remote possibilty,\n most likely during testing when you have not got the strftime format\n correct. Unless you consider the fault serious, just omit the time in case\n of failure (but ensure that the subsequent code does not fail as a result).</p>\n\n<p>For what it is worth, here is how I might rewrite your function. There is a <code>log_msg</code> function that logs to any stream and a log_to_file that logs to a file using log_msg.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;time.h&gt;\n\nstatic int\nlog_msg(FILE *f, const char *msg)\n{\n time_t when = time(NULL);\n struct tm tm;\n char buf[20];\n localtime_r(&amp;when, &amp;tm);\n if (strftime(buf, sizeof buf, \"%d-%m-%Y %H:%M:%S\", &amp;tm) == 0) {\n buf[0] = '\\0';\n }\n if (fprintf(f, \"[%s] %s\\n\", buf, msg) &lt; 0) {\n return -1;\n }\n return 0;\n}\n\nstatic int\nlog_to_file(const char *msg, const char *filename)\n{\n FILE *f = fopen(filename, \"a\");\n if (!f) {\n return -1;\n }\n int ret = log_msg(f, msg);\n if (fclose(f) != 0) {\n ret = -1;\n }\n return ret;\n}\n\nint main(int argc, char** argv)\n{\n if (argc &gt; 1) {\n const char *filename = argv[1];\n if (log_to_file(\"Hello, just testing\", filename) &lt; 0) {\n perror(filename);\n }\n } else {\n if (log_msg(stdout, \"Hello, just testing\") &lt; 0) {\n perror(\"stdout\");\n }\n }\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T02:20:37.720", "Id": "19680", "ParentId": "19643", "Score": "2" } }, { "body": "<pre><code>if ((log_file_stream = fopen(log_file_string, \"a\")) == NULL) return EXIT_FAILURE;\nif (printf(\"%s\\n\", strcat(output_string, input_string)) &lt; 1) return EXIT_FAILURE;\nif (fprintf(log_file_stream, \"%s\\n\", output_string) &lt; 1) return EXIT_FAILURE;\nif (fclose(log_file_stream) == EOF) return EXIT_FAILURE;\n</code></pre>\n\n<p>You leak <code>log_file_stream</code> if any of the lines between the <code>fopen</code> and the <code>fclose</code> fail.</p>\n\n<p>There are several ways around this. In C (which does not have exceptions or <a href=\"http://en.wikipedia.org/wiki/RAII\" rel=\"nofollow\">RAII</a>), the best way around this is to avoid early <code>return</code> statements when there's something to clean up. (Allocation, file handle, lock being held, etc.)</p>\n\n<p>For example you could do (just meant as a quick sketch):</p>\n\n<pre><code>FILE *log_file_stream = NULL;\nint status = 0;\n\nif (!status &amp;&amp; (log_file_stream = fopen(log_file_string, \"a\")) == NULL) status = EXIT_FAILURE;\nif (!status &amp;&amp; printf(\"%s\\n\", strcat(output_string, input_string)) &lt; 1) status = EXIT_FAILURE;\nif (!status &amp;&amp; fprintf(log_file_stream, \"%s\\n\", output_string) &lt; 1) status = EXIT_FAILURE;\n\n// Close the file if it is non-NULL.\n//\nif (log_file_stream)\n fclose(log_file_stream);\n\nreturn status;\n</code></pre>\n\n<p>The key benefit is that this <code>fclose</code> call runs regardless of success or failure, similar to a <code>finally</code> block or a destructor in RAII. You can add more <code>if (!status &amp;&amp; /* ... */)</code> blocks at will and you won't have to add redundant cleanup code.</p>\n\n<p>Another way to do this is to use <code>goto</code> (if you are not morally opposed to it for silly reasons - it actually works well in C code for this specific purpose and you'll find it all over large projects, including *nix kernels.)</p>\n\n<pre><code> FILE *log_file_stream = NULL;\n int status = 0;\n\n if ((log_file_stream = fopen(log_file_string, \"a\")) == NULL) goto error;\n if (printf(\"%s\\n\", strcat(output_string, input_string)) &lt; 1) goto error;\n if (fprintf(log_file_stream, \"%s\\n\", output_string) &lt; 1) goto error;\n\n cleanup:\n // Close the file if it is non-NULL.\n //\n if (log_file_stream)\n fclose(log_file_stream);\n\n return status;\n\n error:\n status = EXIT_FAILURE;\n goto cleanup;\n</code></pre>\n\n<p>This gives you the benefit of not having to tediously check <code>status</code> again and again.</p>\n\n<hr>\n\n<p><b>Update on 2nd reading</b></p>\n\n<p>I don't like some of the repeated buffer size constants here, for example <code>strlen(input_string) + 23 &gt; 32767</code> ... how weird to write out <code>32767</code> instead of <code>sizeof(output_string)</code>, which would allow you to change the size without having to change it in two places.</p>\n\n<p>Taking <code>strlen()</code> (an O(n) operation) to perform the size check is also a bit odd. One common idiom in C code is to just optimistically start storing characters in the output buffer, and the moment you detect that you don't have enough space, <b><i>that's</i></b> when you return the error. (Think of an implementation of <code>strncpy(dst, src, n)</code> which has something like <code>while (*src &amp;&amp; n) { *dst++ = *src++; --n; }</code> at its core.) Looking at your code though it doesn't seem like using that idiom directly will be convenient, but you can start using standard string functions in a way that will be more consistent with that. Maybe you should make the <code>strftime</code> call write into a stack-allocated temporary buffer (and again, please pass something derived from <code>sizeof</code> as the size parameter, rather than writing an integer constant size twice), then feed the results into <code>snprintf(output_buffer, sizeof(output_buffer), /* ... */)</code>, which will take this approach.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T02:40:56.910", "Id": "19681", "ParentId": "19643", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T00:08:12.663", "Id": "19643", "Score": "2", "Tags": [ "performance", "c", "strings", "logging" ], "Title": "Logging input and log file strings" }
19643
<p>I am a CS student about to enter my junior year. I am attempting to get better and better at programming and thought that this would be a good place to toss my code out there to see if some of you could give me some tips on how to make it better.</p> <p>If you've got tips as to different websites I could go to for this sort of thing, please don't hesitate to tell me.</p> <pre><code>import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; /************************************************************************* * Compilation: javac EightPuzzle.java Execution: java EightPuzzle Dependencies: * MinPQ.java * * AI solution to N-by-N slider puzzle using heuristic function which is depth * in tree plus number of tiles out of position. * * Note: integer 0 corresponds to blank cell * * Goal state is of the following form and is hardwired into the dist() and * manhattan() methods. * * 1 2 3 4 5 6 7 8 * *************************************************************************/ public class EightPuzzle implements Comparable&lt;EightPuzzle&gt; { private final static int N = 3; private final static String[] names = { " ", " 1", " 2", " 3", " 4", " 5", " 6", " 7", " 8" }; private static int totalEnqueued; private final static int[][] solved = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 0 } }; private int moves; private int[][] tiles; private EightPuzzle parent; private int priority; private int distance; int zeroLocX = 0; int zeroLocY = 0; // allocate separate memory for new tiles array EightPuzzle(int[][] tiles) { this.tiles = new int[N][N]; for (int i = 0; i &lt; N; i++) for (int j = 0; j &lt; N; j++) this.tiles[i][j] = tiles[i][j]; } EightPuzzle(int[][] tiles, EightPuzzle parent, int moves) { this.tiles = new int[N][N]; for (int i = 0; i &lt; N; i++) for (int j = 0; j &lt; N; j++) this.tiles[i][j] = tiles[i][j]; this.parent = parent; this.moves = moves; priority(); } // priority /** * @return */ public int priority() { int manhatDist = 0; for (int x = 0; x &lt; N; x++) for (int y = 0; y &lt; N; y++) { switch (tiles[x][y]) { case 1: manhatDist += posDiff(x, y, 0, 0); break; case 2: manhatDist += posDiff(x, y, 0, 1); break; case 3: manhatDist += posDiff(x, y, 0, 2); break; case 4: manhatDist += posDiff(x, y, 1, 0); break; case 5: manhatDist += posDiff(x, y, 1, 1); break; case 6: manhatDist += posDiff(x, y, 1, 2); break; case 7: manhatDist += posDiff(x, y, 2, 0); break; case 8: manhatDist += posDiff(x, y, 2, 1); break; case 0: manhatDist += posDiff(x, y, 2, 2); break; default: break; } } this.priority = manhatDist + moves; return priority; } private int posDiff(int xPos, int yPos, int xGoal, int yGoal) { int diff = Math.abs(xPos - xGoal); diff += Math.abs(yPos - yGoal); return diff; } // which board position is closer to the goal board position /** * (non-Javadoc) see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(EightPuzzle b) { if (b.distance() == distance()) { for (int i = 0; i &lt; N; i++) { if (!(Arrays.equals(b.getBoard()[i], this.getBoard()[i]))) { //if any elements are different, we know the arrays are not equal if (b.priority() &gt; priority()) //but we still need to know whether to return a -1 or 1 return -1; return 1; } } return 0; //if we make it here they are equal } else if (b.priority() &gt; priority()) //if the distances are different return -1; else return 1; } /** * @return */ public int[][] getBoard() { return tiles; } // does board position equal goal position? /** * @return */ public boolean isSolved() { // your implementation for (int i = 0; i &lt; N; i++) { if (!(Arrays.equals(tiles[i], solved[i]))) { return false; } } return true; } //for NxN expansion...not quite complete yet. public int[][] findGoalState() { int[][] solved = new int[N][N]; int nums = 1; for (int i = 0; i &lt; N; i++) for (int j = 0; j &lt; N; j++) { solved[i][j] = nums; nums++; if (nums == (N * N)) { solved[N - 1][N - 1] = 0; break; } } return solved; } // return sum of Manhattan distances of tiles to their proper position private int distance() { this.distance = priority() - moves; return this.distance; } private int getZeroXLoc() { for (int x = 0; x &lt; N; x++) for (int y = 0; y &lt; N; y++) if (tiles[x][y] == 0) { zeroLocX = x; //finding our zero so we can begin moving tiles zeroLocY = y; } return zeroLocX; } private int getZeroYLoc() { getZeroXLoc(); return zeroLocY; } private void assignZeroLoc() { getZeroYLoc(); } // return the neighboring board positions /** * @return */ public EightPuzzle[] neighbors() { ArrayList&lt;EightPuzzle&gt; tempneighbors = new ArrayList&lt;EightPuzzle&gt;(); assignZeroLoc(); //determines both x and y loc's of the zero for (int i = -1; i &lt; 2; i++) { //creating all surrounding x coordinates int p = zeroLocX + i; //current array being looked at if (p &lt; 0 || p &gt; N - 1) continue; //meaning these squares are out of bounds for (int j = -1; j &lt; 2; j++) { int q = zeroLocY + j; //current index in current array if (q &lt; 0 || q &gt; N - 1 || (p == zeroLocX &amp;&amp; q == zeroLocY) || //if we are out of bounds or at the same square ((Math.abs(zeroLocX - p) + Math.abs(zeroLocY - q))) &gt; 1) //or if delta x + delta y is greater than 1, aka at a diagonal space continue; //skip this iteration int[][] temptiles = new int[N][N]; for (int m = 0; m &lt; N; m++) temptiles[m] = Arrays.copyOf(tiles[m], N); //copy the original board int tempQ = temptiles[p][q]; //store the value of the value to swap temptiles[p][q] = 0; //place the 0 in a valid location temptiles[zeroLocX][zeroLocY] = tempQ; //place the stored value to swap where the 0 was EightPuzzle neighbor = new EightPuzzle(temptiles, this, this.moves + 1); //create a new 8 puzzle tempneighbors.add(neighbor); //add it to the arraylist totalEnqueued++; } } EightPuzzle[] neighbors = new EightPuzzle[tempneighbors.size()]; return tempneighbors.toArray(neighbors); } // print parents in reverse order /** * */ public void showPath() { if (parent != null) parent.showPath(); System.out.println("Move #" + moves + " Priority = " + priority); System.out.println(toString()); } // print details of puzzle /** * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { String s = ""; for (int i = 0; i &lt; N; i++) { for (int j = 0; j &lt; N; j++) s += names[tiles[i][j]] + " "; s += "\n"; } return s; } /** * @return */ public boolean isSolvable() { int[] row = new int[(N * N) - 1]; int rowIndex = 0; for (int i = 0; i &lt; N; i++) { for (int j = 0; j &lt; N; j++) { if (tiles[i][j] != 0) { row[rowIndex] = tiles[i][j]; rowIndex++; } } } int inversions = 0; for (int x = 0; x &lt; row.length; x++) { for (int y = x; y &lt; row.length; y++) if (row[x] &gt; row[y]) inversions++; } return inversions % 2 == 0; } /*********************************************************************** * Test routine. **********************************************************************/ public static void main(String[] args) { // 6 moves int[][] easy0 = { { 1, 2, 3 }, { 7, 0, 5 }, { 8, 4, 6 } }; //&lt;1 second int[][] hard0 = { { 0, 8, 7 }, { 2, 5, 1 }, { 3, 6, 4 } }; //5.5 minutes int[][] hard1 = { { 4, 5, 0 }, { 6, 8, 7 }, { 1, 2, 3 } }; //5.5 minutes int[][] medium0 = { { 2, 3, 1 }, { 7, 0, 8 }, { 6, 5, 4 } }; //1 second int[][] medium1 = { { 1, 2, 3 }, { 8, 0, 4 }, { 7, 6, 5 } }; //1 second int[][] medium2 = { { 1, 2, 3 }, { 7, 0, 4 }, { 8, 6, 5 } }; //2 seconds int[][] twentytwo = { {4, 8, 2}, {3, 6, 5}, {1, 7, 0} }; System.out .println("Please enter the 3x3 grid in the format \n\"XXX \n XXX \n XXX\" where X is a number between 0 and 8"); Scanner scan = new Scanner(System.in); int userEntered = 0; int[][] userIn = new int[N][N]; try { while (userEntered &lt; 3) { String line = scan.nextLine().trim(); for (int i = 0; i &lt; N; i++) { userIn[userEntered][i] = Integer.parseInt(Character .toString((line.charAt(i)))); } userEntered++; } } catch (Exception e) { System.out .println("Please restart the program and enter the gridin the correct format"); System.exit(0); } EightPuzzle x = new EightPuzzle(userIn); System.out.println(x); MinPQ&lt;EightPuzzle&gt; pq = new MinPQ&lt;EightPuzzle&gt;(); pq.insert(x); int nodes = 0; ArrayList&lt;EightPuzzle&gt; seen = new ArrayList&lt;EightPuzzle&gt;(); // Stopwatch sw = new Stopwatch(); while (!pq.isEmpty()) { x = pq.delMin(); //get the minimum key if (nodes == 0) { if (!x.isSolvable()) { System.out .println("This is an unsolvable puzzle, please enter a solvable one"); System.exit(0); } } nodes++; //TODO:make this faster, maybe a binary search tree instead of arraylist for (int i = 0; i &lt; seen.size(); i++) { //make sure we aren't back tracking. if (x.compareTo(seen.get(i)) == 0) { x = pq.delMin(); } } seen.add(x); //add to the nodes we've seen if (x.isSolved()) { // System.out.println(sw.elapsedTime()); break; } EightPuzzle[] neighbors = x.neighbors(); //find and add all neighbors for (int i = 0; i &lt; neighbors.length; i++) if (!(x.compareTo(neighbors[i]) == 0) &amp;&amp; neighbors[i].isSolvable()) pq.insert(neighbors[i]); } System.out.println("Total nodes enqueued = " + totalEnqueued); System.out.println("Nodes expanded = " + nodes); x.showPath(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T14:05:28.710", "Id": "31504", "Score": "0", "body": "MinPQ cannot be resolved to a type" } ]
[ { "body": "<p>In the Constructor, you manually copy an array:</p>\n\n<pre><code>for(int j = 0; j &lt; N; j++)\n{\n this.tiles[i][j] = tiles[i][j];\n}\n</code></pre>\n\n<p>Which can be replaced with:</p>\n\n<pre><code>System.arraycopy(tiles[i], 0, this.tiles[i], 0, N);\n</code></pre>\n\n<p>And the entire switch in your <code>priority()</code> method can be replaced by:</p>\n\n<pre><code>manhatDist += posDiff(x, y, (tiles[x][y] == 0 ? 2 : (int) (tiles[x][y] / 3.5)), (tiles[x][y] + 2) % 3);\n</code></pre>\n\n<p>To test this code, I used:</p>\n\n<pre><code>for(int i = 0; i &lt; 9; i++)\n{\n System.out.println(i + \"\\t\" + (i == 0 ? 2 : (int) (i / 3.5)) + \"\\t\" + (i + 2) % 3);\n}\n</code></pre>\n\n<p>Which produces:</p>\n\n<pre><code>0 2 2\n1 0 0\n2 0 1\n3 0 2\n4 1 0\n5 1 1\n6 1 2\n7 2 0\n8 2 1\n</code></pre>\n\n<p>Which is what you're already doing manually.</p>\n\n<p>Additionally, your constructor with more parameters exactly duplicates code from the smaller one, so you could replace (your newly changed!):</p>\n\n<pre><code>this.tiles = new int[N][N];\nfor(int i = 0; i &lt; N; i++)\n{\n System.arraycopy(tiles[i], 0, this.tiles[i], 0, N);\n}\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>this(new int[N][N]);\n</code></pre>\n\n<p>So the smaller constructor does that part, then continues with the additional options.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T02:39:49.333", "Id": "31449", "Score": "0", "body": "Great, thanks for the suggestions. I implemented them both and it looks like they are working well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T02:40:47.800", "Id": "31450", "Score": "0", "body": "Does anyone have a suggestion as to how the neighbors() method could be improved? I was playing with recursive ideas and/or a BFS but couldn't quite put my finger on it as well as I could with this iterative solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T12:20:50.293", "Id": "31471", "Score": "0", "body": "My original change to your switch was wrong, I didn't notice the third parameter should change. I have updated my post to include the new code as well as the output." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T00:29:49.097", "Id": "19646", "ParentId": "19644", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T00:16:08.653", "Id": "19644", "Score": "5", "Tags": [ "java", "ai" ], "Title": "Optimizations to 8-puzzle" }
19644
<p>I'm writing a Telnet parser in Haskell that can run within any monad that implements some event-handling functions. When it finishes processing a block of input - whether because it read it all or because it was interrupted by an event handler - it returns the remainder of the text and a continuation for more input.</p> <p>Right now, the code works, but it's pretty ugly. I've tried to make the patterns I saw in the program as obvious as possible, but I'm stymied at the actual refactoring stage.</p> <p>I'm still pretty new to Haskell, so any feedback and advice on best practices is appreciated!</p> <pre><code>import qualified Data.ByteString as BS import Data.ByteString (ByteString) import Data.Word (Word8) import Control.Monad {- - I suspect I can change these datatypes to use something like - data Parser m r = Parser (ByteString -&gt; m r) - but I'm not sure how to go about doing that. -} data TelnetParser m = TelnetParser (ByteString -&gt; m (TelnetState m)) type TelnetState m = (ByteString, TelnetParser m) {- - These are the handler functions that the parser requires. - These allow you to execute other monadic actions in response to - Telnet events. -} class (Monad m) =&gt; Telnet m where onText :: Word8 -&gt; m () onCommand :: Word8 -&gt; m Bool onOption :: Word8 -&gt; Word8 -&gt; m Bool onText _ = return () onCommand _ = return True onOption _ _ = return True readTelnet :: (Telnet m) =&gt; ByteString -&gt; TelnetParser m -&gt; m (TelnetState m) readTelnet str (TelnetParser f) | BS.null str = return (str, TelnetParser f) | otherwise = f str isOption :: Word8 -&gt; Bool isOption = (`elem` [250..254]) decideContinue :: (Telnet m) =&gt; Bool -&gt; ByteString -&gt; TelnetParser m -&gt; m (TelnetState m) decideContinue True = readTelnet decideContinue False = curry return {- - These functions implement the various states of the Telnet parser. -} readOption :: (Telnet m) =&gt; Word8 -&gt; ByteString -&gt; m (TelnetState m) readOption cmd str = do action &lt;- decideContinue `liftM` onOption cmd ch action rest (TelnetParser readText) where (ch, rest) = (BS.head str, BS.tail str) readIAC :: (Telnet m) =&gt; ByteString -&gt; m (TelnetState m) readIAC str | ch == 255 = onText ch &gt;&gt; (rest `readTelnet` TelnetParser readText) | isOption ch = (rest `readTelnet` TelnetParser (readOption ch)) | otherwise = do action &lt;- decideContinue `liftM` onCommand ch action rest (TelnetParser readText) where (ch, rest) = (BS.head str, BS.tail str) readCR :: (Telnet m) =&gt; ByteString -&gt; m (TelnetState m) readCR str | ch == 10 = onText 13 &gt;&gt; onText 10 &gt;&gt; (rest `readTelnet` TelnetParser readText) | ch == 0 = onText 13 &gt;&gt; (rest `readTelnet` TelnetParser readText) | otherwise = onText 13 &gt;&gt; (rest `readTelnet` TelnetParser readText) where (ch, rest) = (BS.head str, BS.tail str) readText :: (Telnet m) =&gt; ByteString -&gt; m (TelnetState m) readText str | ch == 255 = (rest `readTelnet` TelnetParser readIAC) | ch == 13 = (rest `readTelnet` TelnetParser readCR) | otherwise = onText ch &gt;&gt; (rest `readTelnet` TelnetParser readText) where (ch, rest) = (BS.head str, BS.tail str) </code></pre>
[]
[ { "body": "<p>I think one of the reason why functional programming is usually easier is its natural modularity. Consider to design your solution in a more layered way. I.e. separate parser and invocations. Avoid callbacks in favor of lazy stream of events (see <a href=\"http://www.haskell.org/ghc/docs/7.6.1/html/libraries/base-4.6.0.0/System-IO-Unsafe.html#v%3aunsafeInterleaveIO\" rel=\"nofollow\"><code>unsafeInterleaveIO</code></a>) or borrow ideas from reactive frameworks. Also see <a href=\"http://hackage.haskell.org/packages/archive/binary/0.6.4.0/doc/html/Data-Binary-Get.html\" rel=\"nofollow\"><code>Data.Binary.Get</code> module</a> or <a href=\"http://hackage.haskell.org/package/parsec\" rel=\"nofollow\"><code>parsec</code> package</a> for implementing parser.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T11:54:59.730", "Id": "19692", "ParentId": "19652", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T04:04:00.867", "Id": "19652", "Score": "4", "Tags": [ "haskell" ], "Title": "Refactoring a Telnet parser" }
19652
<p>I've written a script to generate DNA sequences and then count the appearance of each step to see if there is any long range correlation.</p> <p>My program runs really slow for a length 100000 sequence 100 times replicate. I already run it for more than 100 hours without completion.</p> <pre><code>#!/usr/bin/env python import sys, random import os import math length = 10000 initial_p = {'a':0.25,'c':0.25,'t':0.25,'g':0.25} tran_matrix = {'a': {'a':0.495,'c':0.113,'g':0.129,'t':0.263}, 'c': {'a':0.129,'c':0.063,'g':0.413,'t':0.395}, 't': {'a':0.213,'c':0.495,'g':0.263,'t':0.029}, 'g': {'a':0.263,'c':0.129,'g':0.295,'t':0.313}} def fl(): def seq(): def choose(dist): r = random.random() sum = 0.0 keys = dist.keys() for k in keys: sum += dist[k] if sum &gt; r: return k return keys[-1] c = choose(initial_p) sequence = '' for i in range(length): sequence += c c = choose(tran_matrix[c]) return sequence sequence = seq() # This program takes a DNA sequence calculate the DNA walk score. #print sequence #print len u = 0 ls = [] for i in sequence: if i == 'a' : #print i u = u + 1 if i == 'g' : #print i u = u + 1 if i== 'c' : #print i u = u - 1 if i== 't' : #print i u = u - 1 #print u ls.append(u) #print ls l = 1 f = [] for l in xrange(1,(length/2)+1): lchange =1 sumdeltay = 0 sumsq = 0 for i in range(1,length/2): deltay = ls[lchange + l ] - ls[lchange] lchange = lchange + 1 sq = math.fabs(deltay*deltay) sumsq = sumsq + sq sumdeltay = sumdeltay + deltay f.append(math.sqrt(math.fabs((sumsq/length/2) - math.fabs((sumdeltay/length/2)*(sumdeltay/length/2))))) l = l + 1 return f def performTrial(tries): distLists = [] for i in range(0, tries): fl() distLists.append(fl()) return distLists def main(): tries = 10 distLists = performTrial(tries) #print distLists #print distLists[0][0] averageList = [] for i in range(0, length/2): total = 0 for j in range(0, tries): total += distLists[j][i] #print distLists average = total/tries averageList.append(average) # print total return averageList out_file = open('Markov1.result', 'w') result = str(main()) out_file.write(result) out_file.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:26:31.680", "Id": "31452", "Score": "0", "body": "Could you explain what this is supposed to do in plain English? 1) At the moment, this is a bit long to read without explanation, 2) It may help you identify the problem yourself, and 3) Stop people taking a stab at stuff that looks like it *may* be wrong" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:35:07.817", "Id": "31453", "Score": "0", "body": "Hi, the first function is seq(), it randomly generate DNA sequences based on the transition matrix follow markov chain, each step will be either a,c,t,or g. the length is ten thousands. after the dna sequence generated, the u will be calculated. u is the total score by DNA walk, for example, at each step, if there is a|g, u + 1, if there is a c|g, u -1. Therefore we will have u from step 1 to step 10 thousands. Then we calculate the fluctuation for u from l= 1 step to l =5000 step, to see if there is a long range correlation exist. The performTrial() is using to do replicate for fl() function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:38:30.300", "Id": "31454", "Score": "0", "body": "Then the main() calculate the average score from the replications output from performTrial()." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:42:08.367", "Id": "31455", "Score": "0", "body": "The f value return from fl() is the root mean fluctuation calculated from u on different length(step) scale." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:52:36.157", "Id": "31456", "Score": "0", "body": "@Frank Is there a reason your `fl()` function only operates over half the random sequence and does nothing with the other half?" } ]
[ { "body": "<p>One word: numpy.</p>\n\n<p>A few more words: </p>\n\n<p><code>numpy</code> is a library that includes highly-tuned algorithms (often in Fortran, C, and C++) specifically for the purposes of accelerating numerical computations over matrices and other arrays. If it's at all applicable to what you're trying to do, it's almost certainly the best answer. Even when <code>numpy</code> itself isn't appropriate, look at the other components of <code>scipy</code> (the larger project it's part of).</p>\n\n<p>At the moment, the <a href=\"http://numpy.scipy.org\">numpy site</a> seems to be down, and the <a href=\"http://www.scipy.org\">scipy site</a> seems to be responding but broken. The <a href=\"http://docs.scipy.org/doc/\">docs wiki</a> is working, at least. (Please don't take this as an indication that <code>numpy</code> is some fly-by-night project; almost everyone who does numerical or scientific computing in Python relies on it. I'm sure it'll be fixed shortly.)</p>\n\n<p>However, there are other possibilities for other use cases:</p>\n\n<ul>\n<li>Analyze your algorithms and make sure the problem isn't what you're doing, rather than how you're doing it. There's no point making everything 30% faster, or even 95%, when the real problem is that you're doing 1000000 loops instead of 1000.</li>\n<li>Profile your code, and don't worry about the parts that aren't slow or aren't called often.</li>\n<li>Whenever it's possible to use a built-in function, even if it's a bit more awkward, it's often faster. (For example, sticking an iterator in a <code>collections.deque</code> of size 0 is at least 30% faster than any pure-Python way of walking and disposing the iterator.) </li>\n<li><a href=\"http://www.cython.org\">Cython</a> gives you a way to write almost-Python code that gets compiled into C (and then into binary code).</li>\n<li>You can port (bits of) your code to C explicitly.</li>\n<li>Sometimes just running in <code>PyPy</code> (or maybe <code>Jython</code> or <code>IronPython</code>) instead of the normal <code>CPython</code> makes a big difference.</li>\n<li>Replace explicit lists with generators, and explicit list-building loops that can't be replaced by generators with list comprehensions.</li>\n<li>If you need that last 2%, there are all kinds of tricks, like rebinding members of objects to local variables, that aren't <em>always</em> more trouble than they're worth.</li>\n</ul>\n\n<p>A couple more words on Cython:</p>\n\n<p>The first step to accelerating some slow critical code with Cython is just to move it as-is into Cython. If that doesn't help enough, try adding explicit types to variables and turning function definitions from <code>def</code> into <code>cdef</code>. If that's still not enough, then you have to actually learn how to use <code>Cython</code> effectively—but you may get enough win that you don't even have to understand why it's helping. (Although obviously you <em>should</em> learn anyway.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:36:31.657", "Id": "31457", "Score": "0", "body": "I have only skimmed over his code, but some of the operations seem to be hard/impossible to vectorize, so for this particular case `numpy` may not be the answer. But still +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:39:06.593", "Id": "31459", "Score": "1", "body": "They should also take a look at [PyMC](http://pymc-devs.github.com/pymc/) for MCMC implementations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:41:23.957", "Id": "31460", "Score": "1", "body": "@Frank You might want to also look at [Python for Data Analysis](http://shop.oreilly.com/product/0636920023784.do) (note: I have no financial incentive in plugging this book). It's a good book for learning how to do the kinds of things you're trying to do with Python. In short, you're doing it all wrong. This should set you straight. See also if you can find some workshops in your area to learn using Python for scientific data analysis." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:44:05.293", "Id": "31461", "Score": "0", "body": "@Iguananaut: You might want to write a separate answer if you've got specifics that are more appropriate to his use case than my general answer, because it may be more useful to a later reader (also, I can +1 you again that way)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:46:05.297", "Id": "31462", "Score": "0", "body": "@abarnert Thanks,I really appreciate it, i'll try incorporate your ideas first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:48:33.253", "Id": "31463", "Score": "0", "body": "@Iguananaut Thanks for the suggestion, can you please at least point out where is the wrong part, the way to do this job or which step should i take to go the right way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:33:19.300", "Id": "31464", "Score": "0", "body": "@Frank It's kind of lots of things, so it's hard to respond to every single one. The first is the use of pure Python for number crunching--that's just always going to be slow. You want to use vectorized operations as much as possible, as well as existing implementations of whatever algorithms you're implementing. Second, there are lots of basic Python mistakes. That's fine, you're a beginner. It's just hard to address everything. I'll see what I can do in a bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:53:30.157", "Id": "31465", "Score": "1", "body": "@Iguananaut (and OP) I think profiling the existing code would be the best first step -- and it could be very useful during the likely iterative process of speeding various parts of it up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T23:22:19.783", "Id": "31466", "Score": "0", "body": "@martineau: I think thinking through the algorithm is the first step; profiling second. But either way, I think both of them are high enough up on the list of recommendations (being #1 and #2)." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:26:16.517", "Id": "19655", "ParentId": "19654", "Score": "12" } }, { "body": "<p>Concerning just a little part of your code</p>\n\n<pre><code>u = 0\nls = []\nfor i in sequence:\n u += (1 if i in 'ag' else (-1))\n ls.append(u)\n\nprint ls\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>def gen(L,u = 0):\n for i in L:\n u += (1 if i in 'ag' else (-1))\n yield u\n\nprint list(gen(sequence))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T00:19:15.767", "Id": "19656", "ParentId": "19654", "Score": "1" } }, { "body": "<p>At the risk of being frivolous, two suggestions with the posted code:</p>\n\n<ol>\n<li><p>Did you really mean <code>fl()</code> on both occasions?</p>\n\n<pre><code>for i in range(0, tries):\n fl()\n distLists.append(fl())\n</code></pre></li>\n<li><p>There's no need to use <code>math.fabs</code> on values guaranteed to be positive!</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T21:44:46.393", "Id": "19675", "ParentId": "19654", "Score": "1" } }, { "body": "<p>Your algorithm is quadratic in length and linear in tries. \nThe double loop in fl() dominates. O(length^2 * tries)</p>\n\n<p>After Glenn's improvements (removing superfluous fl() halves the running time of main() and removing the function call from the inner loop further reduces the running time almost by another third. Your mileage may vary.) fl() runs about 6-7 secs. main totals ~70 secs.</p>\n\n<p>increasing the length by ten (10,000 to 100,000), and increasing the tries by ten (10 to 100) (which I understand from \"100 times replicate,\") the running time should be about ~70,000 secs which is about 20hrs.</p>\n\n<p>implementing the algorithm in C or another compiled language, Cython, (maybe PyPy, it can do JIT for pure python, as far as I know, which your inner loop is)\nshould further half that time to about 8/10 hrs, which is acceptable.</p>\n\n<p>Moreover, </p>\n\n<pre><code>lchange =1\nsumdeltay = 0\nsumsq = 0\nfor i in range(1,length/2):\n deltay = ls[lchange + l ] - ls[lchange]\n lchange = lchange + 1\n sq = math.fabs(deltay*deltay)\n sumsq = sumsq + sq\n sumdeltay = sumdeltay + deltay\nff = math.sqrt(math.fabs((sumsq/length/2) - (sumdeltay/length/2)*(sumdeltay/length/2)))\n</code></pre>\n\n<p>portion of your code is read-only, and paralellizable.\nyou can calculate ls beforehand and save to a text file.\nput the code in a separate python script.\nspawn new processes passing each <code>l</code> (or some interval of <code>l</code> values eg, 500-1000 depending on no of processes you want to spawn) as command-line parameters.\nand saving the results in text files, e.g. f_345.txt, if run with <code>l=345</code>.\nlater combining the results.\nthis can be done in python or bash or some other scripting language.</p>\n\n<p>you can, possibly, further half the run time on a quad-core desktop.\nor split the work to multiple computers (in a work or school environment).\nalso you will not lose partial results.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T09:31:04.967", "Id": "31494", "Score": "0", "body": "I also think, since you mentioned correlation, that `sumsq/length/2` should be `sumsq/(length/2)`.\n\n`/` is left associative in python. But I guess you want to divide by `(length/2)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T07:58:32.993", "Id": "31547", "Score": "0", "body": "another bad style or less probably a bug is the use of local variables in the loop\n`lchange` is always equal to `i` so why not just use `i`, if the name means something it can be called `lchange` then.\n\n`l = l + 1` has no effect. `l` iterates over `xrange(1,(length/2)+1)` with or without it. if you are trying to iterate over odd numbers, which i do not think you do, you should use `xrange(1,(length/2)+1, 2)`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T09:19:54.600", "Id": "19688", "ParentId": "19654", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:20:57.837", "Id": "19654", "Score": "6", "Tags": [ "python", "beginner", "algorithm", "bioinformatics" ], "Title": "Generating DNA sequences and looking for correlations" }
19654
<p>Are there ways to avoid this triply nested for-loop?</p> <pre><code>def add_random_fields(): from numpy.random import rand server = couchdb.Server() databases = [database for database in server if not database.startswith('_')] for database in databases: for document in couchdb_pager(server[database]): if 'results' in server[database][document]: for tweet in server[database][document]['results']: if tweet and 'rand_num' not in tweet: print document tweet['rand_num'] = rand() server[database].save(tweet) </code></pre> <p><strong>Update</strong> </p> <p>People suggesting that I use a generator reminded me that I forgot to mention that <code>couchdb_pager</code> is a generator over the list <code>server[database]</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T05:37:54.397", "Id": "31467", "Score": "4", "body": "Fundamentally, you're descending through three separate levels of data. Unless you can flatten them or skip one, you have to use a for-loop for each level in the hierarchy. I'd suggest refactoring some of your loops out into their own functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T06:48:52.893", "Id": "31468", "Score": "0", "body": "Maybe using a generator or iterator?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T07:46:05.427", "Id": "31470", "Score": "3", "body": "As it is I don't see any problem with this code - it's readable and efficient. If you really don't like the nesting you could do something like `documents = (document for database in databases for document in couchdb_pager(server[database]) if 'results' in document)` then loop through the documents." } ]
[ { "body": "<p>I agree with the question comments - there's no real way to avoid them (unless you can restructure the databases!), but the code can be made more readable by removing the loops into a separate generator function, especially since you're not doing any processing between each loop.</p>\n\n<p>Consider something like (caution: untested):</p>\n\n<pre><code>def find_all_document_tweets( server ):\n databases = [database for database in server if not database.startswith('_')]\n for database in databases:\n for document in couchdb_pager(server[database]):\n if 'results' in server[database][document]:\n for tweet in server[database][document]['results']:\n yield database, document, tweet\n\ndef add_random_fields():\n from numpy.random import rand\n server = couchdb.Server()\n for ( database, document, tweet ) in find_all_document_tweets( server ):\n if tweet and 'rand_num' not in tweet:\n print document\n tweet['rand_num'] = rand()\n server[database].save(tweet)\n</code></pre>\n\n<p>As an extra bonus, it seems likely that the loops now in <code>find_all_document_tweets</code> will be common in your code, so that it's now usable elsewhere.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T07:56:46.643", "Id": "19658", "ParentId": "19657", "Score": "1" } }, { "body": "<p>There are a few tweaks that can improve this code:</p>\n\n<pre><code>def add_random_fields():\n from numpy.random import rand\n server = couchdb.Server()\n databases = (server[database] for database in server if not database.startswith('_'))\n # immediately fetch the Server object rather then the key, \n # changes to a generator to avoid instantiating all the database objects at once\n for database in databases:\n for document in couchdb_pager(database):\n document = database[document] \n # same here, avoid holding keys when you can have the objects\n\n for tweet in document.get('results', []):\n # rather then checking for the key, have it return a default that does the same thing\n if tweet and 'rand_num' not in tweet:\n print document\n tweet['rand_num'] = rand()\n database.save(tweet)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T14:27:30.333", "Id": "19694", "ParentId": "19657", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T05:07:32.170", "Id": "19657", "Score": "3", "Tags": [ "python" ], "Title": "Removing the massive amount of for-loops in this code" }
19657
<p>Is this an acceptable way to make sure a java.sql.ResultSet is always closed, and also make sure that an Exception caught is propagated to the caller? </p> <p>Please don't hesitate to review other aspects of this sample as well.</p> <pre><code>public void updateReplicationStatus(BeanReplicationTask taskBean, String strStatus) throws Exception { String strSelect = this.createReplicationSelectStatement(taskBean); ResultSet resultSet = null; try { resultSet = DerbyDog.getResultSet(strSelect); if (resultSet.next()) { resultSet.updateString(COLUMN_STATUS, strStatus); resultSet.updateRow(); } } catch (Exception e) { throw e; } finally { if (resultSet != null) { resultSet.close(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T14:15:33.313", "Id": "31505", "Score": "0", "body": "To answer the questions: 2 times yes." } ]
[ { "body": "<h1>Close a ResultSet/Resource</h1>\n\n<p>If you are using java 7 then I would recommend to use <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\">try with resources</a></p>\n\n<p>it will take care of closing ResultSet for you and make your code a little cleaner.</p>\n\n<pre><code>public void updateReplicationStatus(BeanReplicationTask taskBean, String strStatus) throws Exception {\n String strSelect = this.createReplicationSelectStatement(taskBean); \n try (ResultSet resultSet = DerbyDog.getResultSet(strSelect) { \n if (resultSet.next()) {\n resultSet.updateString(COLUMN_STATUS, strStatus);\n resultSet.updateRow();\n }\n } catch (Exception e) {\n throw e;\n } \n}\n</code></pre>\n\n<h1>Exception Handling</h1>\n\n<p>personal I prefer to wrap my own exceptions around generic exceptions. </p>\n\n<p>That way I can throw a more precise exception with a comment to help myself when debugging</p>\n\n<pre><code>public void updateReplicationStatus(BeanReplicationTask taskBean, String strStatus) throws ReplicationStatusException {\n String strSelect = this.createReplicationSelectStatement(taskBean); \n try (ResultSet resultSet = DerbyDog.getResultSet(strSelect) { \n if (resultSet.next()) {\n resultSet.updateString(COLUMN_STATUS, strStatus);\n resultSet.updateRow();\n }\n } catch (SqlException e) {\n throw new ReplicationStatusException(\"update ReplicationStatus failed because of a SQLException\", e);\n } catch (Exception e) {\n throw new ReplicationStatusException(\"update ReplicationStatus failed because of an unexpected exception\", e)\n } \n}\n</code></pre>\n\n<p>that's about my 2 cents </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T15:49:39.567", "Id": "19662", "ParentId": "19659", "Score": "7" } }, { "body": "<ol>\n<li><p>+1 to Alex and an improvement for Java 6: you could eliminate the <code>null</code> check in the <code>finally</code> block if you move the <code>DerbyDog.getResultSet</code> call before the <code>try</code> block. If it's inside the <code>try</code> block and it throws an exception you won't be able to <code>close</code> the <code>ResultSet</code> because the reference will remain <code>null</code>. <em>Guideline 1-2: Release resources in all cases</em> in the <a href=\"http://www.oracle.com/technetwork/java/seccodeguide-139067.html\" rel=\"nofollow noreferrer\">Secure Coding Guidelines for the Java Programming Language, Version 4.0</a> documentation could be helpful.</p></li>\n<li><p>The <code>catch</code> block is unnecessary here. Exceptions will be propagated without it.</p></li>\n<li><p>Be aware of static helper classes. <code>DerbyDog</code> seems one of them. You might find <a href=\"https://codereview.stackexchange.com/a/14361/7076\">my former answer about it</a> useful.</p></li>\n</ol>\n\n\n\n<pre><code>ResultSet resultSet = DerbyDog.getResultSet(strSelect);\ntry {\n if (resultSet.next()) {\n resultSet.updateString(COLUMN_STATUS, strStatus);\n resultSet.updateRow();\n }\n} finally {\n resultSet.close();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-07T20:06:22.760", "Id": "20245", "ParentId": "19659", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T12:04:20.740", "Id": "19659", "Score": "2", "Tags": [ "java", "exception" ], "Title": "Closing a ResultSet and rethrowing an Exception" }
19659
<p>What do you think about this?</p> <pre><code>#utils.py def is_http_url(s): """ Returns true if s is valid http url, else false Arguments: - `s`: """ if re.match('https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})(?:/[\w&amp;%?#-]{1,300})?',s): return True else: return False #utils_test.py import utils class TestHttpUrlValidating(unittest.TestCase): """ """ def test_validating(self): """ """ self.assertEqual(utils.is_http_url('https://google.com'),True) self.assertEqual(utils.is_http_url('http://www.google.com/r-o_ute?key=value'),True) self.assertEqual(utils.is_http_url('aaaaaa'),False) </code></pre> <p>Is this enough? I'm going to insert URLs into database. Are there other ways to validate it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T05:23:48.827", "Id": "64943", "Score": "0", "body": "I'd use [urlparse](http://docs.python.org/2/library/urlparse.html) in the standard library to check it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T19:58:55.057", "Id": "64944", "Score": "1", "body": "You can use the rfc3987 package. `rfc3987.match('http://http://codereview.stackexchange.com/', rule='URI')`" } ]
[ { "body": "<p>I would check out <a href=\"https://github.com/django/django/blob/master/django/core/validators.py\" rel=\"nofollow\">Django's validator</a> - I'm willing to bet it's going to be decent, and it's going to be very well tested.</p>\n\n<pre><code>regex = re.compile(\n r'^(?:http|ftp)s?://' # http:// or https://\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|' # domain...\n r'localhost|' # localhost...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|' # ...or ipv4\n r'\\[?[A-F0-9]*:[A-F0-9:]+\\]?)' # ...or ipv6\n r'(?::\\d+)?' # optional port\n r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n</code></pre>\n\n<p>This covers a few edge cases like IP addresses and ports. Obviously some stuff (like FTP links) you might not want to accept, but it'd be a good place to start.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-04T20:48:21.603", "Id": "356316", "Score": "0", "body": "This code example seems mostly copied from that SO answer. I think it should have proper attribution. https://stackoverflow.com/a/7160778/172132\n(Unlike the original answer this checks for IPv6 URLs, though.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T20:06:23.763", "Id": "19670", "ParentId": "19663", "Score": "2" } } ]
{ "AcceptedAnswerId": "19670", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T15:53:42.797", "Id": "19663", "Score": "3", "Tags": [ "python", "regex", "validation", "url", "http" ], "Title": "HTTP URL validating" }
19663
<p>So basically jqueryphp is a jQuery plugin that allows you to call any PHP function within client-side JavaScript: <a href="https://github.com/Xaxis/jqueryphp" rel="nofollow">jqueryphp@github</a></p> <p>I wrote it as a response to projects such as PHP.JS and other JavaScript emulated PHP function libraries. I realize that my solution will only be useful in contexts where latency is not much of an issue since each PHP function call requires an AJAX request and response. </p> <p>With that in mind, I'm extremely interested to hear if anyone thinks this plugin is a viable idea or not? And outside of the security implications, why?</p> <p>Also I'm interested in any possible optimizations I could make in any of my code?</p> <p><strong>Here's the frontend: jqueryphp.js</strong></p> <pre><code>(function( $ ) { var config = { 'path' : 'function_request.php' }; var methods = { /* * This method initializes the default path configuration * variable required to process any function requests. */ init : function( options ) { var settings = $.extend(config, options); }, /* * This method handles all calls to pre-existing PHP functions * regardless of whether they are native or user defined. */ call : function( func, callback ) { /* * We subtract 2 from the arglen variable so when building * our args string to pass to the server we are not sending * the func string or the callback object to be interpreted * as a argument to be passed to a PHP function. */ var self = this, arglen = arguments.length - 2, args = arguments; /* * Here we build a JSON object containing the arguments (if * any) to be passed to the PHP function. We offset our index * by 2 so we don't pass the function string or the callback * object to the server. */ var jsonObj = []; for (var i=0; i&lt;arglen; i++) { var argId = i + 2; jsonObj.push( args[argId] ); } /* * We stringify our arguments list to pass it through to * the server for processing. */ var args = JSON.stringify(jsonObj); /* * Finally the request object is built and sent to the server * for handling. */ var request = $.ajax({ url: config.path, type: "POST", data: {'method': 'call', 'func': func, 'args': args}, dataType: "text", success: function(data) { callback(data, self); } }); return this; }, /* * This method allows for running PHP code written within * JavaScript. */ exec: function( code, callback ) { var self = this; /* * Finally the request object is built and sent to the server * for handling. */ var request = $.ajax({ url: config.path, type: "POST", data: {'method': 'exec', 'code': code}, dataType: "text", success: function(data) { callback(data, self); } }); return this; } }; /* * So the user of this plugin doesn't have to constantly pass in * the 'call' parameter, being as how it will be the most used * method, for convenience we make it so it is assumed when no * method parameter string is passed the 'call' method is used. */ $.fn.php = function( method ) { if ( methods[method] ) { return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( method !== 'init' &amp;&amp; method !== 'exec' ) { return methods[ 'call' ].apply( this, Array.prototype.slice.call( arguments )); } else if ( typeof method === 'object' ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.php' ); } }; })( jQuery ); </code></pre> <p><strong>Here's the backend: func_request.php</strong></p> <pre><code>&lt;?php /* * While the jqueryphp plugin allows for the execution of * arbitrary code via the 'exec' method, this functionality * is disabled by default. The plugin request 'exec' uses * the eval() construct which is very dangerous. If it is * used pay special attention not to pass any user provided * data without proper validation in place. */ $config = array( 'EXEC' =&gt; false, 'SEC_MODE' =&gt; 'blacklist' ); /* * The blacklist array is used when the SEC_MODE configuration * variable is set to blacklist. In such a case all PHP functions * are allowed except those found in the array. */ $blacklist = array( '`', 'create_function', 'escapeshellcmd', 'exec', 'include', 'include_once', 'passthru', 'pcntl_exec', 'phpinfo', 'popen', 'require', 'require_once', 'shell_exec', 'system' ); /* * The whitelist array is used when the EXCLUSIVE configuration * variable is set to whitelist. In such a case all PHP functions are * disallowed except for those found in the array. */ $whitelist = array( // 'strlen', // (e.g. Allowing the strlen function) // 'highlight_string' // (e.g. Etc...) ); /* * The first data passed from the client is which method request * is being made. For instance are they making a 'call' to a PHP * function or are they attempting to run PHP code written in * JavaScript via 'exec'. */ $method_request = $_POST['method'] ? $_POST['method'] : false; if ( $method_request ) { switch ( $method_request ) { /* * This method handles all calls to pre-existing PHP functions * regardless of whether they are native or user defined. */ case 'call' : /* * We receive the function requested and arguments that * are to be passed to it. */ $func_request = $_POST['func'] ? $_POST['func'] : false; $func_args = $_POST['args'] ? $_POST['args'] : false; /* * Based on the EXCLUSIVE configuration variable we attempt to * build our function call. */ switch ( $config['SEC_MODE'] ) { case 'blacklist' : if ( function_exists($func_request) &amp;&amp; !in_array($func_request, $blacklist) ) { $function = $func_request; } else { $function = false; } break; case 'whitelist' : if ( function_exists($func_request) &amp;&amp; in_array($func_request, $whitelist) ) { $function = $func_request; } else { $function = false; } break; } /* * Next we take our $func_args which should contain a JSON * encoded string and convert it into a PHP associative array. */ $args_arr = json_decode($func_args, false); /* * If the user requested function exists and is allowed * we proceed to call that function, passing any arguments * given with the requested function. */ if ( $function !== false ) { $call = $function; echo call_user_func_array($call, $args_arr); } break; /* * This method handles the execution of user passed PHP strings * to the server. */ case 'exec' : if ( $config['EXEC'] === true ) { /* * We receive the code to be executed from the user. */ $code_string = $_POST['code'] ? $_POST['code'] : false; echo eval( $code_string ); } else { echo "Usage of the 'exec' method has been disabled."; } break; } } ?&gt; </code></pre> <p><strong>Here's a demo usage page:</strong> </p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; &lt;title&gt;jQuery PHP&lt;/title&gt; &lt;script type="text/javascript" src="lib/jquery-1.8.3.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="lib/jqueryphp.js"&gt;&lt;/script&gt; &lt;style&gt; body { margin:40px; } .results { border:1px dashed green; width:100%; margin-bottom:10px; } &lt;/style&gt; &lt;/head&gt; &lt;script&gt; $(document).ready(function() { // Initialize our path $.fn.php('init', {'path': 'http://www.mydomain.com/jqueryphp/lib/func_request.php'}); // Example of calling the PHP strlen() function $("#results1").php('strlen', function(data, self) { $(self).html(data); }, 'A test string!'); /* * Example of calling a disabled PHP function while also * demonstrating jQuery's method chaining is still in tact. */ $("#results2").php('phpinfo', function(data, self) { $(self).html(data); }).css({border: '1px dashed red'}); // Example of calling highlight_string() $("#results3").php('highlight_string', function(data, self) { $(self).html(data); }, "&lt;?php phpinfo(); ?&gt;"); /* * Example demonstrating the usage of jQuery.php's exec * method to pass PHP code to the backend and return the * result. This method is disabled by default. */ var code = "$a = 2; $b = 2; $c = $a + $b; echo $c;" $("#results4").php('exec', code, function(data, self) { $(self).html(data); }); }); &lt;/script&gt; &lt;body&gt; &lt;p&gt;&lt;b&gt;jQuery.php Demonstrations:&lt;/b&gt;&lt;/p&gt; Returned results from the PHP strlen() function &lt;div id="results1" class="results"&gt;&lt;/div&gt; Example of calling a disabled PHP function &lt;div id="results2" class="results"&gt;&lt;/div&gt; Returned results from the PHP strlen() function &lt;div id="results3" class="results"&gt;&lt;/div&gt; Returned results using jQuery.php's 'exec' method. &lt;div id="results4" class="results"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T17:52:13.940", "Id": "31479", "Score": "0", "body": "Use a whitelist instead of a blacklist. You **will** miss something important in the blacklist." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T17:53:08.587", "Id": "31480", "Score": "0", "body": "I appreciate the comment. I allow for the usage of either. Though I should probably rename the variable arrays that define those lists because the current naming convention I'm using is confusing." } ]
[ { "body": "<p>It's an interesting idea but I'm struggling to see any real-world use for it at such a simple level. Most of the relevant inbuilt PHP functions have javascript counterparts which would be preferred. For instance, there's no reason you'd ever want to use an ajax request just to do a string replace. </p>\n\n<p>In my opinion, to make this a beneficial and useful I'd like to be able to transparently call methods on PHP objects using javascript. var total = order.getTotal() for instance which would fire off a javascript request that, on the server did something like:</p>\n\n<pre><code>$order = new Order($_GET['id']);\nreturn $order-&gt;{$_GET['method']}();\n</code></pre>\n\n<p>Having said that, because of the nature of ajax requests and callbacks, I'm not sure you'll be able to create a clean enough interface to make it worthwhile.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T18:22:34.887", "Id": "31481", "Score": "0", "body": "One usage scenario that has been striking me as potentially interesting would be access to PHP GD functions or other graphics processing functions. As you say, most core PHP functions are indeed emulated in JavaScript and one can fairly easy go out and find those functions and include them in a JavaScript lib. With that said, perhaps it would simply be easier in some instances to just call whatever PHP function you like without finding the JS equivalent. \nI agree with your suggestion about a more transparent method of calling and using PHP within JavaScript. I've been looking into that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T18:31:46.363", "Id": "31482", "Score": "0", "body": "GD is a good example, but it would require you to maintain the reference to the image data between requests. You could do this with sessions but it would be horribly inefficient compared with using a standard javascript ajax call to a script which did everything in one go. You could use your code to call a user-defined function but this is essentially what sajax already did 6 years ago." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T18:38:34.220", "Id": "31483", "Score": "0", "body": "Yeah I've been on the fence regarding the practical applications of this little experiment. ... I guess I mainly wrote it because there are so many functions in PHP I'm always wanting to use when coding in JavaScript and I was getting tired of recreating or finding that equivalent code in JS. ... Anyhow, I appreciate your comments: they're definitely good food for thought. Cheers." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T18:17:02.743", "Id": "19666", "ParentId": "19664", "Score": "0" } }, { "body": "<p>I could see the sec_mode whitelist being useful for someone who wants a simple ajax controller. However, such a controller would not scale well with complexity, because one would only be able to modify functionality via adding/removing functions and parameters.</p>\n\n<p>The exec mode and sec_mode blacklist mode look impractical to secure, and they probably should not exist. For example, exec mode would enable someone to inspect the server configuration or execute infinite loops. Blacklist mode relies on the developer (1) to blacklist all of the possible unsafe functions on a given server configuration and library setup and (2) to update the blacklist as functions are added throughout the lifetime of the project.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T19:24:41.633", "Id": "31484", "Score": "0", "body": "Good thoughts and points. I agree entirely that the blacklist mode and exec mode are basically hugely impractical for production development. I just wanted to include that functionality for quick demonstration purposes. For example: it's easier to install the plugin and run a test on a function without requiring a user to first qualify that function in the whitelist. Perhaps instead of not existing I can just have the blacklist mode disabled by default like the exec mode is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T00:34:59.193", "Id": "31596", "Score": "0", "body": "No, you shouldn't do this. If the function can be enabled, it WILL be enabled by more inexperienced developers - and it is YOUR responsibility to let them know they will hurt themselves, because with the blacklist prefilled, you suggest that this will be safe because \"there is a blacklist\". Better not include this in any working software." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T19:16:27.537", "Id": "19668", "ParentId": "19664", "Score": "2" } }, { "body": "<p>You are doomed!</p>\n\n<p>Basically you try to allow an attacker to define which code should be executed, and you try to find out if you are smarter in detecting malicious code than him injecting and hiding it.</p>\n\n<p>The \"EXEC\" mode is completely insecure, we need not discuss this. But I doubt the blacklist mode is of good use either. I feel it to be insecure as well, but I cannot prove it in 5 minutes. For example, I can try to read any file on the webserver by calling <code>file_get_contents()</code>. I can try to overwrite any file by using <code>file_put_contents()</code>. I could install my multipurpose script this way that is called a second later, and you get owned.</p>\n\n<p>In the end, only the whitelist mode seems reasonably secure, but this is just a generalized form of AJAX RPC calling - and a very dumb one, because it is limited to single PHP functions, you cannot do anything more sophisticated.</p>\n\n<p>And if you really think about it: There are already plenty of working solutions to allow Ajax calls to do more useful stuff within one single call. Some of them are called \"restful webservice\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T00:31:35.750", "Id": "19759", "ParentId": "19664", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T17:33:45.823", "Id": "19664", "Score": "2", "Tags": [ "javascript", "php", "jquery" ], "Title": "Would a plugin for calling PHP functions within JavaScript prove useful?" }
19664
<p>For example, given a 2D array (a matrix):</p> <pre><code>{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}} </code></pre> <p>What are the solutions to find a number, such as 6?</p> <p>Here's the code I tried using binary search method:</p> <pre><code>int main(){ int sample[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 6; int lowX, highX, lowY, highY, midX, midY; //Note: some values are hardcoded, should not matter. lowX = 0; highX = 2; lowY = 0; highY = 3; if(target &lt;= sample[0][0] || target &gt;= sample[3 - 1][4 - 1]){ std::cout&lt;&lt;"Nope"; } while(lowX &lt;= highX &amp;&amp; lowY &lt;= highY){ midX = (lowX + highX)/2; midY = (lowY + highY)/2; if(target &lt; sample[midX][midY]){ highX = midX - 1; highY = midY - 1; } else if(target &gt; sample[midX][midY]){ lowX = highX + 1; lowY = highY + 1; } else { lowX = highX + 1; lowY = highY + 1; } } if(target == sample[midX][midY]){ std::cout&lt;&lt;"Found"; } else{ std::cout&lt;&lt;"Nope"; } return 0; } </code></pre> <p>Is this method optimal? What are the other possible solutions? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-16T17:25:09.097", "Id": "121896", "Score": "0", "body": "[Similarly finding an element in a matrix](http://www.writeulearn.com/element-sorted-2d-matrix/)" } ]
[ { "body": "<p>Binary search is typically the best you can do for this sort of thing, but only if you can assure that the data is ordered. You never mentioned that the data will appear presorted, but did give it as an example. If the data isn't sorted, this would be a linear search.</p>\n\n<p>How well a search performs depends a lot on what data you'll be dealing with. If your 2d array will never contain duplicates I would suggest a hash table.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T20:25:53.673", "Id": "19673", "ParentId": "19665", "Score": "0" } }, { "body": "<p>Have you actually tested your code (with numbers other than 6)? Because I doubt that can work.</p>\n\n<p>Firstly you have <code>lowX = highX + 1;</code> where it most likely should be <code>lowX = midX + 1;</code> (dito with <code>Y</code>).</p>\n\n<p>And more importantly, your code only adds or subtracts one from X and Y at the same time. There is no case where X and Y are changed independently from each other, thus making it impossible to navigate the whole matrix.</p>\n\n<p>I would suggest two alternative solutions:</p>\n\n<p>A) Run the binary search recursivly. First search the outer array for the inner element (array) that includes the sought number, then search that array.</p>\n\n<p>B) Logically map the two dimensional array to a simple array and search that, e.g. an index <code>i</code> on a simple array maps to the indexes <code>x = i/4</code> and <code>y = x%4</code> of the matrix.</p>\n\n<p>Questions: What is the use case for this? If the arrays are sorted like this, why use a matrix instead of a simple array? What is the logic behind using sub-arrays like this? Do you need the location of an element, or just if it's present or not?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T13:42:21.220", "Id": "19693", "ParentId": "19665", "Score": "1" } }, { "body": "<p>Given a matrix of size m*n; doing a two dimensional search will take, whether you try to do it at the same time or Row and column in order, O(log m + log n) steps. Which is equal to O(log (m*n)), that is the complexity of normal binary search in all elements. (which is not surprising really)</p>\n\n<p>Actually if the data is stored in a 2D array like <code>int sample[3][4]</code>, you can just cast it to a int array and do a STL <code>binary_search</code> on it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T11:53:52.497", "Id": "19734", "ParentId": "19665", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T18:15:25.357", "Id": "19665", "Score": "1", "Tags": [ "optimization", "c", "search", "binary-search", "matrix" ], "Title": "Searching for an element in a 2D array" }
19665
<p>I have a CakePHP function here that gets info for a twitter screen_name from the twitter api and writes it to a mysql db. I'm just looking for feedback about other ways to accomplish this that might be more efficient with fewer loops maybe. The challenge is, there are many screen_names that need to be processed for a $reportid before the "report" is considered done. Any feedback is very much appreciated. thanks.</p> <pre><code> function admin_wtfTwitter($reportid, $jobid) { $this-&gt;autoRender = false; //use if the api lags //set_time_limit(18000); //notify the log $this-&gt;admin_saveLog($reportid, $jobid, 'parsecrawlresults', 'Twitter wce started.'); //get the twitter channels from reportdetails $channels = $this-&gt;Reportdetail-&gt;getChannel($reportid, 4); //channel 4 = twitter foreach ($channels as $c) { //open reportdetail channel for writting $this-&gt;Reportdetail-&gt;create(); $this-&gt;Reportdetail-&gt;set(array('id' =&gt; $c['Reportdetail']['id'])); /* * small_tag is null --&gt; continue to next reportdetail record * small_tag is bad * small_tag is good but no data returned */ if ($c['Reportdetail']['small_tag'] == null) { $this-&gt;Reportdetail-&gt;set(array('done' =&gt; -1, 'note' =&gt; 'small_tag null')); $this-&gt;Reportdetail-&gt;save(); continue; } $uri = 'http://api.twitter.com/1/users/show.json?screen_name=' . $c['Reportdetail']['small_tag']; $data = @file_get_contents($uri); if($data === false) { unset($data); $this-&gt;Reportdetail-&gt;set(array('done' =&gt; -1, 'note' =&gt; 'small_tag bad')); $this-&gt;Reportdetail-&gt;save(); continue; } $content = json_decode($data, true); //set fans, title username $this-&gt;Reportdetail-&gt;set(array( 'fans' =&gt; $content['followers_count'], 'title' =&gt; $content['description'], 'username' =&gt; strtolower($content['screen_name']) )); //proceed with second api call**************************** unset($uri); unset($data); unset($content); $i = 0; $e = 0; $postmonths = array(); //LIMIT SET TO 1000 - CAN BE 3200 - https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline $uri = 'https://api.twitter.com/1/statuses/user_timeline.json?trim_user=true&amp;exclude_replied=true&amp;include_entities=true&amp;include_rts=true&amp;contributor_details=false&amp;count=1000&amp;screen_name=' . $c['Reportdetail']['small_tag']; $data = @file_get_contents($uri); if($data === false) { unset($data); $this-&gt;Reportdetail-&gt;set(array('done' =&gt; -1, 'note' =&gt; 'small_tag bad')); $this-&gt;Reportdetail-&gt;save(); continue; } $content = json_decode($data, true); //set engagement, posts foreach ($content as $t) { if (!empty($t['id_str'])) { $i++; $e = $e + $t['retweet_count']; array_push($postmonths, substr($t['created_at'], 4, 3)); //API resutls are: "created_at":"Fri Nov 30 00:38:34 +0000 2012 } } $this-&gt;Reportdetail-&gt;set(array( 'posts' =&gt; $i, 'engagements' =&gt; $e )); //get and set frequency $freq = $this-&gt;admin_calcFrequency($i, count(array_unique($postmonths))); $this-&gt;Reportdetail-&gt;set(array('frequency' =&gt; $freq)); //******************************************************** //we're done with this one $this-&gt;Reportdetail-&gt;set(array('done' =&gt; 1)); //commit the content to reportdetail record $this-&gt;Reportdetail-&gt;save(); } //notify the log $this-&gt;admin_saveLog($reportid, $jobid, 'parsecrawlresults', 'Twitter wce completed.'); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T11:43:33.830", "Id": "31498", "Score": "0", "body": "admin_wtfTwitter() function is doing too many things. you should split this and distribute the responsibilities." } ]
[ { "body": "<p>There are two fundamental principles I would like to point out: \"Don't Repeat Yourself\" (DRY) and Single Responsibility. The principles should be self explanatory from their names. The very first thing I notice is that you have a \"god\" function. In other words, a function that is trying to do everything. This violates both of these principles. DRY because the code cannot be easily reused; Single Responsibility because functions should do just one thing. To avoid this you should separate this one function into multiple smaller ones. The best way to do this is to try and determine each individual task you are trying to accomplish and separate accordingly. I'll leave that bit up to you.</p>\n\n<p>A small thing real quick before continuing. This is actually a method, not a function, and therefore the access modifier should be explicitly defined as <code>public</code>, <code>private</code>, or <code>protected</code> to avoid accidents. By default it resolves to the public scope, but you should not depend upon that.</p>\n\n<pre><code>public function admin_wtfTwitter() {\n</code></pre>\n\n<p>Internal comments are very detrimental to legibility and code size. You should avoid them except when debugging. If your code is self-documenting then most comments will become unnecessary and you will only need doccomments for the rest. Comments like \"notify the log\" or \"get the twitter channels\" should be inherently obvious from the context. If you do nothing else, removing these comments alone will dramatically increase overall legibility.</p>\n\n<p>You should also avoid (un)commenting out a feature to simulate different environments. If you have a feature that you will sometimes need to activate, you should create a switch in your function's arguments to handle it. For instance:</p>\n\n<pre><code>function admin_wtfTwitter( $reportid, $jobid, $lag = FALSE ) {\n if( $lag ) {\n set_time_limit( 180000 );\n }\n</code></pre>\n\n<p>Though I should caution that you shouldn't override your time limit like that. First of all, it makes your server hang while it waits for the task to finish. Second, it could mask a much larger problem, such as an infinite loop. If your program is doing so much that it can't finish, then that should be a sign that there is something wrong and you should fix it, not mask it. There are a number of different methods you can use: manually limit the initial amount of work, dynamically limit it by breaking it up into chunks, and caching results to name a few. There are probably more, but those are the ones I'm familiar with. The method you chose depends upon your situation.</p>\n\n<p>You should avoid single letter variables except when used in generic throw away values or incrementals. Using <code>$c</code> instead of <code>$channel</code> is rather abstract and can later lead to confusion, especially in larger chunks of code. The same can be said for non-common acronyms, in other words acronyms that are not HTML, PHP, etc...</p>\n\n<p>Whitespace is your friend and PHP never minds a little over-zealousness in its use. Never cram multiple statements onto one line, even if it is legible, but especially avoid it when its not. Having more than one level of indentation wont hurt. That being said you should be aware of the arrow anti-pattern and ensure you aren't violating it.</p>\n\n<pre><code>if( $channel[ 'Reportdetail' ] [ 'small_tag' ] == NULL ) {\n $this-&gt;Reportdetail-&gt;set( array(\n 'done' =&gt; -1,\n 'note' =&gt; 'small_tag null'\n ) );\n $this-&gt;Reportdetail-&gt;save();\n continue;\n}\n</code></pre>\n\n<p>Lets return to the first principle I mentioned: DRY. There are a few subtle aspects that are sometimes overlooked. Usually this principle is applied by breaking code up into functions or loops and most think that is enough. But it can also be used for something as simple as saving a reused array pointer to a variable. So, instead of continuously typing out <code>$c['Reportdetail']['small_tag']</code>, save that value to a variable, say <code>$small_tag</code> and use that instead. Later, should you decide to change the source or path, the initial value of the variable is the only line you will have to worry about.</p>\n\n<p>Continuing on this line of thought, if you are setting multiple values to a resource, then the best way is to do it all at once. Not only does this follow DRY, it also saves processing time. Currently you are using <code>$this-&gt;Reportdetail-&gt;set()</code> method repeatedly to set multiple attributes. Always avoid accessing or manipulating resources multiple times when at all possible.</p>\n\n<pre><code>$attributes = array(\n 'id' =&gt; $channel[ 'Reportdetail' ] [ 'id' ]\n);\n\nif( $small_tag == NULL ) {\n $attributes[ 'done' ] = -1;\n $attributes[ 'note' ] = 'small_tag null';\n\n $this-&gt;Reportdetail-&gt;set( $attributes );\n $this-&gt;Reportdetail-&gt;save();\n continue;\n}\n</code></pre>\n\n<p>You can even go one step farther and create a \"default\" state. For example, if the <code>$small_tag</code> is NULL or bad the \"done\" attribute is set to \"-1\" and there is a \"note\" attribute. So if we set up our <code>$attributes</code> array with the null values as a default, we can manipulate or unset attributes as necessary. This sometimes even allows us to remove an if statement if done right.</p>\n\n<pre><code>$attributes = array(\n 'id' =&gt; $channel[ 'Reportdetail' ] [ 'id' ],\n 'done' =&gt; -1,\n 'note' =&gt; 'small_tag null'\n);\n\n$uri = \"http://api.twitter.com/1/users/show.json?screen_name=$small_tag\";\n$data = file_get_contents( $uri );\nif( $data === FALSE ) {\n if( $small_tag ) {\n $attributes[ 'note' ] = 'small_tag bad';\n }\n\n $this-&gt;Reportdetail-&gt;set( $attributes );\n $this-&gt;Reportdetail-&gt;save();\n continue;\n}\n\n$attributes[ 'done' ] = 1;\nunset( $attributes[ 'note' ] );\n</code></pre>\n\n<p>There are a few things I want to point out about what I demonstrated above. The most noticeable is the new if statement structure. If we assume that <code>file_get_contents()</code> will return FALSE if <code>$small_tag</code> is NULL then we can reuse the set/save/continue for both \"bad\" statements, all we have to do is apply the proper \"note\" depending upon the value of <code>$small_tag</code>. There shouldn't be any noticeable difference in processing time as it should immediately fail, but you may want to check that.</p>\n\n<p>Something a little less noticeable is the removal of the error suppressor <code>@</code>. First of all, you should never use the error suppressor. You should always explicitly check for errors and handle them. However, it isn't even necessary here. <code>file_get_contents()</code> only throws errors if using the maxlength or offset arguments, neither of which you are. The only \"bad\" return you have to worry about is a FALSE one.</p>\n\n<p>Another not so obvious change is the removal of the <code>unset( $data );</code> line. Micromanaging memory like this is unnecessary. The benefit is so negligible as to be nearly useless and the added clutter detracts from even that small appeal. The only reason to unset a value is if you may end up using it later and don't want it to have a value first. If you are in a loop and the next iteration of that loop automatically overwrites the previous values, then unsetting is unnecessary. This includes unsetting <code>$uri</code> and <code>$content</code>.</p>\n\n<p>The final thing I wanted to point out is that you are recreating a boolean by using numerical TRUE/FALSE values with your \"done\" attribute. The difference between using an actual boolean and a pseudo-boolean is small but the abstractness can cause confusion. You should just use a real boolean unless absolutely necessary.</p>\n\n<p>The rest is more of the same. There's only one last thing I noticed, and it goes along with what I said about the arrow anti-pattern earlier: Watch for unnecessary indentation. If you can reverse an if statement to reduce the amount of indented code then do so. For example:</p>\n\n<pre><code>foreach( $content as $t ) {\n if( empty( $t[ 'id_str' ] ) ) { \n continue;\n }\n\n //etc...\n}\n</code></pre>\n\n<p>Hope this helps</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T17:34:24.877", "Id": "31733", "Score": "0", "body": "mseancole, I really appreciate the comments. I will digest them over the break. Thanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T19:43:34.967", "Id": "19821", "ParentId": "19667", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T18:48:40.567", "Id": "19667", "Score": "2", "Tags": [ "php", "mysql", "api", "cakephp" ], "Title": "Is there a better way to loop through records and call an api?" }
19667
<p>To start with Common Lisp I am doing Project Euler using this language. Usually I manage to solve problems but I am quite sure that my code is not as efficient as it could be in Common Lisp. That is why I need a review from experienced lispers.</p> <p>This is my code for <a href="http://projecteuler.net/problem=35" rel="nofollow">problem 35</a>. Please offer any improvements.</p> <pre><code>(defun prime-p (n) (cond ((= n 1) nil) ((= n 2) t) ((evenp n) nil) (t (loop for i from 3 to (isqrt n) by 2 never (zerop (mod n i)))))) (defun list-&gt;num (lst) (loop for i in lst for p = (- (length lst) 1) then (- p 1) sum (* i (expt 10 p)))) (defun num-&gt;list (n) (loop for c across (write-to-string n) collect (parse-integer (string c)))) (defun rotate (lst) (append (last lst) (butlast lst))) (defun number-rotations (n) (let* ((digits (num-&gt;list n)) (digits-count (length digits))) (loop repeat digits-count for rotated = digits then (rotate rotated) collect (list-&gt;num rotated)))) (defun problem-35 (limit) (let ((hash-primes (make-hash-table))) (loop for n from 1 to limit if (prime-p n) do (setf (gethash n hash-primes) t)) (loop for p being the hash-keys in hash-primes if (loop for n in (number-rotations p) always (gethash n hash-primes)) collect p))) </code></pre>
[]
[ { "body": "<p>In <code>list-&gt;num</code> you can count down with something like <code>for i downfrom n</code>.</p>\n\n<pre><code>(defun num-&gt;list (n)\n (loop for c across (write-to-string n)\n collect (parse-integer (string c))))\n</code></pre>\n\n<p>In above function you can just collect <code>(digit-char-p c)</code>. The function returns the digit value as a number.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T17:36:33.973", "Id": "19701", "ParentId": "19669", "Score": "4" } }, { "body": "<p>Consider giving common lisp some optimizing hints. Adding a single <code>(declare (fixnum n)</code> takes the runtime (on my machine) of <code>(euler-35 1000000)</code> from 1.2 seconds to 0.83 seconds:</p>\n\n<pre><code>(defun prime-p (n)\n (declare (fixnum n))\n (cond\n ((= n 1) nil)\n ((= n 2) t)\n ((evenp n) nil)\n (t (loop for i from 3 to (isqrt n) by 2\n never (zerop (mod n i))))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-12T07:12:47.523", "Id": "116529", "ParentId": "19669", "Score": "1" } }, { "body": "<p>If you treat primes below 1,000,000, memorize primes below 1,000.\nUse strings in rotation operation.</p>\n\n<pre><code>(defun print-rotation (number)\n (let* ((str (format nil \"~a\" number))\n (strstr (concatenate 'string str str)))\n (loop for i below (length str) do\n (format t \"~a~%\" (parse-integer (subseq strstr i (+ i (length str))))))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T07:07:13.527", "Id": "200025", "ParentId": "19669", "Score": "1" } } ]
{ "AcceptedAnswerId": "19701", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T19:45:20.107", "Id": "19669", "Score": "4", "Tags": [ "programming-challenge", "lisp", "common-lisp" ], "Title": "Project Euler #35 in Common Lisp" }
19669
<p>I'm trying to figure out a pattern to best accommodate this pretty ugly code:</p> <pre><code>var userDiscounts = _discountRepository.GetUserDiscountsForUsersWithDiscounts(new List&lt;int&gt; { buyerUserId, sellerUserId }).ToList(); // Buyer. var buyerHasFreeCommission = false; var buyerDiscounts = userDiscounts.Where(ud =&gt; ud.UserId == buyerUserId); foreach(var userDiscount in buyerDiscounts) { switch (userDiscount.Discount.Type) { case DiscountTypes.SingleFreeCommisionPerUser: buyerHasFreeCommission = true; break; } } var sellerHasFreeCommission = false; var sellerDiscounts = userDiscounts.Where(ud =&gt; ud.UserId == sellerUserId); foreach(var userDiscount in sellerDiscounts) { switch (userDiscount.Discount.Type) { case DiscountTypes.SingleFreeCommisionPerUser: sellerHasFreeCommission = true; break; } } if (!sellerHasFreeCommission) { var sellerCommisionChargeTransaction = new Transaction { AccountId = sellerAccountId, Type = TransactionTypes.Fee, Amount = -2 }; var sellerTransferFeeTransaction = new Transaction { AccountId = 5020, Type = TransactionTypes.Fee, Amount = 2 }; _accountRepository.AddTransaction(sellerCommisionChargeTransaction); _accountRepository.AddTransaction(sellerTransferFeeTransaction); } if (!buyerHasFreeCommission) { var buyerCommisionChargeTransaction = new Transaction { AccountId = buyerAccountId, Type = TransactionTypes.Fee, Amount = -2 }; var buyerTransferFeeTransaction = new Transaction { AccountId = 5020, Type = TransactionTypes.Fee, Amount = 2 }; _accountRepository.AddTransaction(buyerCommisionChargeTransaction); _accountRepository.AddTransaction(buyerTransferFeeTransaction); } if (!buyerHasFreeCommission || !sellerHasFreeCommission) _accountRepository.SaveChanges(); </code></pre> <p>This won't be very maintainable when I need to add a new discount... I was thinking maybe somehow I could use the strategy pattern?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T23:54:39.033", "Id": "31488", "Score": "1", "body": "Did you forgot to finish your sentence?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T01:07:17.563", "Id": "31489", "Score": "0", "body": "Haha, yes I did I was having trouble sending the questions..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T06:14:48.740", "Id": "31492", "Score": "0", "body": "Please describe what will change if a new discount is added" } ]
[ { "body": "<p>You can filter all the data needed right from repository, and then iterate over collection containing required elements only:</p>\n\n<pre><code>var usersWithoutSingleFreeCommision = _discountRepository\n .GetUserDiscountsForUsersWithDiscounts(new List&lt;int&gt; { buyerUserId, sellerUserId })\n .GroupBy(ud =&gt; ud.UserId)\n .Where(g =&gt; g.All(ud =&gt; ud.Discount.Type != DiscountTypes.SingleFreeCommisionPerUser))\n .Select(g =&gt; g.Key)\n .ToArray();\n\n//you might already have this mapping somewhere. Otherwise just cache it in readonly field\nvar accountIdMapping = new Dictionary&lt;int, int&gt; { { buyerUserId, buyerAccountId }, { sellerUserId, sellerAccountId } };\n\nforeach (var userId in usersWithoutSingleFreeCommision)\n{\n var commisionChargeTransaction = new Transaction\n {\n AccountId = accountIdMapping[userId],\n Type = TransactionTypes.Fee,\n Amount = -2\n };\n\n var transferFeeTransaction = new Transaction\n {\n AccountId = 5020,\n Type = TransactionTypes.Fee,\n Amount = 2\n };\n\n _accountRepository.AddTransaction(commisionChargeTransaction);\n _accountRepository.AddTransaction(transferFeeTransaction);\n}\n\n//you can remove this check as usually SaveChanges() is always called. It just makes the life easier\nif (usersWithoutSingleFreeCommision.Any())\n _accountRepository.SaveChanges();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T22:59:42.910", "Id": "19677", "ParentId": "19672", "Score": "1" } }, { "body": "<p>Put the contents, or all of each if and foreach into their own functions. Unit test the functions. Put everything else into small functions too. </p>\n\n<p>In the end your main function should read like a small story:</p>\n\n<pre><code>var buyerHasFreeCommision = GetBuyerFreeCommision(userDiscouts);\nif (buyerHasFreeCommision) AddBuyerFees(userDiscounts);\nvar sellerHasFreeCommision = GetSellerFreeCommision(userDiscounts);\nif (seller...)\n</code></pre>\n\n<p>If you do this, you'll probably see some pattern emerge.\nI can already see two classes, or rather instances of a- instead of one. Maybe something like Strategy?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T09:26:06.843", "Id": "19689", "ParentId": "19672", "Score": "0" } }, { "body": "<p>The strategy pattern is a good candidate for this, one way you could implement it would be something like as follows (the discounts are the strategies).</p>\n\n<p>Define an interface for classes which can apply discounts:</p>\n\n<pre><code>public interface IApplyDiscount\n{\n void Apply(buyerUserId, buyerTransaction, sellerUserId, sellerTransaction);\n}\n</code></pre>\n\n<p>Create an implementation of the interface for the <code>SingleFreeCommisionPerUser</code> discount.</p>\n\n<pre><code>public class SingleFreeCommisionPerUserDiscount : IApplyDiscount\n{\n public void Apply(buyerUserId, buyerTransaction, sellerUserId, sellerTransaction)\n {\n var userDiscounts = _discountRepository.GetUserDiscountsForUsersWithDiscounts(new List&lt;int&gt; { buyerUserId, sellerUserId }).ToList();\n\n var buyerHasFreeCommission = userDiscounts.Any(ud =&gt; ud.UserId == buyerUserId &amp;&amp; ud.Discount.Type == DiscountTypes.SingleFreeCommisionPerUser);\n\n if(buyerHasFreeCommission)\n {\n buyerTransaction.Amount = 0;\n }\n\n var sellerHasFreeCommission = userDiscounts.Any(ud =&gt; ud.UserId == buyerUserId &amp;&amp; ud.Discount.Type == DiscountTypes.SingleFreeCommisionPerUser);\n\n if(sellerHasFreeCommission)\n {\n sellerTransaction.Amount = 0;\n }\n }\n}\n</code></pre>\n\n<p>The main code then creates the initial commission transactions:</p>\n\n<pre><code>var sellerCommisionChargeTransaction = new Transaction\n{\n AccountId = sellerAccountId,\n Type = TransactionTypes.Fee,\n Amount = -2\n};\n\nvar buyerCommisionChargeTransaction = new Transaction\n{\n AccountId = buyerAccountId,\n Type = TransactionTypes.Fee,\n Amount = -2\n};\n</code></pre>\n\n<p>Applies all the available discounts:</p>\n\n<pre><code>List&lt;IApplyDiscount&gt; discounts = GetAllDiscounts();\ndiscounts.ForEach(d =&gt; d.Apply(buyerUserId, buyerCommisionChargeTransaction, sellerUserId, sellerCommisionChargeTransaction));\n</code></pre>\n\n<p>Then, only add the corresponding charge if a transaction amount is due.</p>\n\n<pre><code>if (sellerCommisionChargeTransaction.Amount &lt; 0)\n{\n var sellerTransferFeeTransaction = new Transaction\n {\n AccountId = 5020,\n Type = TransactionTypes.Fee,\n Amount = -sellerCommisionChargeTransaction.Amount\n };\n\n _accountRepository.AddTransaction(sellerCommisionChargeTransaction);\n _accountRepository.AddTransaction(sellerTransferFeeTransaction);\n}\n\nif (buyerCommisionChargeTransaction.Amount &lt; 0)\n{\n var buyerTransferFeeTransaction = new Transaction\n {\n AccountId = 5020,\n Type = TransactionTypes.Fee,\n Amount = -buyerCommisionChargeTransaction.Amount\n };\n\n _accountRepository.AddTransaction(buyerCommisionChargeTransaction);\n _accountRepository.AddTransaction(buyerTransferFeeTransaction);\n}\n</code></pre>\n\n<p>Then if you want to add other discount types and rates, you can just create additional <code>IApplyDiscount</code> implementations and include them in the results of the <code>GetAllDiscounts()</code> call.</p>\n\n<p>This implementation is more flexible, you don't need to change any of the current implementation to add additional discounts.</p>\n\n<p>The discounts could be percentages and the corresponding <code>TransferFeeTransaction</code> will cater for that by charging the positive value of whatever amount remains on the <code>CommissionChargeTransaction</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T10:57:19.117", "Id": "19691", "ParentId": "19672", "Score": "2" } } ]
{ "AcceptedAnswerId": "19691", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T20:21:39.863", "Id": "19672", "Score": "5", "Tags": [ "c#", "design-patterns" ], "Title": "Does this ugly code fit into a design pattern?" }
19672
<p>I'm a code banger from way back trying to learn good Python style. Here is my attempt at the classic game. I'm trying to learn Tk, because I have a couple codes that need GUIs. Any suggestions or comments?</p> <pre><code>from tkinter import * import random # use a class definition to hold all my functions class MyApp(Tk): def __init__(self): """ initialize the frame and widgets""" #load Tk Tk.__init__(self) #make a frame fr = Frame(self) #intialize operation buttons and the label self.player_button = Button(self, text="Me", command=lambda: self.do_start(TRUE), font=("Helvetica", 16)) self.computer_button = Button(self, text="Computer", command=lambda: self.do_start(FALSE), font=("Helvetica", 16)) self.exit_button = Button(self, text="Exit", command=self.do_exit, font=("Helvetica", 16)) self.again_button = Button(self, text="again?", command=self.do_again, state=DISABLED, font=("Helvetica", 16)) self.myLabel = Label(self, text="Who starts?", font=("Helvetica", 16)) #initialize a list to use for my field buttons (note: 0 is not used) self.bList = [0,1,2,3,4,5,6,7,8,9] #use a loop to build my field buttons for i in range(1,10): self.bList[i] = Button(self, text="---", #bList now button references command=lambda j=i: self.do_button(j), state=DISABLED, relief=RAISED, height=3, width=7, font=("Helvetica", 24)) #grid everything into the frame fr.grid() self.myLabel.grid(row=0, columnspan=4) self.player_button.grid(row=1, column=0) self.computer_button.grid(row=1, column=2) self.exit_button.grid(row=5, column=0) self.again_button.grid(row=5, column=2) #use a loop to grid the field buttons myL = [[1,4,0], [2,4,1], [3,4,2], #button number, row, column [4,3,0], [5,3,1], [6,3,2], [7,2,0], [8,2,1], [9,2,2]] for i in myL: self.bList[i[0]].grid(row=i[1], column=i[2]) def do_start(self,player): """start the game, if player is TRUE, player make first move""" #turn Me, computer, and again? buttons off self.player_button.config(state=DISABLED) self.computer_button.config(state=DISABLED) self.again_button.config(state=DISABLED) #reset the bState and mySums lists and the flags self.bState = [10,0,0,0,0,0,0,0,0,0] #state of button 1-player -1-comp 0-open self.mySums = [0,0,0,0,0,0,0,0] #sums of rows, columns and diagonals self.gameDone = FALSE self.specialDefense = FALSE #turn the field buttons on for i in range(1,10): self.bList[i].config(state=NORMAL) #if player is true the player starts otherwise the computer starts self.myLabel.config(text="You are X, make a move") if player: self.turn = FALSE else: self.turn = TRUE self.do_move() def do_button(self, i): """handle a field button click""" #i is the number of the button that was pushed note: 1 through 9 # if turn is true the computer made a move otherwie player if self.turn: myText = "-0-" self.turn = FALSE self.bState[i] = -1 else: myText = "-X-" self.turn = TRUE self.bState[i] = 1 #Disable the ith button and test if we are done self.bList[i].config(text=myText, state=DISABLED) self.test_done() # if it is the computer's turn and the game is not over make a move if (self.turn) and (not self.gameDone): self.do_move() def test_done(self): """test if the game is over""" #if there is not a 0 in bstate the game is done if not (0 in self.bState): self.myLabel.config(text="Draw, game over!") self.gameDone = TRUE self.again_button.config(state=NORMAL) #after doing sums look for 3 or -3 to find if there was a winner self.do_sums() if 3 in self.mySums: #note 3 in mySums means player has won self.myLabel.config(text="You won!") self.gameDone = TRUE self.again_button.config(state=NORMAL) elif -3 in self.mySums: #note -3 in mySums means computer has won self.myLabel.config(text="Computer won!") self.gameDone = TRUE self.again_button.config(state=NORMAL) def do_sums(self): """put a list of the various row, column, and diagonal sums in mySums""" triples = [[1,2,3], [4,5,6], [7,8,9], #rows [1,4,7], [2,5,8], [3,6,9], #columns [1,5,9], [3,5,7]] #diagonals count = 0 for i in triples: self.mySums[count] = 0 for j in i: self.mySums[count] += self.bState[j] count += 1 def do_move(self): """computer picks a move to make""" #mix it up a little by starting with the center for first move sometimes if (not 1 in self.bState) and (not -1 in self.bState): #i.e. first move if random.random() &lt; 0.20: #20% of the time start in center self.do_button(5) return #handle the case where player as made first move to a corner if (1 in self.bState) and (not -1 in self.bState): if self.bState.index(1) in [1,3,7,9]: self.do_button(5) self.specialDefense = TRUE return #test if computer can win, if so do the move for i in range(1,10): if self.bState[i] == 0: self.bState[i] = -1 #make a trial move self.do_sums() if -3 in self.mySums: #note -3 means computer has won self.do_button(i) #make move if a win return else: self.bState[i] = 0 #switch back of not a win #test if player can win, if so block for i in range(1,10): if self.bState[i] == 0: self.bState[i] = 1 #make a trial move self.do_sums() if 3 in self.mySums: #note 3 in bState means player has won self.do_button(i) #block if player could win self.specialDefense = FALSE #special defense no longer needed return else: self.bState[i] = 0 #switch back of not a win #for the second special defense move, pick a side (if not already done) if self.specialDefense: self.specialDefense = FALSE sides = [2,4,6,8] random.shuffle(sides) #shuffle them so people don't get as bored for i in sides: if self.bState[i] == 0: self.do_button(i) return #pick a corner if open corners = [1,3,7,9] random.shuffle(corners) #shuffle them so people don't get as bored for i in corners: if self.bState[i] == 0: self.do_button(i) return #take center if open if self.bState[5] == 0: self.do_button(5) return #pick a side if open sides = [2,4,6,8] random.shuffle(sides) #shuffle them so people don't get as bored for i in sides: if self.bState[i] == 0: self.do_button(i) return def do_again(self): """reset everything to play again""" #reset my buttons and change the label self.player_button.config(state=NORMAL) self.computer_button.config(state=NORMAL) self.myLabel.config(text="Who starts?") #disable the field buttons for i in range(1,10): self.bList[i].config(text="---", state=DISABLED) def do_exit(self): """destroy the frame when exit is pushed""" root.destroy() # end of MyApp class if __name__ == '__main__': root = MyApp() root.title("Carl's Tic Tac Toe") root.mainloop() </code></pre> <hr> <p>In response to the answers:</p> <p>I see the point about starting from 0. Is there a better way to do this? Part of the reason I did the buttons in a loop is that they all have the same formats. With this code I have the potential of having my first button different than the others.</p> <pre><code>num_buttons = 9 self.bList = [Button(#arguments)] for i in range(1, num_buttons) self.bList.append(Button(#arguments)) </code></pre> <p>Since writing this I have now learned that making the first definition empty works i.e.,</p> <pre><code>num_buttons = 9 self.bList = [] for i in range(num_buttons) self.bList.append(Button(#arguments)) </code></pre>
[]
[ { "body": "<p><strong>Lambda Usage</strong></p>\n\n<p>I'm not a great fan of the lambda usage to create what are effectively partially applied functions in the <code>self.player_button</code> and <code>self.computer_button</code>. Instead I'd rather do something like:</p>\n\n<pre><code>import functools\nself.player_button = Button(self, text=\"Me\",\n command=functools.partial(self.do_start, TRUE),\n font=(\"Helvetica\", 16))\n</code></pre>\n\n<p>This makes the intent more clear in my eyes.</p>\n\n<p><strong>List Buttons</strong></p>\n\n<p>You create a list of integers in <code>self.bList = [0,1,2,3,4,5,6,7,8,9]</code> and then immediately assign buttons to it. 10 is also a bit of a <em>magic number</em> here, so I'd replace it with something like:</p>\n\n<pre><code>num_buttons = 9\nself.bList = [0]\nfor i in range(num_buttons):\n self.bList.append(Button(#arguments))\n</code></pre>\n\n<p>Better still would just be dealing with 0 offsets, instead of having a <code>0</code> at the start and then indexing from 1. Keep everything as uniform as possible. It makes other parts of the program simpler as well:</p>\n\n<pre><code>for i in range(1,10):\n self.bList[i].config(state=NORMAL)\n</code></pre>\n\n<p>can simply be:</p>\n\n<pre><code>for button in self.bList:\n button.config(state=NORMAL)\n</code></pre>\n\n<p><strong>Lists</strong></p>\n\n<p><code>self.mySums = [0,0,0,0,0,0,0,0]</code> is more clearly written as <code>self.mySums = [0]*8</code></p>\n\n<p><strong>Style</strong></p>\n\n<p>Try and stick to one variable naming style; there's <code>self.player_button</code> and <code>self.myLabel</code> for example. Doesn't really matter which one you pick, but consistency is key. Method names are probably a bit anaemic, things like <code>do_button</code> and <code>do_again</code> really need more descriptive names - do what with a button? Do what again?</p>\n\n<p>Finally, TRUE should be <code>True</code> and likewise FALSE should be <code>False</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T05:54:49.303", "Id": "19684", "ParentId": "19683", "Score": "6" } }, { "body": "<p>Avoid using:</p>\n\n<pre><code>from _____ import *\n</code></pre>\n\n<p>I believe it violates the zen of python:</p>\n\n<blockquote>\n <p><em>Explicit is better than implicit.</em></p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T23:10:56.737", "Id": "31642", "Score": "1", "body": "Could you also explain why its a bad idea?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T21:07:57.730", "Id": "31739", "Score": "1", "body": "Two advantages that I have found about keeping things explicit (1) keeping the namespace clean i.e., not having a lot of unused definitions, and (2) being clear on where you are getting particular definitions. For example, there could be several definitions of classes with the same name in different modules. If so what happens?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-15T18:44:36.327", "Id": "114996", "Score": "0", "body": "tkinter is one of the very few modules [that are allowed](https://docs.python.org/2/library/tkinter.html#a-simple-hello-world-program) to do this import style." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T06:03:14.440", "Id": "19685", "ParentId": "19683", "Score": "0" } } ]
{ "AcceptedAnswerId": "19684", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T03:48:00.813", "Id": "19683", "Score": "11", "Tags": [ "python", "game", "gui" ], "Title": "Tic Tac Toe game GUI" }
19683
<p>I am reading lot of articles regarding memory leaks. But i am not sure about below code. I usually do coding in this way. Can anyone tell me, will they leak memory?</p> <p>I have doubts in following 3 scenarios (marked them in code).</p> <p>I got these suspects after reading this <a href="http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/" rel="nofollow">post</a></p> <pre><code>var orderDetails = $("&lt;root/&gt;"); function GetOrderDetais() { $.ajax( { url: url, dataType: 'xml', data: someThing, dataType: 'text', type: 'POST', contentType: "text/xml; charset=utf-8", success:function(value) //1 - closure function refrencing global variable { orderDetails = $(value); orderDetails.find("header").each(function() //2 - closure function refrencing global variable { //loop through order header details and do some DOM appends here. }); ShowOrderDetails(); }, error:function(jqXHR, textStatus, errorThrown) { alert("Error" + textStatus + " ==&gt; " + errorThrown); }, }); } function ShowOrderDetails() { var orderNum = orderDetails.find("header oNum").text(); $(orderDetails).find("item").each(function() //3 - closure function refrencing outer variable { //loop through item details and do some DOM appends here to form table. //one intresting statement. $("div").append($(this).find("itemNum").text() + " - " + orderNum); }); } </code></pre> <blockquote> <p><strong>Update:</strong></p> <p>See this <a href="http://vimeo.com/45140516#" rel="nofollow">Video</a> to learn about memory leake.</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T11:58:10.780", "Id": "31499", "Score": "0", "body": "There is no such thing a memory leaks in JavaScript. However there can be memory leaks in JavaScript **implementations** of browsers due to bugs. But these are very different from browser to browser - even between minor versions. Usually a JS developer doesn't need to worry about memory leaks, unless they have error reports about memory problems in a specific browser - and even then these are usually fixed quite quickly by the browser manufacturer (except older IE versions). Do you have concrete memory/performance problems in specific browsers? If not, you shouldn't worry about it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T12:16:53.647", "Id": "31501", "Score": "2", "body": "@RoToRa. No. javascipt can be suffered by memory leaks due to poor coding. There are lot of articles available in internet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T13:48:08.127", "Id": "31503", "Score": "0", "body": "Show me one. I think you (or the articles) are not referring to memory leaks, but inefficient memory usage - a completely different thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T04:53:09.033", "Id": "31544", "Score": "0", "body": "@RoToRa check out this [link](http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/)" } ]
[ { "body": "<p>No, there is nothing you're doing in that code that would result in memory leaks.</p>\n\n<p>I found an article written by Jack Slocum (creator of the ExtJS framework) that details some basic steps to follow to avoid memory leaks. The original article is a bit dated and browsers have gotten a lot better at cleaning up memory, so I don't know how much of it still applies to the latest browsers (it certainly applies to older versions of IE and Firefox).</p>\n\n<p>Here is the article: <a href=\"http://maxthonuser.blogspot.com/2008/02/easy-steps-to-avoid-javascript-memory.html\" rel=\"nofollow\">http://maxthonuser.blogspot.com/2008/02/easy-steps-to-avoid-javascript-memory.html</a></p>\n\n<p>Relevant text (in case the link ever dies):</p>\n\n<blockquote>\n <p>It's as simple as these 3 steps:</p>\n \n <ol>\n <li><p>Never put anything in a DOM expando or property other than a primitive value unless you plan on cleaning it up.\n This is the most important rule of all. It may seem convenient to put your JS object in a DOM expando, so you can $() and get it, but don't do it. Sure, I know what you are thinking, I am being a little paranoid. There are lots of instances where putting a JS Object in a DOM expando won't cause a leak. That's true, but there are also many that will... some which are not so easy to detect (i.e. closures). So to avoid the possibility all together, I follow this simple rule.</p></li>\n <li><p>Clean up all your DOM event handlers on unload if there's a chance they could reference a DOM object.\n There's no reason to manually do this when there are libraries that do it automatically. I use YAHOO.util.Event for all my event handlers, it handles this for me automagically. Other libraries (prototype, dojo, etc) have some sort of mechanism to do the same thing, although I'm not sure how effective they are. If you look at the leak images above once again, you will notice almost all of them are in event related code of those libraries.</p></li>\n <li><p>Set your XMLHttpRequest onreadystatechange handlers to null when you are done with them.\n I use YAHOO.util.Connect for all my XHR connections and it uses a polling mechanism instead of readstate, so I don't need to do this anymore. If you can switch to YAHOO.util.Connect (or YAHOO.ext.UpdateManager built on top of it), I'd recommend it.</p></li>\n </ol>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T22:44:53.833", "Id": "19714", "ParentId": "19686", "Score": "2" } }, { "body": "<p>I can't find any reason for your global variable.</p>\n\n<p>As far as I can see, it is declared and overridden in the success handler of your ajax request. So why not declearing it inside the success handler?</p>\n\n<p>Next: </p>\n\n<p>Why didn't you use a parameter in </p>\n\n<pre><code>function ShowOrderDetails(orderDetails)\n</code></pre>\n\n<p>so you could pass your orderDetails easily from your success handler to the function. No reference to a global object needed - or better: no need for a global object at all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-16T01:17:30.057", "Id": "27445", "ParentId": "19686", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T07:44:42.810", "Id": "19686", "Score": "3", "Tags": [ "javascript", "jquery", "memory-management" ], "Title": "Will this kind of codes leak memory?" }
19686
<p>I have written a basic image upload function that handles up to five file inputs, intended to be hosted live on the internet very soon.</p> <p>As far as I know it's secure and works well (minus checking the range of the first 100 bytes and looking for magic numbers), but please tell me if you can see any flaws or areas where I can improve this function.</p> <pre><code>&lt;?php function fihHomeIndex() { global $conf, $DBH; if ($_SERVER['REQUEST_METHOD'] == 'POST') { $errors = array(); if (empty($_POST['adult'])) { $errors[] = 'Please choose whether this image is ADULT content or family safe!'; } else { if ($_POST['adult'] == 'yes' || $_POST['adult'] == 'no') { } else { $errors[] = 'Possible hacking attempt. Upload aborted.'; } } if ($spamIP = isSpamIP($_SERVER['REMOTE_ADDR'])) { $errors[] = 'Sorry, your IP is listed in one of the spammer lists we use.'; } if (count($errors) &gt;= 1) { fihDisplayHead(); fihDisplayFirstColumn(); fihDisplayError($errors); fihDisplayFoot(); } else { $upload_errors = array(); $empty_fields = 0; $fields_submitted = count($_FILES['fihImageUpload']['name']); foreach ($_FILES['fihImageUpload']['name'] as $index =&gt; $name) { if ($_FILES['fihImageUpload']['error'][$index] == 4) { $empty_fields++; } } $all_fields_empty = ($fields_submitted == $empty_fields) ? true : false; if ($all_fields_empty) { fihDisplayHead(); fihDisplayFirstColumn(); fihDisplayError('Please choose atleast one file to upload!'); fihDisplayFoot(); } else { $files_to_process = $fields_submitted; // TODO if a image was rejected due to an error, the script may // break if it tries to process a empty $_FILES array.. // print_r($_FILES); foreach ($_FILES['fihImageUpload']['name'] as $index =&gt; $name) { if ($_FILES['fihImageUpload']['error'][$index] == 4) { $files_to_process--; continue; } if ($_FILES['fihImageUpload']['error'][$index] == 0) { if (filesize($_FILES['fihImageUpload']['tmp_name'][$index]) &gt; 5242880) { $upload_errors[] = htmlspecialchars($name) . ' exceeded file size limit.'; $files_to_process--; continue; } } if (false !== ($fileInfo = @getimagesize($_FILES['fihImageUpload']['tmp_name'][$index]))) { if (strrchr($_FILES['fihImageUpload']['name'][$index], '.') == FALSE) { $upload_errors[] = 'Files must have an extension.'; $files_to_process--; continue; } elseif (!in_array(substr(strrchr($_FILES['fihImageUpload']['name'][$index], '.'), 1), $conf['upload']['file_types']) || !in_array($fileInfo['mime'], $conf['upload']['mime_types'])) { $upload_errors[] = htmlspecialchars($name) . ' is not an image.'; $files_to_process--; continue; } } else { $upload_errors[] = htmlspecialchars($name) . ' is not an image.'; $files_to_process--; continue; } } if (count($upload_errors) &gt; 0 || $files_to_process == 0) { fihDisplayHead(); fihDisplayFirstColumn(); fihDisplayError($upload_errors); fihDisplayFoot(); die(); } else { foreach ($_FILES['fihImageUpload']['name'] as $index =&gt; $name) { $orig_name = sanitize(explode('.', $_FILES['fihImageUpload']['name'][$index])[0]) . '.' . explode('.', $_FILES['fihImageUpload']['name'][$index])[1]; $new_name = sanitize(explode('.', $_FILES['fihImageUpload']['name'][$index])[0]) . '_' . time() . '.' . explode('.', $_FILES['fihImageUpload']['name'][$index])[1]; # Upload the file first if (move_uploaded_file($_FILES['fihImageUpload']['tmp_name'][$index], $conf['storage']['folder'] . 'full/' . $new_name)) { $ii = getimagesize($conf['storage']['folder'] . 'full/' . $new_name); # Second tell the database that we uploaded a file if (!$DBH-&gt;query("INSERT INTO `".$conf['db']['table_prefix']."images` (`image_id`, `image_orig_filename`, `image_filename`, `image_adult`) VALUES (NULL, '" . $orig_name . "', '" . $new_name . "', '" . $_POST['adult'] . "');")) { die('Database error'); } $li = $DBH-&gt;insert_id; $image_ext = $ii[0] . 'x' . $ii[1]; $image_size = filesize($conf['storage']['folder'] . 'full/' . $new_name); createThumbnail($new_name, $conf['storage']['folder'] . 'thumb/', 200, 200, $li); if (!$DBH-&gt;query("INSERT INTO `".$conf['db']['table_prefix']."images_meta` (`meta_id`, `image_id`, `image_ext`, `image_size`) VALUES (NULL, '" . $li . "', '" . $image_ext . "', '" . $image_size . "');")) { die('Database error'); } $template_info[$index] = array( 'thumb_url' =&gt; $conf['storage']['url'] . 't/' . $li, 'image_absolute_url' =&gt; $conf['storage']['url'] . 'f/' . $li, 'image_page_url' =&gt; $conf['base_url'] . 'view-image/' . $li, 'filename' =&gt; $orig_name ); $sti = base64_encode(serialize($template_info)); header('Location: ' . $conf['base_url'] . 'upload-success/' . $sti); } } } } } } else { # Display the header fihDisplayHead(); # Display the first column, which contains a login form and social networking tools fihDisplayFirstColumn(); # Display the upload section fihDisplayUpload(); # Footer fihDisplayFoot(); } } ?&gt; </code></pre> <p>The function is <a href="https://gist.github.com/4316786" rel="nofollow" title="The function is located here">located here</a></p>
[]
[ { "body": "<p>Immediately I see globals. Avoid globals at all cost. Strike them from your memory. You will never need them. Ever. Globals are one of the worst things PHP has ever done. It is not always obvious when a variable is a global thus it is very easy to miss and sometimes impossible to trace. It is also really easy to change the value of a global from anywhere, either maliciously or accidentally, meaning they are insecure and definitely shouldn't be used with something as important as a database handle.</p>\n\n<p>Instead you should inject those variables into your function as arguments. You can even use type hinting to ensure the right kinds of arguments are passed. The below function requires a <code>$conf</code> array and a <code>$DBH</code> PDO resource. If the wrong variable type is passed the program will immediately fail. This is just one way to ensure that your application can do what you expect it to do.</p>\n\n<pre><code>function fihHomeIndex( Array $conf, PDO $DBH ) {\n</code></pre>\n\n<p>The next thing I noticed is the heavy level of indentation. Heavy indentation is bad because it reduces legibility. There is an anti-pattern that explains this. The arrow anti-pattern simply states that excessively indented code, illustrated as code that comes to points like arrows, is bad form and should be avoided. Though I should point out that the arrow shapes are unnecessary, it is the heavy indentation that is important. There are a number of ways to avoid violating this principle, chief among them is avoiding unnecessary if/else statements, not using else statements when unnecessary, and breaking from if statements early if possible.</p>\n\n<p>The following block of code reverses the logic of your original, unused, if statement and removes the else. The if statement was unnecessary because it wasn't being used, but without it the else could not be used, thus the reversal of the logic.</p>\n\n<pre><code>if( $_POST[ 'adult' ] != 'yes' &amp;&amp; $_POST[ 'adult' ] != 'no' ) {\n $errors[] = 'Possible hacking attempt. Upload aborted.';\n}\n</code></pre>\n\n<p>The above if statement can then be combined with the parent else statement to create an else-if statement. This removed two levels of indentation and unnecessary code.</p>\n\n<pre><code>if( empty( $_POST[ 'adult' ] ) ) {\n //etc...\n} else if( $_POST[ 'adult' ] != 'yes' &amp;&amp; $_POST[ 'adult' ] != 'no' ) {\n //etc...\n}\n</code></pre>\n\n<p>You should avoid assigning variables in statements. There are some exceptions, such as in loops, but for the most part it is considered bad form as it is easily missed during debugging. PHP allows it and doesn't know any better, but it could just as easily have been meant to be a comparison rather than assignment and there is no way to know other than with context. However, in the below instance a variable is not even necessary as you are not using it except as an expression. Just comparing the return value of the function is enough.</p>\n\n<pre><code>//proper way to define variables before validating\n$spamIP = isSpamIP( $_SERVER[ 'REMOTE_ADDR' ] );\nif( $spamIP ) {\n\n//if variable wont be used\nif( isSpamIP( $_SERVER[ 'REMOTE_ADDR' ] ) ) {\n</code></pre>\n\n<p>Let's look at a fundamental principle, \"Don't Repeat Yourself\" (DRY). As the name implies your code should not repeat itself. I've only scanned your code at this point, but already I have noticed some repetition. Let's look at it in its simplest form first, I'll return to the other aspects as they come up. When you have an array and you are pointing at a specific value inside of it and you need to use that value multiple times, you can assign that value to a variable. This has many benefits, first being that you don't have to type out that path again and again and another being that should that path change you will only have to change it once. For example:</p>\n\n<pre><code>$names = $_FILES[ 'fihImageUpload' ] [ 'name' ];\n$fields_submitted = count( $names );\n\nforeach( $names as $index =&gt; $name) {\n //etc...\n}\n</code></pre>\n\n<p>When you need the boolean value of an expression, you don't need to explicitly set it, you can just set the value of the variable to the return value of the expression. It is already a boolean. However, this is unnecessary. As mentioned above, you do not need to set a variable if you are not going to use it. Just use the expression in the if statement.</p>\n\n<pre><code>//without the ternary it is the same\n$all_fields_empty = $fields_submitted == $empty_fields;\n//just declare in if statement\nif( $fields_submitted == $empty_fields ) {\n</code></pre>\n\n<p>Let's return to the DRY principle. When you have a chunk of code that is repeated in multiple parts of your application then you should either find some way to refactor it so it only exists once, or you should create a function to perform that task for you. Let's create a function real quick.</p>\n\n<pre><code>function render( $content ) {\n fihDisplayHead();\n fihDisplayColumn();\n fihDisplayError( $content );\n fihDisplayFoot();\n}\n\n//now in fihHomeIndex()\nif( count( $errors ) &gt;= 1 ) {\n render( $errors );\n}\n</code></pre>\n\n<p>Sometimes you can violate DRY simply by repeating something unnecessarily. For example: At the very beginning you looped over the <code>$names</code> to determine which files had errors and incremented a counter. Now you are looping over the same array and performing the same check to determine if a file should be skipped. If you unset said file in the first loop it will be unnecessary to perform the check again. So let's modify the first loop.</p>\n\n<pre><code>foreach( $names as $index =&gt; $name) {\n if( $_FILES[ 'fihImageUpload' ] [ 'error' ] [ $index ] == 4 ) {\n //$empty_fields++;//unnecessary\n unset( $names[ $index ] );\n }\n}\n</code></pre>\n\n<p>Now, with the above modification the <code>$empty_fields</code> incremental is unnecessary as we can now just check to see if <code>$names</code> array is empty. This also means that the <code>$files_to_process</code> incremental will be unnecessary.</p>\n\n<pre><code>//all fields empty\nif( empty( $names ) ) {\n</code></pre>\n\n<p>Of course we are still repeating our loop, and those are the worst things to repeat as they take up so much memory (relatively). Let's look at a neat little built in function of PHP called <code>array_diff_key()</code>. With this function we can input two arrays and get a returned array of the difference between their keys. The best part about this function is that it wont include any of the extra keys that may exist in the second array that don't also exist in the first. It uses the first array as a template.</p>\n\n<pre><code>$names = $_FILES['fihImageUpload' ] [ 'name' ];\n$errors = $_FILES[ 'fihImageUpload' ] [ 'error' ];\n\n$difference = array_diff_key( $names, $errors );\nif( empty( $difference ) ) {\n</code></pre>\n\n<p>Let's look at another fundamental principle. The Single Responsibility Principle is the one that is most being violated here. Remember the function, <code>render()</code>, we created earlier? Notice how it is easy to determine what that that function is doing. Its short, sweet, and does exactly what it says it does. That's what this principle is all about. Functions should do one thing. So look at your function and try and see what all it is doing. Quite a bit. Try breaking your function up into multiple smaller functions. This will also aid in following the DRY and arrow anti-pattern.</p>\n\n<p>There's probably a lot more I can go into, but this should be a good start.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T21:30:26.707", "Id": "19826", "ParentId": "19687", "Score": "6" } } ]
{ "AcceptedAnswerId": "19826", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T08:58:45.933", "Id": "19687", "Score": "2", "Tags": [ "php", "php5" ], "Title": "Image upload script in PHP" }
19687
<p>I am very new to programming and this is my first functional code. It works fine but I'm sure that I could use a lot of optimization. If you see any blunders or would be able to help condense the script that would be fantastic.</p> <pre><code>#!/usr/bin/python import sys, getopt, subprocess, os, tempfile, shutil, time file_name = sys.argv[2] pwd = os.getcwd() + "/" dirname = pwd + "Secretome_files" file_location = dirname + '/' try: os.makedirs(dirname) except OSError: if os.path.exists(dirname): pass else: raise def singleline(): print "\nMaking fasta single line" file_in = sys.argv[1] file_out = open(file_location + file_name + "singleline.fasta", "w") command = ("fasta_formatter -i " + file_in + " -w 0") p1 = subprocess.Popen((command), stdout=file_out, shell=True) p1.wait() print "Fasta now single line" def signalp(): singleline() command = ("signalp -f short -m " + file_location + file_name + "removed_SigPep.fasta " + file_location + file_name + "singleline.fasta &gt; "+ file_location + file_name + "signalpOUT.txt") print "\nRunning SignalP" signalpRUN = subprocess.Popen([command], shell=True) signalpRUN.wait() print "SignalP Complete" print "\nCreating SignalP protein list" command2 = ("fasta_formatter -i " + file_location + file_name + "removed_SigPep.fasta -t") file_out2 = open(file_location + file_name + "removed_SigPep_tab.fasta.txt", "w") tab = subprocess.Popen([command2], stdout=file_out2, shell=True) tab.wait() command3 = ("cut -f1,1 " + file_location + file_name + "removed_SigPep_tab.fasta.txt") file_out3 = open(file_location + file_name + "listaftercut.txt", "w") file_out4 = open(file_location + file_name + "goodlistSigP.txt", "w") listGood = subprocess.Popen([command3], stdout=file_out3, shell=True) listGood.wait() openfile = open(file_location + file_name + "listaftercut.txt", 'r') for line in openfile: goodname = line.partition(' ')[0] + '\n' file_out4.write(goodname) def sigpFasta(): command4 = ("faSomeRecords " + file_location + file_name + "singleline.fasta " + file_location + file_name + "goodlistSigP.txt " + file_location + file_name + "signalP_pass.fasta") print "\nRetreving SignalP fasta" fastaRUN = subprocess.Popen([command4], shell=True) fastaRUN.wait() def tmhmm(): command = ("tmhmm " + file_location + file_name + "removed_SigPep.fasta") file_out = open(file_location + file_name + "tmhmmOUT.txt", "w") print "\nRunning tmhmm on mature signalp sequences only" tmhmmRUN = subprocess.Popen([command], stdout=file_out, shell=True) tmhmmRUN.wait() print "tmhmm complete" print "\nIdentifying sequences without tm regions." openfile = open(file_location + file_name + "tmhmmOUT.txt", "r") file_out2 = open(file_location + file_name + "tmhmmGoodlist.txt", "a") for line in openfile: if "\tPredHel=0\t" in line: goodname = line.partition('\t')[0] + '\n' file_out2.write(goodname) def targetp(): command = ("targetp -N " + file_location + file_name + "signalP_pass.fasta") file_out = open(file_location + file_name + "targetpOUT.txt", "w") print "\nRunning TargetP on SignalP pass seqeunces only" targetpRUN = subprocess.Popen([command], stdout=file_out, shell=True) targetpRUN.wait() print "TargetP complete" print "\nIdentifying sequences that are secreated." lines = open(file_location + file_name + 'targetpOUT.txt').readlines() open(file_location + file_name + 'targetpOUT_parse.txt', 'w').writelines(lines[8:-2]) openfile = open(file_location + file_name + "targetpOUT_parse.txt", "r") file_out2 = open(file_location + file_name + "targetpGoodlist.txt", "a") for line in openfile: if "S" in line: goodname = line.partition(' ')[0] + '\n' file_out2.write(goodname) def wolfpsort(): command = ("runWolfPsortSummary fungi &lt; " + file_location + file_name + "singleline.fasta") file_out = open(file_location + file_name + "wolfPsortOUT.txt", "w") file_out2 = open(file_location + file_name + "wolfPsortErrorLog.txt", "w") print "\nRunning WoLFPSORT" wolfRUN = subprocess.Popen([command], stdout = file_out, stderr=file_out2, shell=True) wolfRUN.wait() print "WoLFPSORT complete" lines = open(file_location + file_name + 'wolfPsortOUT.txt').readlines() open(file_location + file_name + 'wolfPsortOUT_parse.txt', 'w').writelines(lines[1:]) file_out2 = open(file_location + file_name + "wolfPsortGoodlist.txt", "a") searchValue = "extr" f = open(file_location + file_name + "wolfPsortOUT_parse.txt", "r+b") for line in f: if line.split()[1] == searchValue: goodname = line.partition(' ')[0] + '\n' file_out2.write(goodname) def secretome(): file1 = set(line.strip() for line in open(file_location + file_name + "goodlistSigP.txt")) file2 = set(line.strip() for line in open(file_location + file_name + "tmhmmGoodlist.txt")) file3 = set(line.strip() for line in open(file_location + file_name + "targetpGoodlist.txt")) file4 = set(line.strip() for line in open(file_location + file_name + "wolfPsortGoodlist.txt")) newfile = open(file_location + file_name + "secretome_pass.txt", "w") for line in file1 &amp; file2 &amp; file3 &amp; file4: if line: newfile.write(line + '\n') def secFasta(): command = ("faSomeRecords " + file_location + file_name + "singleline.fasta " + file_location + file_name + "secretome_pass.txt " + file_name + "secretome_pass.fasta") print "\nRetreving Secretome fasta" fastaRUN = subprocess.Popen([command], shell=True) fastaRUN.wait() print "\nSecretome identification Complete" signalp() sigpFasta() tmhmm() targetp() wolfpsort() secretome() secFasta() exit(0) </code></pre>
[]
[ { "body": "<p>Can you explain what your program is supposed to do? You should put your function calls in a main function and just call main():</p>\n\n<pre><code> if __name__ == 'main':\n main()\n</code></pre>\n\n<p>Also use one line per import and put function definitions under the imports. You might want to read about pep8. Additionally I noticed that your variable names aren't very informative. Indexing your variables should be avoided and use more descriptive names to keep it more readable.\nYou can rewrite secretome() much shorter \"file1=\", \"file2=\" etc is almost the same code except one filename. To simplify things filenames should be all lowercase in case you want to do operations on them later with another program or script. Put your Try/Except in a function and name the function accordingly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T20:50:55.763", "Id": "31528", "Score": "0", "body": "This is a pipeline for protein sequence analysis. It uses widely available prediction programs and parses the results to identify proteins with specific functions. I will have to work on getting a main() function put together." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T14:57:10.100", "Id": "19696", "ParentId": "19695", "Score": "4" } }, { "body": "<pre><code>#!/usr/bin/python\n\nimport sys, getopt, subprocess, os, tempfile, shutil, time\n\nfile_name = sys.argv[2]\npwd = os.getcwd() + \"/\"\ndirname = pwd + \"Secretome_files\"\nfile_location = dirname + '/'\n</code></pre>\n\n<p>Use the function <code>os.path.join</code> to create paths rather then adding the <code>/</code> yourself. </p>\n\n<pre><code>try:\n os.makedirs(dirname)\nexcept OSError:\n if os.path.exists(dirname):\n pass\n else:\n raise\n</code></pre>\n\n<p>Instead do something like this:</p>\n\n<pre><code>except OSError as error:\n if error.errno != errno.ENOENT:\n raise\n</code></pre>\n\n<p>This way you check the error code, which can already tell you whether it failed because the file already existed.</p>\n\n<pre><code>def singleline(): \n print \"\\nMaking fasta single line\"\n file_in = sys.argv[1]\n</code></pre>\n\n<p>I recommend passing command line arguments in as parameters rather then fetching them here.</p>\n\n<pre><code> file_out = open(file_location + file_name + \"singleline.fasta\", \"w\") \n</code></pre>\n\n<p>You should really close this file after you are done with it</p>\n\n<pre><code> command = (\"fasta_formatter -i \" + file_in + \" -w 0\") \n</code></pre>\n\n<p>Those parens do nothing</p>\n\n<pre><code> p1 = subprocess.Popen((command), stdout=file_out, shell=True)\n</code></pre>\n\n<p>The parens do nothing here.</p>\n\n<pre><code> p1.wait() \n</code></pre>\n\n<p>You could use the function subprocess.check_call, which will take care of doing the wait, it'll also raise an exception if the program has an error which might be useful.</p>\n\n<pre><code> print \"Fasta now single line\"\n\ndef signalp():\n singleline() \n</code></pre>\n\n<p>Stylistically, I'd have the function singline return the location of its output file, and then use that here.</p>\n\n<pre><code> command = (\"signalp -f short -m \" + file_location + file_name + \"removed_SigPep.fasta \" + file_location + file_name + \"singleline.fasta &gt; \"+ file_location + file_name + \"signalpOUT.txt\")\n</code></pre>\n\n<p>Adding strings isn't very efficient. For subprocess, it makes the most sense to create a list of parameters and pass that the Popen constructor.</p>\n\n<pre><code> print \"\\nRunning SignalP\" \n signalpRUN = subprocess.Popen([command], shell=True) \n</code></pre>\n\n<p>Why do you use the <code>&gt;</code> syntax here where you passed a file object earlier? I'd recommend being consistent.</p>\n\n<pre><code> signalpRUN.wait() \n print \"SignalP Complete\"\n\n print \"\\nCreating SignalP protein list\"\n command2 = (\"fasta_formatter -i \" + file_location + file_name + \"removed_SigPep.fasta -t\")\n file_out2 = open(file_location + file_name + \"removed_SigPep_tab.fasta.txt\", \"w\")\n tab = subprocess.Popen([command2], stdout=file_out2, shell=True)\n tab.wait()\n</code></pre>\n\n<p>Your doing this basic idea several times. Write a function that takes the command line and the output file and does the execution.</p>\n\n<pre><code> command3 = (\"cut -f1,1 \" + file_location + file_name + \"removed_SigPep_tab.fasta.txt\")\n file_out3 = open(file_location + file_name + \"listaftercut.txt\", \"w\") \n file_out4 = open(file_location + file_name + \"goodlistSigP.txt\", \"w\") \n</code></pre>\n\n<p>Wait to open this until you are using it</p>\n\n<pre><code> listGood = subprocess.Popen([command3], stdout=file_out3, shell=True)\n listGood.wait()\n openfile = open(file_location + file_name + \"listaftercut.txt\", 'r')\n</code></pre>\n\n<p>I suggest using the <code>with open() as file:</code> syntax to make sure files get closed. </p>\n\n<pre><code> for line in openfile:\n goodname = line.partition(' ')[0] + '\\n'\n file_out4.write(goodname)\n</code></pre>\n\n<p>The output for this file would be better in its own function.</p>\n\n<pre><code>def sigpFasta(): \n command4 = (\"faSomeRecords \" + file_location + file_name + \"singleline.fasta \" + file_location + file_name + \"goodlistSigP.txt \" + file_location + file_name + \"signalP_pass.fasta\")\n print \"\\nRetreving SignalP fasta\" \n fastaRUN = subprocess.Popen([command4], shell=True) \n fastaRUN.wait()\n\ndef tmhmm(): \n command = (\"tmhmm \" + file_location + file_name + \"removed_SigPep.fasta\")\n file_out = open(file_location + file_name + \"tmhmmOUT.txt\", \"w\")\n print \"\\nRunning tmhmm on mature signalp sequences only\"\n tmhmmRUN = subprocess.Popen([command], stdout=file_out, shell=True)\n tmhmmRUN.wait()\n</code></pre>\n\n<p>Another place to use that function. Also, rather then all the print chatter, I suggest having it print the commands its executing.</p>\n\n<pre><code> print \"tmhmm complete\"\n print \"\\nIdentifying sequences without tm regions.\"\n openfile = open(file_location + file_name + \"tmhmmOUT.txt\", \"r\")\n file_out2 = open(file_location + file_name + \"tmhmmGoodlist.txt\", \"a\")\n for line in openfile:\n if \"\\tPredHel=0\\t\" in line: \n goodname = line.partition('\\t')[0] + '\\n'\n file_out2.write(goodname)\n</code></pre>\n\n<p>Rather then reopenning and appending to Goodlist a bunch of times, I suggest one function that opens each of the files you pull from and writes them. That way you only have to open the Godolist once.</p>\n\n<pre><code>def targetp():\n command = (\"targetp -N \" + file_location + file_name + \"signalP_pass.fasta\")\n file_out = open(file_location + file_name + \"targetpOUT.txt\", \"w\")\n print \"\\nRunning TargetP on SignalP pass seqeunces only\"\n targetpRUN = subprocess.Popen([command], stdout=file_out, shell=True)\n targetpRUN.wait()\n print \"TargetP complete\"\n\n print \"\\nIdentifying sequences that are secreated.\"\n\n lines = open(file_location + file_name + 'targetpOUT.txt').readlines()\n open(file_location + file_name + 'targetpOUT_parse.txt', 'w').writelines(lines[8:-2])\n\n openfile = open(file_location + file_name + \"targetpOUT_parse.txt\", \"r\")\n file_out2 = open(file_location + file_name + \"targetpGoodlist.txt\", \"a\") \n for line in openfile: \n if \"S\" in line: \n goodname = line.partition(' ')[0] + '\\n'\n file_out2.write(goodname)\n</code></pre>\n\n<p>This is very very similiar each time. Looking into writing a single function that can do it.</p>\n\n<pre><code>def wolfpsort():\n command = (\"runWolfPsortSummary fungi &lt; \" + file_location + file_name + \"singleline.fasta\")\n file_out = open(file_location + file_name + \"wolfPsortOUT.txt\", \"w\")\n file_out2 = open(file_location + file_name + \"wolfPsortErrorLog.txt\", \"w\") \n print \"\\nRunning WoLFPSORT\"\n wolfRUN = subprocess.Popen([command], stdout = file_out, stderr=file_out2, shell=True)\n wolfRUN.wait()\n print \"WoLFPSORT complete\"\n\n lines = open(file_location + file_name + 'wolfPsortOUT.txt').readlines()\n open(file_location + file_name + 'wolfPsortOUT_parse.txt', 'w').writelines(lines[1:])\n\n file_out2 = open(file_location + file_name + \"wolfPsortGoodlist.txt\", \"a\")\n\n searchValue = \"extr\"\n f = open(file_location + file_name + \"wolfPsortOUT_parse.txt\", \"r+b\")\n for line in f:\n if line.split()[1] == searchValue: \n goodname = line.partition(' ')[0] + '\\n'\n file_out2.write(goodname)\n\ndef secretome():\n file1 = set(line.strip() for line in open(file_location + file_name + \"goodlistSigP.txt\"))\n file2 = set(line.strip() for line in open(file_location + file_name + \"tmhmmGoodlist.txt\"))\n file3 = set(line.strip() for line in open(file_location + file_name + \"targetpGoodlist.txt\"))\n file4 = set(line.strip() for line in open(file_location + file_name + \"wolfPsortGoodlist.txt\"))\n</code></pre>\n\n<p>It'd be a good idea to have a global constant for these various filenames. You could also use a function that factor out the duplication here.</p>\n\n<pre><code> newfile = open(file_location + file_name + \"secretome_pass.txt\", \"w\")\n for line in file1 &amp; file2 &amp; file3 &amp; file4:\n if line:\n newfile.write(line + '\\n')\n\ndef secFasta():\n command = (\"faSomeRecords \" + file_location + file_name + \"singleline.fasta \" + file_location + file_name + \"secretome_pass.txt \" + file_name + \"secretome_pass.fasta\") \n print \"\\nRetreving Secretome fasta\" \n fastaRUN = subprocess.Popen([command], shell=True) \n fastaRUN.wait() \n print \"\\nSecretome identification Complete\"\n\nsignalp()\nsigpFasta()\ntmhmm()\ntargetp()\nwolfpsort()\nsecretome()\nsecFasta()\n</code></pre>\n\n<p>I would suggest having a main function that looks like this this:</p>\n\n<pre><code>def main():\n command([\"myprogram\",\"-t\",\"-w\", sys.argv[1]], output = 'the_outputfile')\n command(...)\n command(...)\n my_processing_function()\n my_other_function()\n</code></pre>\n\n<p>I think that would make the logic easier to read. </p>\n\n<pre><code>exit(0)\n</code></pre>\n\n<p>Doesn't really have an effect, because it'll exit with an error code of 0 by default anyways.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T20:45:51.813", "Id": "31526", "Score": "0", "body": "Thanks for all the input! The reason that I had to use \">\" a few times is because the program I'm calling required it over stdin and stdout. I did try to avoid that but couldn't get it working without the \">\". When you say 'Adding strings isn't very efficient. For subprocess, it makes the most sense to create a list of parameters and pass that the Popen constructor' Can you give me an example what your talking about? I also thought I could create a general subprocess command but I wasn't sure how to do that so I just did each one explicitly. I'll work on improving this. Thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T02:17:34.247", "Id": "31537", "Score": "0", "body": "@ian_informatics, you can do: `subprocess.Popen([\"prog\",\"arg1\",\"arg2\"])` Python will take care of joining them together for the shell command as if you'd done \"prog arg1 arg2\". It makes for simpler code not to do that part yourself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-09T04:17:29.540", "Id": "196233", "Score": "0", "body": "Also in many places you are not following python naming conventions. `snake_case` for variables and functions, `SHOUTCASE` for constants." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T15:12:53.420", "Id": "19697", "ParentId": "19695", "Score": "6" } }, { "body": "<p>The single thing that immediately jumps out at me is that there is not a single comment within the entire program. Break up the blocks of code with a few comments explaining <em>why</em> your code is doing what it is doing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T20:48:07.837", "Id": "31527", "Score": "0", "body": "I wanted to get it working before I made comments. That is something I'm adding now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T18:21:32.303", "Id": "19703", "ParentId": "19695", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T14:34:22.033", "Id": "19695", "Score": "5", "Tags": [ "python", "file", "bioinformatics", "child-process" ], "Title": "FASTA file processing using Python to invoke external filters" }
19695
<p>I humbly submit the following for critique. This was my final project for an Intro To Java Programming class ("handed-in" already, I can't make changes).</p> <p>The abundant commenting is required by the professor.</p> <blockquote> <p>Design and implement a stringed musical instrument class using the following guidelines:</p> <ol> <li><p>Data fields for your instrument should include number of strings, an array of string names representing string names (e.g. E,A,D,G), and <code>boolean</code> fields to determine if the instrument is tuned, and if the instrument is currently playing. You are welcome to add additional data fields if you like.</p></li> <li><p>A constructor method that set the tuned and currently playing fields to false.</p></li> <li><p>Other methods</p> <ol> <li>to tune the instrument</li> <li>to start the instrument playing</li> <li>to stop the instrument from playing.</li> </ol></li> <li><p>Other methods as you see fit (Add at least one unique method).</p></li> </ol> <p>Write the output from your <code>Instrument</code> class methods to a text file that a user entered from the command line arguments (e.g. java Mynamep3tst myfilename.txt). This allows your program to accept filenames from the user via a command line argument.</p> </blockquote> <p>The <code>Guitar</code> class:</p> <pre><code>//data fields include all required by assignment plus numberOfGuitars and numberOfTwelveStringGuitars private int numberOfStrings = 6; private static int numberOfGuitars = 0, numberOfTwelveStringGuitars = 0; StringPackage stringPackage = new StringPackage("guitar", 6); private boolean tuned = false; private boolean playing = false; //simple constructor, built with tuned and playing false public Guitar(){ numberOfGuitars++; } //constructor for different number of strings //same basic build re: tuning and playing public Guitar(int numberOfStrings) throws IOException{ this.numberOfStrings = numberOfStrings; stringPackage = new StringPackage("guitar", numberOfStrings); if(numberOfStrings == 12) numberOfTwelveStringGuitars++; } //displays string notes using methods in StringPackage class public void viewStringPackage(Guitar thisGuitar) throws IOException { String notes = thisGuitar.stringPackage.Notes(); StringPackage.comboPrint("The strings on this guitar are: " + notes + "\n"); } //method to find out how many strings a particular guitar has public int getNumberOfStrings() { return numberOfStrings; } //this is my unique method per assignment instructions public static int getNumberOfGuitars(){ return numberOfGuitars; } //this too public static int getNumberOfTwelveStringGuitars() { return numberOfTwelveStringGuitars; } //method to determine if Guitar is tuned public boolean isTuned() { return tuned; } //method to tune Guitar public void tune() throws IOException { StringPackage.comboPrint("The Guitar is tuned." + "\n"); tuned = true; } //method to see if Guitar is playing public boolean isPlaying() { return playing; } //method to start Guitar playing public void play() throws IOException { StringPackage.comboPrint("The Guitar is now playing." + "\n"); playing = true; } //method to stop Guitar playing public void stopPlay() throws IOException{ StringPackage.comboPrint("The Guitar is no longer playing." + "\n"); playing = false; } }//class </code></pre> <p>The <code>StringPackage</code> class:</p> <pre><code>public class StringPackage { //data fields include a String[] to hold string names as per the assignment private static final String GUITAR = "guitar", VIOLIN = "violin"; String[] stringArray; //builds the StringPackage for each instrument //can be amended to include new instruments as they're built //don't know how to throw exceptions yet so this will have to do as a substitute public StringPackage(String typeOfInstrument, int numberOfStrings) { if(numberOfStrings == 6 &amp;&amp; typeOfInstrument.equalsIgnoreCase(GUITAR)){ String temp = "E A D G B E"; stringArray = temp.split(" "); }//6 string else if(numberOfStrings == 12 &amp;&amp; typeOfInstrument.equalsIgnoreCase(GUITAR)){ String temp ="E E A A D D G G B B E E"; stringArray = temp.split(" "); }//12 string else if (numberOfStrings == 4 &amp;&amp; typeOfInstrument.equalsIgnoreCase(VIOLIN)){ String temp = "G D A E"; stringArray = temp.split(" "); }//violin else System.out.println("***Exception! " + numberOfStrings + " string "+ typeOfInstrument + " has not been created yet!***"); }//StringPackage //.length method to for use in loops, etc. public int length(){ int length = stringArray.length; return length; } //builds string for notes display //used by viewStringPackage in Guitar and Violin public String Notes(){ StringBuilder notes = new StringBuilder(); for(int i = 0; i &lt; stringArray.length; i++){ notes.append(stringArray[i] + " "); } String notes1 = notes.toString(); return notes1; } public static void comboPrint(String myString) throws IOException { boolean append = true; FileWriter myOutFile = new FileWriter("GuitarViolin.txt", append); PrintWriter fileOut = new PrintWriter(myOutFile); System.out.println(myString); fileOut.println(myString); fileOut.close(); } }//StringPackage </code></pre> <p>The test:</p> <pre><code>public class test { public static void main(String[] args) throws IOException { //allows user to enter file to write from command line //satifies section 4 requirement if(args.length &gt; 0) section4(args); //create arrays to hold new instruments Guitar[] sixStrings = new Guitar[4]; Guitar[] twelveStrings = new Guitar[4]; Violin[] violins = new Violin[4]; //create 4 new 6-String Guitars, 12-String Guitars and Violins //for a total of 12 new instruments (assignment called for 10) for (int i = 0; i &lt; 4; i++){ sixStrings[i] = new Guitar(); twelveStrings[i] = new Guitar(12); violins[i] = new Violin(); } howMany(); //displays number of instruments created //Display status of the instruments statusAll(sixStrings, twelveStrings, violins); //Tune the instruments and start them playing for(int i = 0; i &lt; violins.length; i++){ sixStrings[i].tune(); sixStrings[i].play(); twelveStrings[i].tune(); twelveStrings[i].play(); violins[i].tune(); violins[i].play(); }//tune and start play statusAll(sixStrings, twelveStrings, violins); //stop instrument from playing for(int i = 0; i &lt; violins.length; i++){ sixStrings[i].stopPlay(); twelveStrings[i].stopPlay(); violins[i].stopPlay(); }//stop playing statusAll(sixStrings, twelveStrings, violins); //created this 3 string guitar to test what happens with my "exception" that isn't an exception System.out.println("......................"); Guitar weirdo = new Guitar(3); weirdo.isPlaying(); weirdo.isTuned(); //To show that weirdo doesn't increase numberOfTwelveStringGuitars howMany(); }//main //getNumberOf... is my unique method //it displays how many instruments of each type were created public static void howMany() throws IOException{ StringPackage.comboPrint("Number of 6-String Guitars is: " + Guitar.getNumberOfGuitars() + "\nNumber of 12-String Guitars is: " + Guitar.getNumberOfTwelveStringGuitars() + "\nNumber of Violins is: " + Violin.getNumberOfViolins() + "\n"); }//howMany //displays all status of ALL instruments //I created this to avoid repeating code in the main public static void statusAll(Guitar[] sixStrings, Guitar[] twelveStrings, Violin[] violins) throws IOException{ instrumentStatus(sixStrings); instrumentStatus(twelveStrings); instrumentStatus(violins); }//statusAll //displays current status of all guitars //uses getNumberofStrings method to determine type of guitar public static void instrumentStatus(Guitar[] guitars) throws IOException{ for (int i = 0; i &lt; guitars.length; i++){ if (guitars[i].getNumberOfStrings() == 12) StringPackage.comboPrint("12-String Guitar " + (i +1) + ": "); else StringPackage.comboPrint("Six String Guitar " + (i + 1) + ":"); if (guitars[i].isPlaying()) StringPackage.comboPrint("Is currently playing."); else StringPackage.comboPrint("Is currently not playing."); if (guitars[i].isTuned()) StringPackage.comboPrint("Is currently tuned."); else StringPackage.comboPrint("Is currently not tuned."); guitars[i].viewStringPackage(guitars[i]); }//for }//instrumentStatus(Guitar[]) //displays current status of all violins public static void instrumentStatus(Violin[] violins) throws IOException{ for (int i = 0; i &lt; violins.length; i++){ StringPackage.comboPrint("Violin " + (i +1) + ": "); if (violins[i].isPlaying()) StringPackage.comboPrint("Is currently playing."); else StringPackage.comboPrint("Is currently not playing."); if (violins[i].isTuned()) StringPackage.comboPrint("Is currently tuned."); else StringPackage.comboPrint("Is currently not tuned."); violins[i].viewStringPackage(violins[i]); }//for }//instrumentStatus(Violin[]) public static void section4(String[] args){ String fileToOpen = ""; fileToOpen = args[0]; System.out.println("This program will read from and write to this file: " + fileToOpen + "\n"); try{ File myOutFile = new File(fileToOpen); Scanner input = new Scanner(myOutFile); input.useDelimiter("\n"); while (input.hasNext()){ String text = input.next(); System.out.println("The text is: " + text + ".\n"); } PrintWriter fileOut = new PrintWriter(myOutFile); fileOut.println("After much thought and many hours of work I have come to the conclusion\n" + "that Section 4 of Project 3 is not possible as written.\n\nIt says to \"Write the output " + "from your Instrument class to a text file that a user entered from the command line " + "arguments\"\n\nTo accomplish this, a method in the instrument class would need to " + "access a String variable local to the main method. That is beyond my current skill level " + "and, I think, beyond that of any 'Intro to Java Programming' student.\n\n" + "I've created this file to show that I'm able to allow a user to enter a filename " + "from the command line and have the program write info to it."); fileOut.close(); }//try catch (IOException io){ System.out.println("Sorry that file is not found " + io); }//catch }//section4 }//class </code></pre> <p>I also created a <code>Violin</code> class, which is basically a copy of the <code>Guitar</code> class.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T17:36:28.797", "Id": "31510", "Score": "0", "body": "I haven't looked at it in depth but something I can see straight away is that you didn't really document the methods: public methods are exposed for other classes to use. These classes don't need to know the implementation (including local comments). They only need to know the exposed interface along with the javadoc, which is what you are missing. See the difference in purpose between local comments and javadoc for the class' clients? Accordingly javadoc shouldn't make any references to any details of the internal implementation, only to what the client needs to care about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T18:28:03.207", "Id": "31512", "Score": "0", "body": "@Jubbat I'm embarrassed to ask: When you say \"client\" do you mean customer, user, or another programming using the class I wrote? We haven't done anything with comments other than \"Here are the types of comments, we'll discuss them in Chapter 24 (next semester)\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T18:29:12.430", "Id": "31513", "Score": "0", "body": "@Jubbat If I understand, you're saying javadoc each method to document how it interacts with other classes. That way a client will know how to call the method and what it will do for them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T01:04:34.127", "Id": "31536", "Score": "1", "body": "No need to be embarrased! Your guess in the second comment is right. \"Client\" here is any other class who calls any of your methods. Imagine some other person created this class as part of a library and you need to use it. How do you know what does a method do? Documentation, which is created from javadoc. That's all." } ]
[ { "body": "<p>C++ guy here so maybe I am wrong about this but it looks like you've got a bug. Does java automatically call no-argument constructors from constructors that take arguments? If not then Guitar(int numberOfStrings) doesn't increment \"numberOfGuitars\".</p>\n\n<p>Also it would make more design sense to have \"StringPackage\" be ignorant of any particular instrument type and instead just have one constructor that takes the number of strings and the \"tuning\" String and maybe another String which is the instrument name. This leaves the the class open to being a container for any type of stringed instrument without ever having to modify the class to support new instrument types.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T18:12:44.937", "Id": "31511", "Score": "0", "body": "I explained to my professor in the test plan that that constructr was a nod toward the theoretical finished project - a complete mapping of the stringed instrument class.\n\nThat constructor increments numberOfTwelveStringGuitars if the int is 12. If not, nothing happens.\n\nIn the finished project there would be one for every string configuration.\n\nIf I understand you correctly, the parameters for the StringPackage constructor would receive int noOfStrings and String \"Open E\" (or somesuch?).\n\nThe idea being that there are less tunings than stringed instruments?\n\nThanks for the input!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T19:37:05.067", "Id": "31519", "Score": "1", "body": "Why use English when code will do? `StringPackage(String StringDescription, String Instrument) { stringArray = StringDescription.split(\" \"); instrumentName = Instrument; }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T19:46:18.057", "Id": "31520", "Score": "0", "body": "The above enables you to add new instrument types without having to change StringPacakage for each type. In a commercial application this is important in several ways. For example, suppose you had contracted out someone to add new instruments to your application but your contract with them stipulates that you can't give them source, just the interface documentation (so they could link with your .jar file but not see the source)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T21:38:46.507", "Id": "31529", "Score": "0", "body": "Wow. So simple! My first thought was \"what happens when the wrong strings are entered?\" My second was: fix it with a setter - that could change tuning, etc too. Also, there could be an 'int noOfStrings = stringArray.length()' in there in case that's needed. Thanks @jayinbmore!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T22:26:15.817", "Id": "31532", "Score": "0", "body": "Glad the idea came across. You could also write some format checking code in the constructor since the format is well defined (and you can throw an exception when someone tries to construct StringPackage with the wrong format)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T17:20:18.597", "Id": "19700", "ParentId": "19699", "Score": "5" } }, { "body": "<p>The instructions do not make that much sense in this way. Did you translate them? I think I do not understand the term \"string\" correctly. From your code, it looks connected to \"notes\" but I do not know which string is a \"Software-String\" and which one is a \"Guitar-String\"</p>\n\n<p>If I follow them exactly, I will get this:</p>\n\n<ul>\n<li>a) 4 fields</li>\n<li>b) Set the initial value to false, then the default constructor fulfills the requirements.</li>\n<li>c) Ok, 3 methods</li>\n<li>d) Ok, a method which detunes looks like the easiest approach</li>\n<li>Text) The class methods do not have any output, they do not need to return anything. So the file will be empty. We will take the argument and create an empty file to fulfill the requirements.</li>\n</ul>\n\n<p>Here we go:</p>\n\n<pre><code>import java.io.File;\nimport java.io.FileWriter;\nimport java.io.IOException;\n\npublic class SomeThing {\n private int numberOfStrings;\n private String[] stringNames;\n private boolean isTuned = false;\n private boolean isPlaying = false;\n\n public void tune() {\n isTuned = true;\n }\n\n public void startPlaying() {\n isPlaying = true;\n }\n\n public void stopPlaying() {\n isPlaying = true;\n }\n\n public void throwItAgainstAWallToDetuneIt() {\n isTuned = false;\n }\n\n public static void main(final String[] args) {\n File file = null;\n try {\n file = new File(args[0]);\n } catch (final Exception e) {\n System.err.println(\"First argument should be a path to a file.\");\n System.exit(1);\n }\n appendStringToFile(\"\", file);\n }\n\n private static void appendStringToFile(final String string, final File file) {\n FileWriter fileWriter = null;\n try {\n fileWriter = new FileWriter(file);\n fileWriter.write(string);\n } catch (final IOException e) {\n System.err.println(\"Filewriting failed: \" + e);\n System.exit(1);\n } finally {\n if (fileWriter != null)\n try {\n fileWriter.close();\n } catch (final IOException e) {\n System.err.println(\"fileWriter.close() failed: \" + e);\n System.exit(1);\n }\n }\n }\n}\n</code></pre>\n\n<p>(Obviously, I do not think that this is the way it should be, but this is the way from the requirements)</p>\n\n<p>Some points about your code:</p>\n\n<pre><code>StringPackage stringPackage = new StringPackage(\"guitar\", 6);\n</code></pre>\n\n<p>Make it private. And I do not see the point of this extra class (could be because of the string thing)</p>\n\n<pre><code>private boolean tuned = false;\nprivate boolean playing = false;\n</code></pre>\n\n<p>better names: <code>isTuned</code> and <code>isPlaying</code></p>\n\n<p>It was already pointed out the the two constructors do not look consistent.</p>\n\n<pre><code>public Guitar(final int numberOfStrings) throws IOException {\n</code></pre>\n\n<p>there is no need to throw this exception.</p>\n\n<p>The <code>StringPackage</code> class is too confusing for me.</p>\n\n<pre><code>public int length() {\n final int length = stringArray.length;\n return length;\n}\n</code></pre>\n\n<p>You do not need to have this intermediate variable, a <code>return stringArray.length;</code> is fine in this case.</p>\n\n<pre><code>public static void comboPrint(final String myString) throws IOException {\n final boolean append = true;\n final FileWriter myOutFile = new FileWriter(\"GuitarViolin.txt\", append);\n final PrintWriter fileOut = new PrintWriter(myOutFile);\n System.out.println(myString);\n fileOut.println(myString);\n fileOut.close();\n}\n</code></pre>\n\n<p>It is a better way to not throw the <code>IOException</code>. Instead handle it and properly close the resource. See my ode above.</p>\n\n<blockquote>\n <p>access a String variable local to the main method</p>\n</blockquote>\n\n<p>You can solve this in several ways. If you want to do it like you describe it, your main class could have a <code>public static String path</code> variable. You can access this variable from all other classes then.</p>\n\n<p>Final discussion point: Talk about the comments. I know a lot of people too, which have the opinion that a lot of code is good or high quality code. Even with some suggestions like more code then source code lines. The answer to this theory is just no. Even more, a lot of code lines is most often a good metric for bad code. As long as you are not coding in Fortran77 (where you probably have only 8 char for a variable name), highly-optimized code or something like this, always prefer easy and good readable code. Add comments only if you can not express it clearly in source code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T01:00:19.593", "Id": "31597", "Score": "0", "body": "+1 for `isTuned` and `isPlaying`... a lot easier for others to understand if not familiar with the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-23T01:58:34.793", "Id": "31767", "Score": "0", "body": "I'll keep the isPlaying, etc in mind when naming. That's awesome about the length() method!! I haven't learned exceptions yet - the book just said to put that there to make the method work. The instructions were as I printed them - I agree it's poorly worded and confusing. Thanks for your help! @tb-" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T18:30:00.067", "Id": "19752", "ParentId": "19699", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T16:35:19.520", "Id": "19699", "Score": "4", "Tags": [ "java", "classes" ], "Title": "Stringed musical instrument class" }
19699
<p>I am using ElasticSearch and Tire for search in my app across all models.</p> <ol> <li>I would like to refactor autocomplete method because it looks to complex for me.</li> <li>Am I using a good pattern for searching across model?</li> </ol> <p><strong>Model</strong></p> <pre><code>class Link &lt; ActiveRecord::Base include Tire::Model::Search include Tire::Model::Callbacks tire.mapping do indexes :id, :type =&gt; 'string', :index =&gt; :not_analyzed indexes :title, analyzer: 'snowball', boost: 100 end def to_indexed_json to_json( only: [:id, :title] ) end ... end </code></pre> <p><strong>Controller</strong></p> <pre><code>class SearchController &lt; ApplicationController def new search = SearchesCatalog.new(params[:term]) render json: search.autocomplete.to_json end end </code></pre> <p><strong>Lib</strong></p> <pre><code>class SearchesCatalog attr_reader :options def initialize(options = {}) @options = HashWithIndifferentAccess.new(options) @resources = [ :questions, :answers, :links, :events, past_events, :reviews ] end def results term = options[:term] Tire.search @resources do query { string "#{term}" } end.results end def autocomplete array = [] results.each do |result| case result.type when "past_event" array &lt;&lt; { title: result.content, label: "#{result.content} &lt;span class='search-type'&gt;PastEvent&lt;/span&gt;", value: "/past_events/#{result.id}" } when "event" array &lt;&lt; { title: result.title, label: "#{result.title} &lt;span class='search-type'&gt;Event&lt;/span&gt;", value: "/events/#{result.id}" } when "topic" array &lt;&lt; { title: result.name, label: "#{result.name} &lt;span class='search-type'&gt;Topic&lt;/span&gt;", value: "/#{result.app_id}/t/#{result.id}" } when "link" array &lt;&lt; { title: result.title, label: "#{result.title} &lt;span class='search-type'&gt;Link&lt;/span&gt;", value: "/links/#{result.id}" } when "question" array &lt;&lt; { title: result.content, label: "#{result.content[0..100]} &lt;span class='search-type'&gt;Question&lt;/span&gt;" } when "answer" array &lt;&lt; { title: result.content, label: "#{result.content[0..100]} &lt;span class='search-type'&gt;Answer&lt;/span&gt;" } end array end end </code></pre> <p><strong>Javascript</strong></p> <pre><code>// set up the search bar $("#question_search").autocomplete({ source:$('#question_search').data('source'), html: true, minlength: 1, appendto: "#search_results", select: function( event, ui ) { window.location=ui.item.value; return false; }, focus: function( event, ui ) { $("#question_search").val(ui.item.title); return false; }, open: function( event, ui ) { $('#search_results') .find('a:first').addclass('first').end() .find('a:last').addclass('last'); } }); </code></pre>
[]
[ { "body": "<p>I'll take <code>autocomplete</code> and leave the rest for others. Some notes:</p>\n\n<ul>\n<li>Never write the pattern \"empty array\" + each + push + return array. That's a <code>map</code> (more on functional programming <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">here</a>)</li>\n<li>Is this \"lib\" thing really in <code>lib/</code>? it should go to <code>app/</code>. In <code>lib</code> you only have generic code that may be reused across applications. </li>\n<li>Don't write routes by hand, ever, that's terrible practice, use the helper router methods provided by Rails.</li>\n<li>Don't write tags by hand, use <code>content_tag</code>.</li>\n<li>Abstract and simplify by identifying repeated patterns in your code.</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>def autocomplete\n results.map do |result|\n title, caption, route = case result.type.to_sym\n when :past_event\n [result.content, \"PastEvent\", past_event_path(result)]\n ...\n end\n\n label = \"%s %s\" % [title, content_tag(:span, caption, class: 'search-type')]\n {title: title, label: label, value: route}\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T14:47:56.660", "Id": "31566", "Score": "0", "body": "Using routes looks great but I have problem when item not exist, for example: ``[result.content, \"Review\", service_provider_path(result.service_provider)]`` I would like to skip adding that item to hash ``if result.service_provider.nil?`` Is possible to not adding it to hash ``{title: title, label: label, value: route}``?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T14:51:07.833", "Id": "31567", "Score": "0", "body": "write `(service_provider_path(result.service_provider) if result.service_proder)`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T19:08:42.897", "Id": "19706", "ParentId": "19702", "Score": "2" } }, { "body": "<p>One suggestion is to create three virtual attributes (title, label, link) for each and every model and add the custom implementations. Add these attributes to the index mapping.</p>\n\n<p>Then you have a unique interface to all models. That way you can get rid of the case statement completely.</p>\n\n<pre><code>results.map do |result|\n {title: result.title, label: result.label, value: url}\nend\n</code></pre>\n\n<p>It will make your index bigger but saves computation time on the <code>autocomplete</code> action.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T07:41:50.103", "Id": "31602", "Score": "1", "body": "+1 That's the orthodox approach for OOP and introduces an interesting matter, the so-colled \"Expression problem\": http://c2.com/cgi/wiki?ExpressionProblem. Personally I've found that, when writing helpers, it's more maintainable to use `cases` that to scatter code throughout the models, though. In this case it should be more something like presenters, models are not really the place for \"label\" or \"url\" methods." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T01:10:10.767", "Id": "19761", "ParentId": "19702", "Score": "2" } } ]
{ "AcceptedAnswerId": "19706", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T18:10:07.743", "Id": "19702", "Score": "4", "Tags": [ "ruby", "ruby-on-rails", "search" ], "Title": "ElasticSearch, Tire - refactor autocomplete method for multiple resources" }
19702
<p>I have a Python file with several function definitions in it. One of the functions, named 'main' will be called as soon as the Python file is run.</p> <p>Example:</p> <pre><code>myFile.py import sys def main(arg1....): ---code--- --more functions-- main() </code></pre> <p>When a person wants to run my file they'll type:</p> <pre><code>python myFile.py arg1 arg2 ... </code></pre> <p>The main function is supposed to accept in x number of arguments, however, in case the user doesn't wish to pass in any arguments we're supposed to have default values.</p> <p>My program looks something like this and I'm hoping there is actually a better way to do this than what I have:</p> <pre><code>myFile.py import sys #Even though my function has default values, if the user doesn't wish #to input in any parameter values, they still must pass in the word False #otherwise, pls pass in parameter value def main(name = "Bill", age = 22, num_pets=5, hobby = "soccer"): if len(sys) &gt; 1: i =0 while i &lt; len(sys): if i == 0: if sys.argv[i] == "False": i += 1 continue else: name = sys.argv[i] i += 1 continue elif i == 1: if sys.argv[i] == "False": --------etc. etc.----------- </code></pre>
[]
[ { "body": "<p>You can use the <a href=\"http://docs.python.org/2/tutorial/controlflow.html#tut-unpacking-arguments\" rel=\"nofollow\">apply</a> operator (<code>*</code>):</p>\n\n<pre><code>import sys\n\ndef main(name = \"Bill\", age = 22, num_pets=5, hobby = \"soccer\"):\n pass\n\nif __name__ = \"__main__\":\n main(*sys.argv[1:])\n</code></pre>\n\n<p>You can also use <a href=\"http://pypi.python.org/pypi/argparse\" rel=\"nofollow\">argparse</a> to sanitize the contents of sys.argv before applying them to <code>main()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T05:57:20.100", "Id": "19722", "ParentId": "19707", "Score": "2" } }, { "body": "<p>In case the number of arguments is really long then you can use **kwargs to avoid cluttering up arguments in function definition block. I would also avoid naming the function as \"main\" and replace it with something like \"execute\".</p>\n\n<pre><code>def execute(**kwargs):\n name = kwargs.get('name', 'Bill')\n # get other values\n pass\n\nif __name__ = \"__main__\":\n execute(*sys.argv[1:])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T09:26:06.103", "Id": "19725", "ParentId": "19707", "Score": "4" } }, { "body": "<p>You can also use <a href=\"http://docs.python.org/2/library/optparse.html\" rel=\"nofollow\">optparse</a></p>\n\n<p>Here is an example:</p>\n\n<pre><code>import optparse\n...\nif __name__ == '__main__':\n parser = optparse.OptionParser()\n parser.add_option('-s', '--string', dest = 'someVar', default = 'default', help = '-s with a small s. With default Value')\n parser.add_option('-S', '--boolean', action = 'store_true', dest = 'someBool', help = 'i am a flag :). Use me with a capital S')\n\n (options, args) = parser.parse_args()\n\n main(options)\n</code></pre>\n\n<p>Then your users have to call it like</p>\n\n<pre><code>python script.py -s HerpDerp\n</code></pre>\n\n<p>or</p>\n\n<pre><code>python script.py -h\n</code></pre>\n\n<p>to see a list of available arguments</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T10:19:30.487", "Id": "31548", "Score": "0", "body": "optparse seems to be deprecated since version 2.7" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T10:42:34.230", "Id": "31549", "Score": "0", "body": "@Kinjal You are right. But there is [argparse](http://docs.python.org/3.3/library/argparse.html#module-argparse) which has a similar syntax." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T10:00:04.403", "Id": "19729", "ParentId": "19707", "Score": "0" } }, { "body": "<p>I'd suggest using high-level fool-proof libraries like <a href=\"http://docs.python.org/dev/library/argparse.html\" rel=\"nofollow\">argparse</a>.</p>\n\n<p>The problem with argparse is that its syntax is too verbose, so I developed <a href=\"https://argh.readthedocs.org\" rel=\"nofollow\">Argh</a>. It helps maintain the code simple and pythonic:</p>\n\n<pre><code>import argh\n\ndef main(name, age=22, num_pets=5, hobby='soccer'):\n yield 'This is {name}, {age}'.format(name=name, age=age)\n yield 'He has ' + ('one pet' if num_pets &lt; 2 else 'many pets')\n\nargh.dispatch_command(main)\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>$ ./script.py Bill\nThis is Bill, 22\nHe has many pets\n\n$ ./script.py John -a 50 --num-pets=1 --hobby sleeping\nThis is John, 50\nHe has one pet\n</code></pre>\n\n<p>This can be easily tuned if you don't mind diving into the documentation.</p>\n\n<p>Of course it's not the only library in this field.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T08:54:59.080", "Id": "20370", "ParentId": "19707", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T19:15:33.640", "Id": "19707", "Score": "3", "Tags": [ "python" ], "Title": "Python file with several function definitions" }
19707
<p>Let's say I have three files: a page that is used for searching data called search, a file that handles requests called controller, and a file that has functions which the controller calls based on what POST parameter is passed. From the search page, I post some data and specify my action (search) via AJAX to the controller. The controller then takes that and calls a function that returns the data (which is inserted into the appropriate place in the DOM) which looks something like this:</p> <pre><code>&lt;?php function fetchStudentData($search, $roster) { //If a user is not logged in or the query is empty, don't do anything if(!isLoggedIn() || empty($search)) { return; } global $db; //Placement roster search if($roster == "placement") { $query = $db-&gt;prepare("SELECT t1.id, t2.placement_date, t2.placement_room, t1.student_id, t1.student_type, t1.last_name, t1.first_name, t1.satr, t1.ptma, t1.ptwr, t1.ptre, t1.ptlg, t1.waiver, t2.tests_needed, t2.blackboard_id FROM student_data AS t1 JOIN additional_data AS t2 ON t1.id = t2.student_data_id WHERE t2.placement_date = :search ORDER BY t1.last_name ASC"); $query-&gt;bindParam(":search", $search); $query-&gt;execute(); if($query-&gt;rowCount() == 0) { return; } echo "&lt;div id='searchHeader'&gt; &lt;div class='searchSubHead'&gt;&lt;em&gt;Placement Roster For $search&lt;/em&gt;&lt;/div&gt; &lt;br /&gt; &lt;span&gt;Placement Room&lt;/span&gt; &lt;span&gt;Student ID&lt;/span&gt; &lt;span&gt;Student Type&lt;/span&gt; &lt;span&gt;Last Name&lt;/span&gt; &lt;span&gt;First Name&lt;/span&gt; &lt;span&gt;SATR&lt;/span&gt; &lt;span&gt;PTMA&lt;/span&gt; &lt;span&gt;PTWR&lt;/span&gt; &lt;span&gt;PTRE&lt;/span&gt; &lt;span&gt;PTLG&lt;/span&gt; &lt;span&gt;Waiver&lt;/span&gt; &lt;span&gt;Tests Needed&lt;/span&gt; &lt;span&gt;Blackboard ID&lt;/span&gt; &lt;/div&gt;"; while($row = $query-&gt;fetch()) { echo "&lt;div id='{$row['id']}' class='placementRosterRecord'&gt; &lt;span&gt;{$row['placement_room']}&lt;/span&gt; &lt;span&gt;{$row['student_id']}&lt;/span&gt; &lt;span&gt;{$row['student_type']}&lt;/span&gt; &lt;span&gt;{$row['last_name']}&lt;/span&gt; &lt;span&gt;{$row['first_name']}&lt;/span&gt; &lt;span&gt;{$row['satr']}&lt;/span&gt; &lt;span&gt;{$row['ptma']}&lt;/span&gt; &lt;span&gt;{$row['ptwr']}&lt;/span&gt; &lt;span&gt;{$row['ptre']}&lt;/span&gt; &lt;span&gt;{$row['ptlg']}&lt;/span&gt; &lt;span&gt;{$row['waiver']}&lt;/span&gt; &lt;span&gt;{$row['tests_needed']}&lt;/span&gt; &lt;span&gt;{$row['blackboard_id']}&lt;/span&gt; &lt;/div&gt;"; } } } ?&gt; </code></pre> <p>This is obviously working very well for me but I wanted to know if there's a better way I should be doing this? Should I be returning the raw data from the database and encoded as JSON and then have my JavaScript take care of creating elements/structure? I see that a lot with various API's but this is something internal to my company and not something that other developers will be using. Is there anything wrong with my approach?</p>
[]
[ { "body": "<p>Your approach, which is to load a partial view (html) via ajax, is just fine. Yes, you could load something else such as json, xml, etc. The problem you'd face is that you would require additional client side (js) code to deal with the data. Some feel that the lighter payload of json offers faster loading over html. I argue that your users would likely never really notice an improvement.</p>\n\n<p>I would offer these suggestions:</p>\n\n<ol>\n<li>Design the initial app with 0% javascript in the beginning! Things can change a lot while developing an app. You'll appreciate not having to change both your php and js early on.</li>\n<li>Separate your data access and presentation layers. </li>\n<li>Use a templates system which allows you to render a full html layout (everything inside <code>&lt;html&gt;&lt;/html&gt;</code> including the page specific content) or partial html (the content in <code>&lt;div&gt;&lt;/div&gt;</code>).</li>\n<li>Once you decide to spruce things up with some js and ajax, have your controllers load the partial view if it's an ajax request, or full layout if it's a regular request.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T02:39:45.390", "Id": "19718", "ParentId": "19710", "Score": "3" } }, { "body": "<h1>First of all, you should read about MVC.</h1>\n\n<p>There are a lot of tutorials out there, as well as frameworks (like <a href=\"http://ellislab.com/codeigniter\">CodeIgniter</a>) that implement it. Basically your code should be divided into 3 main categories:</p>\n\n<ul>\n<li><p>Controllers - where all logic should be placed like validations, checks. This is also where Views and Models are used, hence \"controller\"</p></li>\n<li><p>Models - basically the source of data. Usually this is the abstraction of the data storage (databases, sessions, external requests) in the form of functions.</p></li>\n<li><p>Views - the presentation, or in this case, the HTML.</p></li>\n</ul>\n\n<h2>Reasons to use MVC or MV* patterns is</h2>\n\n<ul>\n<li><p>Portability. </p>\n\n<p>The files, especially the views and models, can be plucked out of the architecture, and be used elsewhere in the system without modification. </p>\n\n<p>Models are simply function declarations one can just plug in the controller and call their functions. Views are simply layouts that, when plugged with the right values, display your data. They can be used and reused with little or no modification unlike with mixed code.</p></li>\n<li><p>Purpose-written code and Readability</p>\n\n<p>You would not want your HTML mixed with the logic, nor the data gathering mechanism. This goes for all other parts of your code. For example, when you edit your layout, all you want to see on your screen is your layout code, and nothing more.</p></li>\n</ul>\n\n<h1>Never, and I mean NEVER return marked-up data using AJAX (use <a href=\"http://www.json.org/\">JSON</a>).</h1>\n\n<p>The main reason AJAX is used is because it's asynchronous. This means no page-loading, no more request-<em>wait</em>-respond, and you could do stuff in parallel. It's pseudo-multitasking for the human.</p>\n\n<p>On the same train of thought, the reason why JSON was created was because XML was too heavy for data transfer and we needed a lightweight, data transport format. XML is NOT a data-transport format but a document and mark-up language (Though by \"X\" for extensibility, it has served a lot of purposes beyond document).</p>\n\n<h1>Use client-side templating</h1>\n\n<p>JavaScript engines have become fast these days that even developers create parsers/compilers on JavaScript. And with that comes client-side templating, like <a href=\"https://github.com/janl/mustache.js/\">Mustache</a>.</p>\n\n<p>Coupled with raw data from JSON, which is very light, you can integrate that data into a template to form your view and have JavaScript display it, like you already do.</p>\n\n<h1>Have a rendered version and a data version</h1>\n\n<p>Taking into account the previous answer, if you are making a website rather than a web app, where JS is optional rather than required, one should create a website that works without JS. </p>\n\n<p>However, for the same data but different format, the URL should not change (much). You should then take into account in the request what data type is requested by the client. And so you must accept a parameter which indicates the data type.</p>\n\n<p>An example url would look like this:</p>\n\n<pre><code>//for a website page format (default: HTML):\nhttp://example.com/my/shop/available/items.php\n\n//for the JSON version\nhttp://example.com/my/shop/available/items.php?format=JSON\n\n//for the XML version\nhttp://example.com/my/shop/available/items.php?format=XML\n</code></pre>\n\n<p>This means, that for the same page (available items), you have 3 formats you can use. This can be seen in the <a href=\"http://docs.joomla.org/Framework\">Joomla Framework</a> (the framework that powers the Joomla CMS)</p>\n\n<p>With these 3 tips, your code will be cleanly separated and purposely written (MVC), fast on transport and rendering (JSON + client-side templating) and extensible (multi-format support).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-29T07:55:18.913", "Id": "194123", "Score": "0", "body": "\"Never, and I mean NEVER return marked-up data using AJAX\" I disagree. While a lot of **data** calls you're going to want to use JSON, many common libraries use AJAX for retrieving templates as well, which are simple HTML files. It depends on your use-case. I would argue that saying \"never do this\" is harmful.. even if the harm was done nearly 3 years ago :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T07:42:35.690", "Id": "19723", "ParentId": "19710", "Score": "5" } } ]
{ "AcceptedAnswerId": "19723", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T20:40:12.617", "Id": "19710", "Score": "3", "Tags": [ "javascript", "php", "mysql", "ajax", "json" ], "Title": "Better way to return data via AJAX?" }
19710
<p>This is a project I am working on, which generates an HTML table out of a query result.</p> <p>(The result <code>DataTable</code> of an SQL command via SP)</p> <p>This section of the project is the one that will generate the headers of the table according to the list of columns of each table selected (from the database list of tables). What I am trying to review here is the section that's responsible for generating an HTML markup programmatically.</p> <p>I would like to know your opinion and what you would do differently.</p> <p>In aspx, I will move this back after tests are completed:</p> <pre><code>&lt;% //instantiating class to Get A List&lt;string&gt; returned (of all db table-columns) // this code is inplementing GetClassFields class // you can see its code in section #2 below (helpers section) var TableColscls = GetClassFields.AsListStr(GetClassFields.SelectedClass.tables, tbls.TblTimeCPAReport); %&gt; </code></pre> <p>Then using the list above for the generated HTML table:</p> <pre><code>&lt;div style="width:90%; " dir="rtl"&gt; &lt;%=RenderHtmlTblHeaders(TableColscls)%&gt; &lt;/div&gt; </code></pre> <p><strong>.cs code behind</strong></p> <pre><code> // some usings using Lsts = HTMLGenerator.dataSource.List; // this is what i call HTML TABLE GENERATOR // or DB TO HTML Tables Adapter public string RenderHtmlTblHeaders(List&lt;string&gt; SelectedListStr) { List&lt;string&gt; OmittedCols = new List&lt;string&gt;(); OmittedCols.Add(imprtCPAcols.tbName); OmittedCols.Add(imprtCPAcols.tbIdentCol); StringBuilder NwTRLoopSB = new StringBuilder(); string curRowStyle= string.Empty, nwLine = Environment.NewLine + "\t\t\t", BaseTemplateTD = string.Empty; NwTRLoopSB.Append( string.Format( "&lt;table id='tbl_Settings' cellspacing='0' border='1'&gt;&lt;tr id='TR_headers'{0}&gt;{1}", curRowStyle, nwLine )._Dhtml_DoubleQoutes() ); //a new approach i've discovered (in one of the posts on `SO` ) //to have a counter with foreach loops foreach (var Item in SelectedListStr.Select((Val, counter) =&gt; new { Value = Val, Index = counter })) { if(Lsts.ExcludeColumns(Item.Value, OmittedCols)) { BaseTemplateTD = string.Format("&lt;td&gt;{0}&lt;/td&gt;{1}", Item.Value, nwLine)._Dhtml_DoubleQoutes(); NwTRLoopSB.Append(BaseTemplateTD); } }///ENd TR cells generator Section NwTRLoopSB.Append("&lt;/tr&gt;&lt;/table&gt;"); return NwTRLoopSB.ToString(); } </code></pre> <p><strong>.cs helper namespaces and classes</strong></p> <p>The code blocks below are extracted by relevance to this project as it (the whole file) serves all of my projects as a <em>bunch</em> of helpers.</p> <p><strong>Extensions</strong></p> <p>This one is used to avoid the use of <code>\"</code> within formatted text:</p> <pre><code> /// &lt;summary&gt; /// Replaces a single Quote with Double. used for html Attributes: /// &lt;/summary&gt; public static string _Dhtml_DoubleQoutes(this string NewTRString) { return NewTRString.Replace("'", "\""); } </code></pre> <p><strong>class to list</strong> </p> <pre><code> // using reflection to list / extract all fields of a given class public class GetClassFields { public enum SelectedClass { tables, columns, ColHeaders } public List&lt;string&gt; AsListStr(SelectedClass tabls_Cols_StoerdProc, string TableName) { var tbls = new HTDB_Tables(); HTDB_Cols Cols = new HTDB_Cols(); var ColHeds = new Htdb_PresentedHebColHeaders(); switch (tabls_Cols_StoerdProc) { case SelectedClass.tables: return typeof(HTDB_Tables).GetFields() .Select(f =&gt;f.GetValue(tbls).ToString()).ToList&lt;string&gt;(); case SelectedClass.columns: return typeof(HTDB_Cols).GetNestedTypes() .First(t =&gt; String.Compare(t.Name, TableName, true) == 0) .GetFields() .Select(f =&gt; f.GetValue(Cols).ToString()) .ToList&lt;string&gt;(); case SelectedClass.ColHeaders: return typeof(Htdb_PresentedHebColHeaders).GetNestedTypes() .First(t =&gt; String.Compare(t.Name, TableName, true) == 0) .GetFields() .Select(f =&gt; f.GetValue(ColHeds).ToString()) .ToList&lt;string&gt;(); default: return typeof(HTSPs.GetWorkerNameAndDataForTcReportCPABySnif_Fields).GetNestedTypes() .First(t =&gt; String.Compare(t.Name, TableName, true) == 0) .GetFields() .Select(f =&gt; f.GetValue(null) as string) .ToList(); } } } </code></pre> <p><strong>HTML Generator</strong></p> <p>(This is the short version; you could see my other post for a longer version)</p> <p>Another method to produce style-background-color as <code>bgColor</code> of the alternation of rows within the HTML generated table:</p> <pre><code>public class HTMLGenerator { //i guess i will add whats in cs code behind to this next section of helpers public class HTMFactory { //TablesAlternatingRow public static string DynamicStyle_Generator ( int RowCounter = -1, Dictionary&lt;string, string&gt; StyleAttributeDict = null ) { string BaseStyle = "", propTerminator = "'", BgCol = ""; StringBuilder StylerSB = new StringBuilder(); BgCol = ""; bool bgclaltrnator; if (RowCounter &gt;= 0) { RowCounter++; bgclaltrnator = (RowCounter % 2) == 0; if (bgclaltrnator) BgCol = "#70878F"; else BgCol = "#E6E6B8"; } BaseStyle = string.Format("style='background-color:{0};", BgCol); ///string.Format("{0}:{1};", StlProps.BgColor, val); return string.Concat(BaseStyle, StyleAttributeDict, propTerminator); } } // when inside the loop this will supply the correct "data source" // that will be the content of the table cells // for now it is the "selector" of which column to omitt method that // i have placed here... public class dataSource { public sealed class List { public static bool ExcludeColumns ( string ListItem, List&lt;string&gt; OmittedColumns ) { bool Ret = false; foreach (string col in OmittedColumns) { Ret = string.Compare(ListItem, col) ==0; if (Ret) return false; } return true; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T22:51:08.833", "Id": "31534", "Score": "0", "body": "Have you looked using the HTML Agility Pack. It may be overkill but it might also make some of the steps easier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T02:48:55.303", "Id": "31538", "Score": "0", "body": "@GeneS I know `HtmlAgilityPack`... I am using it for parsing html documents , what else , I couldn't connect the idea ...(4am here) of usage with `HtmlAgilityPack ` , as i don't really know more of it's features, but those I've already used for Parsing , so which part are you referring to and what features of `HtmlAgilityPack` would cover for it better ? , thanks for your time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T15:53:18.573", "Id": "31570", "Score": "0", "body": "You can also use it to create new Html documents. I'm not an expert with it so I am not sure if it would end up being too tedious to create new elements. But if not, it might be a nice way to create the document in an object-oriented fashion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T16:06:46.057", "Id": "31571", "Score": "0", "body": "@GeneS thanks mate . i will look in to this aspect of the HtmlAgilityPack as i like to discover new implementation and see if it is more appropriate or easy to manipulate . did you ever try to pool some `tricks` of not having to hardcode your markup, also because it will be required as it will unnecessarily repeat itself" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T17:31:51.720", "Id": "31579", "Score": "0", "body": "No sorry, I have not had to do this. I suspect if you find the `HtmlAgilityPack` an acceptable solution you will have less hardcoded markup because you will be creating elements instead of strings." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T21:47:28.927", "Id": "19712", "Score": "1", "Tags": [ "c#", "performance", "html", "asp.net" ], "Title": "DataTable 'adapter' to HTML table generator" }
19712
<p>I'm making a family tree. The following script allows the user to expand branches of the tree. It works fine, but there must be a better way.</p> <p>You can see it working <a href="http://www.nicholsonfamilytree.co.uk/test1.asp" rel="nofollow">here</a>.</p> <pre><code>$(function(){ $('.oc').prepend('&lt;img src="icons/bullet_add.png" alt="more" width="16" height="16"/&gt;') $("ul[id|=Nested]").hide(); $("a[id|=trigger_Nested]").click(function() { var text = $(this).siblings("ul"); if (text.is(':hidden')) { text.slideDown("fast"); $(this).next("span").html('&lt;img src="icons/bullet_take.png" alt="close" width="16" height="16" /&gt;'); } else { text.slideUp("fast"); $(this).next("span").html('&lt;img src="icons/bullet_add.png" alt="more" width="16" height="16" /&gt;'); } return false; }); }); </code></pre>
[]
[ { "body": "<p>A couple notes:</p>\n\n<ol>\n<li><p>I would use classes instead of ids for the nested links. I don't know if it's faster to search the DOM for all elements with a specific class, but it looks cleaner and doesn't require you to create unique ids for each element:</p>\n\n<pre><code>$('a.nested-trigger').click(...);\n</code></pre></li>\n<li><p>I would also use classes for the icons, as it's less expensive than replacing DOM nodes:</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;span class=\"oc collpased\"&gt;&lt;/span&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>.oc {\n position: relative;\n right: 10px;\n display: inline-block;\n width: 16px;\n height: 16px;\n}\n.collapsed {\n background: url(icons/bullet_add.png);\n}\n.expanded {\n background: url(icons/bullet_take.png);\n}\n</code></pre>\n\n<p>JS:</p>\n\n<pre><code>$(this).next(\"span\").removeClass(\"collapsed\").addClass(\"expanded\");\n</code></pre></li>\n<li><p>This is related more to the UX of your demo but I would make the icons themselves clickable as well, because they're big enough to look like buttons, and they overlap part of the node.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T04:35:41.557", "Id": "31541", "Score": "0", "body": "All very good points. I especially agree with seand's 3rd point. I tried to click the icons and was thinking the whole thing didn't work for a second." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T01:15:13.387", "Id": "19716", "ParentId": "19713", "Score": "1" } } ]
{ "AcceptedAnswerId": "19716", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T22:38:11.213", "Id": "19713", "Score": "3", "Tags": [ "javascript", "jquery", "tree" ], "Title": "Expanding branches of a family tree" }
19713
<p>The first block of code is my main app.js that is included on every request. It is essentially a library of functions and objects that include related functions (ie: app.utils) that I can use on other pages like page1.js:</p> <p>./app.js</p> <pre><code>var app = window.app || {}; (function($){ app.req = app.req || {}; app.utils = app.utils || {}; app.utils.form = app.utils.form || {}; app.page = app.page || {}; app.log = function(msg){ ( window.console &amp;&amp; console.log(msg) ); }; })(jQuery); </code></pre> <p>This is a page-level script that is included only on the one page:</p> <p>./page1.js</p> <pre><code>(function($){ $(function(){ app.log('page1 stuff'); }); }(jQuery); </code></pre> <p>I'm wondering what other methods are used for organizing larger codebases, or if there are any inheritly flawed ways using this method.</p>
[]
[ { "body": "<p>In JavaScript, there is no sure-fire way to organize framework code. As proof, just take a look at the different frameworks that reside on GitHub. You will see that every developer has his/her own way of organizing code.</p>\n\n<p>Here's what I can recommend in your case:</p>\n\n<p>I see that in your code, you seem to be namespacing your utility functions into deep structures. What I can suggest is to have a built-in function that extends your top <code>app</code> namespace instead of having to manually type in, check it that level exists and create. Have that extend function nest and check it for you.</p>\n\n<p>Also, with extending, it would be great if the extended functions have some access to some inner objects as well</p>\n\n<pre><code>(function(app,$){\n\n //some stuff you want seen by extensions\n var extensionExtras = {\n cache : {}\n }\n\n //an extend function that checks, nests and creates namespaces\n function extend(nesting,fname,handler){\n //split nesting order\n //recursively check for the namespace\n //if it does not exist, create an object for it\n //else, go through it\n //attach function with name\n //overwriting is up to you\n deepNamespaceReference[fname] = function(){\n handler.call(this,extensionExtras);\n }\n }\n\n\n extend('app.from.inside.module','extendedInside',function(){\n //functionality here\n });\n\n //expose extend\n app.extend = extend;\n\n})(window.app = window.app || {},jQuery);\n\n//extend from the outside:\napp.extend('app.some.deep.namespace','fromOutside',function(){\n //functionality here\n});\n\n//and then we can use:\napp.from.inside.module.extendedInside();\napp.some.deep.namespace.fromOutside();\n</code></pre>\n\n<p>However...</p>\n\n<p>Namespacing technique in JavaScript actually uses objects and properties that contain objects. Deeply nested object structures in JavaScript incur a very minor performance drawback but a drawback still. I suggest you keep your namespace levels a minimum to avoid the performance penalties.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T08:04:20.400", "Id": "19724", "ParentId": "19721", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T05:37:16.443", "Id": "19721", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "looking for review of code organization for jQuery/javascript code" }
19721
<p>I had a question regarding my code which downloads a file from S3 with the highest (most recent) timedated filename format:</p> <p>YYYYMMDDHHMMSS.zip</p> <pre><code>from boto.s3.connection import S3Connection from boto.s3.key import Key import sys conn = S3Connection('____________________', '________________________________________') bucket = conn.get_bucket('bucketname') rs = bucket.list("FamilyPhotos") for key in rs: print key.name keys = [(key,datetime.strptime(key.name,'%Y%m%d%H%M%S.zip')) for key in rs] sorted(keys, key = lambda element : element[1]) latest = keys[0][1] latest.get_contents_to_filename() </code></pre> <p>I havent done a lot of python before so I would really appreciate some feedback.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T12:16:27.860", "Id": "31553", "Score": "0", "body": "What are you looking for specifically?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T12:34:22.500", "Id": "31555", "Score": "1", "body": "The part of the script that works out the most recently dated filename. I am sure there is a better way of doing it." } ]
[ { "body": "<p>The names will properly compare lexically even without converting them to datetimes, and you can just use the <a href=\"http://docs.python.org/2/library/functions.html#max\" rel=\"nofollow\"><code>max</code></a> function:</p>\n\n<pre><code>from boto.s3.connection import S3Connection\nfrom boto.s3.key import Key\n\nconn = S3Connection(XXX, YYY)\nbucket = conn.get_bucket('bucketname')\nrs = bucket.list(\"FamilyPhotos\")\nlatest = max(rs, key=lambda k: k.name)\nlatest.get_contents_to_filename()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T07:14:41.163", "Id": "19768", "ParentId": "19727", "Score": "3" } } ]
{ "AcceptedAnswerId": "19768", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T09:37:04.007", "Id": "19727", "Score": "2", "Tags": [ "python", "amazon-s3" ], "Title": "Python Boto Script - Sorting based on date" }
19727
<p>I have a helper class that I am using to return the selected items in a number of IEnumerable POCO collection but I'm not happy with the implementation. One of the reasons for using this method is that the collections area returned by RIA services as ReadOnlyObservableCollections and I don't believe they support LINQ but may be wrong.</p> <p>Is there a way to refactor these three methods using generics? Are there any other improvements that I can make?</p> <pre><code>public class ModelHelper : IModelHelper { public IList&lt;Int32&gt; GetSelectedResults(IEnumerable&lt;FaultAuditScoresDto&gt; scores) { IList&lt;Int32&gt; selected = new List&lt;Int32&gt;(); foreach (FaultAuditScoresDto s in scores) { if (s.IsSelected) { selected.Add(s.ID); } } return selected; } public IList&lt;Int32&gt; GetSelectedResults(IEnumerable&lt;ZonesDto&gt; zones) { IList&lt;Int32&gt; selected = new List&lt;Int32&gt;(); foreach (ZonesDto s in zones) { if (s.IsSelected) { selected.Add(s.ID); } } return selected; } public IList&lt;Int32&gt; GetSelectedResults(IEnumerable&lt;FaultAreasDto&gt; faultAreas) { IList&lt;Int32&gt; selected = new List&lt;Int32&gt;(); foreach (FaultAreasDto s in faultAreas) { if (s.IsSelected) { selected.Add(s.ID); } } return selected; } } </code></pre> <p>I have refactored it to use generics and a dynamic type for the loop but I'm still not happy with it</p> <pre><code> public IList&lt;T&gt; GetSelectedResults&lt;T,U&gt;(IEnumerable&lt;U&gt; scores) { List&lt;T&gt; selected = new List&lt;T&gt;(); foreach (dynamic s in scores) { if (s.IsSelected) { //Need to cast the ID as &lt;T&gt; due to the IList limitation below //http://connect.microsoft.com/VisualStudio/feedback/details/534288/ilist-dynamic-cannot-call-a-method-add-without-casting selected.Add((T)s.ID); } } return selected; } </code></pre> <p>Any other idea?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T10:59:40.827", "Id": "31550", "Score": "2", "body": "Anything IEnuerable or IQueryable supports LINQ. If it isn't generic, you can call .Cast<Type>() first, then it's generic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T11:04:31.290", "Id": "31551", "Score": "0", "body": "I agree with @Lars-Erik , Linq support all possible collection .you may consider using Extension method to write a clean code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T11:12:17.407", "Id": "31552", "Score": "0", "body": "Yes, my mistake. I was missing the 'System.Linq' namespace for this class" } ]
[ { "body": "<p>Implement this interface in all of your Dto where it needed:</p>\n\n<pre><code>interface ICommonDtoStuff&lt;T&gt;\n{\n bool IsSelected { get; }\n T ID { get; }\n}\n</code></pre>\n\n<p>Then you can create a method like this:</p>\n\n<pre><code>public IList&lt;T&gt; GetSelectedResults&lt;T, U&gt;(IEnumerable&lt;U&gt; scores) where U : ICommonDtoStuff&lt;T&gt;\n{\n return scores.Where(x =&gt; x.IsSelected).Select(x =&gt; x.ID).ToList();\n}\n</code></pre>\n\n<p>As extension method:</p>\n\n<pre><code>public static class Extensions\n{\n public static IList&lt;T&gt; GetSelectedResults&lt;T&gt;(this IEnumerable&lt;ICommonDtoStuff&lt;T&gt;&gt; scores)\n {\n return scores.Where(x =&gt; x.IsSelected).Select(x =&gt; x.ID).ToList();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T13:40:10.880", "Id": "31563", "Score": "0", "body": "Instead of generic `T`, you could use `int` if you know the ID is always going to be of that type." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T11:00:41.427", "Id": "19733", "ParentId": "19728", "Score": "2" } } ]
{ "AcceptedAnswerId": "19733", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T09:57:12.593", "Id": "19728", "Score": "1", "Tags": [ "c#", ".net" ], "Title": "POCO helper class refactoring" }
19728
<p>I'm fairly new to mvc and almost finished my auth class I wanted to check that I'm using it all correctly any feedback would be welcome. I used the PIP framework to get started <a href="http://gilbitron.github.com/PIP/" rel="nofollow">http://gilbitron.github.com/PIP/</a></p> <p>here's the controller</p> <pre><code>&lt;?php class Auth extends Controller { protected $username; protected $password; public $action; private $user; function index() { $template = $this-&gt;loadView('login'); $template-&gt;render(); } function login() { $this-&gt;username = $_POST['username']; $this-&gt;password = $_POST['password']; $this-&gt;action = $_POST['which_action']; $login = $this-&gt;loadModel('auth_model'); // pass the user details if($this-&gt;action=="login") { $login = $login-&gt;do_login($this-&gt;username,encrypt_password($this-&gt;password)); switch($login[0]-&gt;active) { case "0": $this-&gt;redirect('auth/login/disabled'); break; case "1": $this-&gt;redirect('dashboard/'); break; default: $this-&gt;redirect('auth/login/error'); break; } } $template = $this-&gt;loadView('login'); $notification = $this-&gt;loadHelper('notification_helper'); // check if the user is active or not $url = $this-&gt;loadHelper('url_helper'); switch($url-&gt;segment(3)) { // account disabled case "disabled": $template-&gt;set('login_result', $notification-&gt;show_notification(1)); break; // wrong login details case "error": $template-&gt;set('login_result', $notification-&gt;show_notification(2)); break; // password reset case "reset": $template-&gt;set('login_result', $notification-&gt;show_notification(3)); break; case "reseterror": $template-&gt;set('login_result', $notification-&gt;show_notification(3)); break; case "changed": $template-&gt;set('login_result', $notification-&gt;show_notification(6)); break; } $template-&gt;render(); } function resetPassword() { $this-&gt;username = $_POST['username']; $this-&gt;password = $_POST['password']; $login = $this-&gt;loadModel('auth_model'); $notification = $this-&gt;loadHelper('notification_helper'); $url = $this-&gt;loadHelper('url_helper'); $template = $this-&gt;loadView('reset_password'); // The form has been posted lets reset the password if($url-&gt;segment(3)==1) { $login-&gt;reset_password($this-&gt;username,getrandomstring(9)); $check_reset = $login-&gt;check_reset($this-&gt;username); $this-&gt;user = $check_reset[0]; switch($this-&gt;user-&gt;password_reset) { case 1: // success $email = $this-&gt;loadHelper('mail_helper'); $email-&gt;send_template(1,$this-&gt;user,array($this-&gt;user-&gt;first_name." ".$this-&gt;user-&gt;last_name =&gt; $this-&gt;user-&gt;email)); // the email was sent if($email-&gt;status=="sent") { $this-&gt;redirect('auth/login/reset'); } else { // something went wrong $this-&gt;redirect('auth/login/reseterror'); } break; case 0: // failure if($this-&gt;user-&gt;active!=0) { $template-&gt;set('password_result', $notification-&gt;show_notification(4)); } else { // account disabled $this-&gt;redirect('auth/login/disabled'); } break; } } if($url-&gt;segment(3)=="confirm") { // first lets check this is a real request $user = $login-&gt;get_user($url-&gt;segment(4),$url-&gt;segment(5)); if($user[0]-&gt;active==1) { $template = $this-&gt;loadView('change_password'); //password change procedure if($this-&gt;action=="change") { // verify the new password matches if($_POST['password']==$_POST['password_confirm']) { //crypt the password $password = encrypt_password($this-&gt;password); //update the account $login-&gt;change_password($url-&gt;segment(4),$password); //redirect to login $this-&gt;redirect('auth/login/changed'); // Receive an email //$email-&gt;send_template(1,$check_reset[0]); } else { // return an error $template-&gt;set('password_result', $notification-&gt;show_notification(7)); } } } else { // kick them back to the login screen $this-&gt;redirect('auth/login/reseterror'); } } $template-&gt;render(); // 2. Receive an email with a link to reset password } } ?&gt; </code></pre> <p>and model</p> <pre><code> &lt;?php class Auth_model extends Model { public function do_login($username,$password) { $q_params = array('username' =&gt; $username,'password' =&gt; $password); $result = $this-&gt;query("SELECT * FROM a_users where user_name = :username AND password = :password",$q_params); return $result; } public function reset_password($username,$seed) { $q_params = array('username' =&gt; $username,'active' =&gt; '1','reset' =&gt; '1','reset_key' =&gt; $seed); $result = $this-&gt;query_update("UPDATE a_users SET password_reset = :reset,password_reset_key = :reset_key where user_name = :username AND active = :active",$q_params); return $result; } public function check_reset($username) { $q_params = array('username' =&gt; $username,'active' =&gt; '1'); $result = $this-&gt;query("SELECT * FROM a_users where user_name = :username AND active = :active",$q_params); return $result; } public function get_user($user_id,$random) { $q_params = array('password_reset_key' =&gt; $random,'user_id' =&gt; $user_id, 'active' =&gt; '1'); $result = $this-&gt;query("SELECT * FROM a_users where user_id = :user_id AND password_reset_key = :password_reset_key AND active = :active",$q_params); return $result; } public function change_password($user_id,$password) { $q_params = array('password_reset' =&gt; 0,'password' =&gt; $password,'user_id' =&gt; $user_id, 'active' =&gt; '1'); $result = $this-&gt;query_update("UPDATE a_users SET password = :password, password_reset = :password_reset where user_id = :user_id AND active = :active",$q_params); return $result; } } ?&gt; </code></pre>
[]
[ { "body": "<p>From an MVC perspective, your controllers are doing far too much. Anything that's related processing on domain concepts (users, logins, products, etc) belongs in the model. </p>\n\n<p>The entire point of MVC is Separation of Concerns so that each component is reusable/replaceable.</p>\n\n<p>To test Separation of Concerns there are a few questions you can ask:</p>\n\n<p><strong>Are any of the components tightly coupled to the others?</strong></p>\n\n<p>In this case, both your models and views are very tightly coupled to your controllers. It's impossible for you to use a different view or model with that controller because the logic that chooses which view to use and which model to use exists within the controller itself. SoC would suggest separating these responsibilities.</p>\n\n<p><strong>If I replace a component will that involve repeating code?</strong></p>\n\n<p>If replacing a component requires rewriting lines of code this is a good indicator of poor Separation of Concerns. In your example, it's impossible to substitute the controller without repeating a lot of code. This limits flexibility and adds extra work. If you then update your view (which should be reusable) you then need to update every single controller that uses the view.</p>\n\n<p>Controllers are not mediators between models and views. They take user input, update the model in some manner then the view requests relevant data from the model. See my answer here: <a href=\"https://codereview.stackexchange.com/questions/19592/small-mvc-for-php/19593#19593\">Small MVC for PHP</a> for a discussion about a very similar implementation.</p>\n\n<p>For your implementation specifically logic in the form of \"Display this if the user is logged in else display this\" is by definition display logic. As such, it belongs in the view and not the controller. </p>\n\n<p>The controller should not be telling the view to render. In fact, in a web MVC implementation, the controller doesn't even need to know of the view's existence (and in the implementations that do it's for a very specific reason). See the wikipedia diagram on MVC:</p>\n\n<p><img src=\"https://i.stack.imgur.com/AwSaC.png\" alt=\"Model-view-controller\"></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller</a></p>\n\n<p>Which states: \"A view requests from the model the information that it needs to generate an output representation.\"</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T17:06:20.513", "Id": "31576", "Score": "0", "body": "Thank you for the detailed response that's really very helpful I don't think I fully understood the MVC approach and will do some more reading. It's hard to get my head around it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T00:08:11.673", "Id": "31595", "Score": "1", "body": "A controller is the part of the software that gets in touch with the outside world. In case of a HTTP application, this is a HTTP request. The controller should only fetch the data from this request, pass it into the appropriate model and trigger what has to be done with it. Eventually some data comes back from the model that should go back to the user - via HTTP because that's what the controller knows. A good model allows to be used in different situations like \"Desktop application needs login\" - no HTTP, but user name and password, and \"access allowed\" or not as response." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T15:25:25.053", "Id": "19743", "ParentId": "19738", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T14:05:11.990", "Id": "19738", "Score": "2", "Tags": [ "php", "mvc" ], "Title": "PHP Mvc code review" }
19738
<p>I was fixing a bug in the code and it was something like this:</p> <pre><code>int const ROW_LOC = 1; //.... Foo ( x , y , ROW_LOC ) ; </code></pre> <p>so it was passing that constant to a method ... and this ROW_LOC constant is being used in multiple other places in the code too.</p> <p>For ONLY ONE place in the code because this constant was getting passed to some method that was working with a zero-based index I did like this:</p> <pre><code>SomeOtherFooMethd ( x , str , ROW_LOC -1 ); </code></pre> <p>So my question is: Do I need to create a separate constant with value Zero for this one method call or you would continue using the same ROW_LOC and like I did just decremneting it by 1 in this case? </p>
[]
[ { "body": "<p>It depends on the meaning of this constant. If the value <code>ROW_LOC - 1</code> has logical relation to <code>ROW_LOC</code> (e.g. it means that it should go right before <code>ROW_LOC</code> in some list) then just use <code>ROW_LOC - 1</code> there, but if it's just <code>0</code> - then either define a new constant or just use <code>0</code> as value, depending on situation.</p>\n\n<p>What I would suggest is to rename <code>ROW_LOC</code> to more meaningful (descriptive) name unless it's a well-known acronym in your company.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T15:29:29.923", "Id": "31568", "Score": "0", "body": "yeah on the second method it should have been ROW_LOC too but there was a bug and that method was using zero-based so I used \"ROW_LOC -1 \" so I think that fits in the \"logical relation to ROW_LOC\"that you mentioned." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T15:14:22.883", "Id": "19742", "ParentId": "19741", "Score": "4" } } ]
{ "AcceptedAnswerId": "19742", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T14:52:53.037", "Id": "19741", "Score": "2", "Tags": [ "c#" ], "Title": "Should we create a new constant or modify an existing one" }
19741
<p>I have following method which highlight matched word in text: </p> <pre><code># Hightlight matched term # # Ex(for term: some): # "&lt;span class="bold"&gt;Some&lt;/span&gt; CEO Event" # def highlight_matched(matched_word, text) regex = matched_word.gsub(/\*|\"|\'/, "") .split(" ") .map { |s| "\\b#{s}" }.join('|') text.gsub(/(#{regex})/i, '&lt;span class="bold"&gt;\1&lt;/span&gt;') end </code></pre> <p>Is there a better solution for that?</p> <p>I am using it here:</p> <pre><code>"%s %s" %[highlight_matched(title[0..70]), content_tag(:span, caption, class: 'search-type')] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T20:06:23.063", "Id": "31585", "Score": "0", "body": "Is `text` pure text or HTML? can you add to the question some asserts?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T20:18:21.813", "Id": "31586", "Score": "0", "body": "Text is ``HTML``" } ]
[ { "body": "<p>You should use a better class name, such as <code>highlighted</code> or <code>search-term</code> or <code>search-match</code>.</p>\n\n<h1>Bug</h1>\n\n<p>Your solution will break anchors, or titles, or other hmtl properties:</p>\n\n<pre><code># Yields: \"Broken &lt;a href='http://www.example.org/&lt;span&gt;cat&lt;/span&gt;nip'&gt;example&lt;/a&gt;.\"\nputs highlight_matched(\"cat\", \"Broken &lt;a href='http://catnip.com'&gt;example&lt;/a&gt;.\")\n</code></pre>\n\n<h2>Another potential problem</h2>\n\n<p>And if you repeatedly run it on the same text with a list of words, you will get nested replacements if you don't have the words sorted by size-descending and replace a word (\"cat\") that is a substring of a previous replacement (\"catnip\").</p>\n\n<p>This might be, or not, a problem.<br>\nFor me it was, because I was replacing with anchors and HTML does not allow nested anchors.<br>\nFor you it might be, too, depending on how you wish to style the matches.</p>\n\n<pre><code>intermediate = highlight_matched(\"catnip\", \"I love catnip!\")\n# Yields: \"I love &lt;span&gt;&lt;span&gt;cat&lt;/span&gt;nip&lt;/span&gt;!\"\nputs highlight_matched(\"cat\", intermediate)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T16:55:40.553", "Id": "19746", "ParentId": "19744", "Score": "3" } }, { "body": "<p>If <code>text</code> may contain HTML (in that case <code>text</code> is a somewhat misleading variable name) you definitely should use a HTML parser. What about this? (adding a <code>&lt;p&gt;</code> as wrapper, otherwise xpath won't find parent text nodes).</p>\n\n<pre><code>require 'nokogiri'\n\ndef highlight(html, word)\n Nokogiri::HTML::fragment(\"&lt;p&gt;\" + html + \"&lt;/p&gt;\").tap do |doc|\n doc.search('.//text()').each do |text_node|\n new_contents = text_node.text.gsub(/\\b(#{word})\\b/i, '&lt;span class=\"bold\"&gt;\\1&lt;/span&gt;')\n text_node.replace(new_contents)\n end\n end.xpath(\"p\").inner_html\nend\n\nputs highlight('&lt;p&gt;&lt;a href=\"http://runner.com\"&gt;Run Rabbit Run&lt;/a&gt;&lt;/p&gt;', \"run\")\n# &lt;p&gt;&lt;a href=\"http://runner.com\"&gt;&lt;span class=\"bold\"&gt;Run&lt;/span&gt; \n# Rabbit &lt;span class=\"bold\"&gt;Run&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T14:22:35.540", "Id": "31618", "Score": "0", "body": "hmm, it not works for me: https://gist.github.com/b5015d8932990efc786b" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T14:25:51.217", "Id": "31619", "Score": "0", "body": "sometimes text has HTML tags sometimes not, like above" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T14:32:27.970", "Id": "31622", "Score": "0", "body": "Here is my output: https://gist.github.com/a03d7b44aa70cb6e0345" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T14:37:30.603", "Id": "31623", "Score": "0", "body": "I am using ``1.9.3``and nokogiri ``1.5.5``" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T15:41:47.057", "Id": "31625", "Score": "0", "body": "oh, I see, the problem is that xpath won't get parent text nodes." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T14:09:53.733", "Id": "19783", "ParentId": "19744", "Score": "4" } } ]
{ "AcceptedAnswerId": "19783", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T15:58:51.893", "Id": "19744", "Score": "6", "Tags": [ "ruby", "ruby-on-rails", "regex" ], "Title": "Refactor highlight matched word in string" }
19744
<p>I have a mixin function which is as follows - </p> <pre><code>function mixin(receiver, supplier) { for (var property in supplier) { if (supplier.hasOwnProperty(property)) { receiver[property] = supplier[property]; } } } </code></pre> <p>To test this function, I am using the <code>ok</code> method of Qunit - </p> <pre><code>test('Mixin Test Runner', function () { // using OK method ok(function () { var receiver = { name: 'Abul Moksud', age: '60' }; var supplier = { hands: 2 }; mixin(receiver, supplier); return receiver.hasOwnProperty('hands') &amp;&amp; (receiver.hands === 2); }(), "Abul Moksud now has two hands"); }); </code></pre> <p>I am an absolute beginner in both unit testing and QUnit. Is my approach OK here, or is there any better option?</p>
[]
[ { "body": "<p>Your code is correct, but can be simplified. <code>ok</code> method usually gets an expression rather than a in-place function that is immediately evaluated.</p>\n\n<p>Here is how I would write this test:</p>\n\n<pre><code>test('Mixin Test Runner', function () {\n var receiver = {\n name: 'Abul Moksud',\n age: '60'\n };\n\n var supplier = {\n hands: 2\n };\n\n mixin(receiver, supplier);\n\n //Assertion phase\n ok(receiver.hasOwnProperty(\"hands\"), \"hands property is defined on reciever\");\n equal(receiver.hands, 2, \"Abul Moksud now has two hands\");\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T17:44:27.143", "Id": "19750", "ParentId": "19745", "Score": "2" } } ]
{ "AcceptedAnswerId": "19750", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T16:05:30.073", "Id": "19745", "Score": "2", "Tags": [ "javascript", "unit-testing" ], "Title": "Testing a mixin function" }
19745
<p>I have this <a href="http://plus.maths.org/content/os/issue50/features/havil/index" rel="nofollow noreferrer">Sundaram's sieve</a> to generate prime numbers up to <code>limit</code> in Common Lisp.</p> <pre><code>(defun sundaram-sieve (limit) (let ((numbers (range 3 (+ limit 1) 2)) (half (/ limit 2)) (start 4)) (dolist (step (range 3 (+ limit 1) 2)) (dolist (i (range start half step)) (setf (nth (- i 1) numbers) 0)) (setq start (+ start (* 2 (+ step 1)))) (if (&gt; start half) (return (cons 2 (remove-if #'zerop numbers))))))) </code></pre> <p>Here <code>range</code> is <a href="https://stackoverflow.com/a/13937652/596361">defined</a> as:</p> <pre><code>(defun range (min max step) (loop for n from min below max by step collect n)) </code></pre> <p>How can i make the code above more functional and idiomatic? The use of <code>setq</code> and <code>setf</code> bothers me, not to mention that it takes 10 seconds to calculate with <code>limit</code> equal 100000, when the equivalent code in Python runs almost instantly.</p>
[]
[ { "body": "<pre><code> (let ((numbers (range 3 (+ limit 1) 2))\n</code></pre>\n\n<p>Above defines a list of numbers. Later you set various numbers to zero. That's not good for a list structure. Use a vector, an one-dimensional array.</p>\n\n<pre><code>(dolist (step (range 3 (+ limit 1) 2))\n</code></pre>\n\n<p>Creating the list and then iterating over it makes no sense. Use a LOOP statement directly.</p>\n\n<pre><code> (dolist (i (range start half step))\n</code></pre>\n\n<p>Creating the list and then iterating over it makes no sense. Use a LOOP statement directly.</p>\n\n<p>Example:</p>\n\n<pre><code>(defun sundaram-sieve (limit)\n (let ((numbers (coerce (cons 2 (range 3 (+ limit 1) 2)) 'vector))\n (half (/ limit 2))\n (start 4))\n (loop for step from 3 upto limit by 2 do\n (loop for i from start below half by step do\n (setf (aref numbers i) 0))\n (incf start (* 2 (1+ step)))\n (when (&gt; start half)\n (return (remove 0 numbers))))))\n</code></pre>\n\n<p>Runs fast.</p>\n\n<pre><code>CL-USER 36 &gt; (time (sundaram-sieve 100000))\nTiming the evaluation of (SUNDARAM-SIEVE 100000)\n\nUser time = 0.007\nSystem time = 0.000\nElapsed time = 0.004\nAllocation = 1646136 bytes\n0 Page faults\n#(2 3 5 7 11 13 17 ... 99971 99989 99991)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T22:52:01.900", "Id": "19791", "ParentId": "19747", "Score": "5" } }, { "body": "<p>You don't need to iterate up to <code>limit</code> but only up to <code>(isqrt limit)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T16:51:56.503", "Id": "526634", "Score": "0", "body": "This may be true, but would be more readable if you would include which line that currently says `limit` may be changed to `isqrt limit`. Presumably you are talking about factors rather than the outer loop." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T15:39:33.830", "Id": "266558", "ParentId": "19747", "Score": "1" } } ]
{ "AcceptedAnswerId": "19791", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T17:02:54.470", "Id": "19747", "Score": "7", "Tags": [ "functional-programming", "common-lisp", "primes" ], "Title": "Sundaram's sieve in Common Lisp" }
19747
<p>I've been on stackoverflow looking for an alternative to the ugly if-elif-else structure shown below. The if-else structure takes three values as input and returns a pre-formatted string used for an SQL query. The code works right now, but it is difficult to explain, ugly, and I don't know a better way to do re-format it. </p> <p>I need a solution that is more readable. I was thinking a dictionary object, but I can't wrap my mind how to implement one with the complex if/else structure I have below. An ideal solution will be more readable. </p> <pre><code>def _getQuery(activity,pollutant,feedstock): if feedstock.startswith('CG') and pollutant.startswith('VOC'): pass if feedstock == 'FR' and activity == 'Harvest': return 'FR' elif feedstock == 'FR': return 'No Activity' elif(activity == 'Fertilizer' and pollutant != 'NOx' and pollutant != 'NH3'): return 'No Activity' elif(activity == 'Chemical' and pollutant != 'VOC'): return 'No Activity' elif( (feedstock == 'CS' or feedstock == 'WS') and (activity == 'Non-Harvest' or activity == 'Chemical')): return 'No Activity' elif( ( ( pollutant.startswith('CO') or pollutant.startswith('SO') ) and ( activity == 'Non-Harvest' or activity == 'Harvest' or activity == 'Transport' ) ) or ( pollutant.startswith('VOC') and not ( feedstock.startswith('CG') or feedstock.startswith('SG') ) ) ): rawTable = feedstock + '_raw' return """ with activitySum as (select distinct fips, sum(%s) as x from %s where description ilike '%s' group by fips), totalSum as (select distinct r.fips, sum(r.%s) as x from %s r group by r.fips), ratios as (select t.fips, (a.x/t.x) as x from activitySum a, totalSum t where a.fips = t.fips), maxRatio as (select r.fips, r.x as x from ratios r group by r.fips, r.x order by x desc limit 1), minRatio as (select r.fips, r.x as x from ratios r group by r.fips, r.x order by x asc limit 1) select mx.x, mn.x from maxRatio mx, minRatio mn; """ % (pollutant, rawTable, '%'+activity+'%', pollutant, rawTable) elif( (pollutant[0:2] == 'PM') and (activity == 'Non-Harvest' or activity == 'Harvest' or activity == 'Transport')): rawTable = feedstock + '_raw' return """ with activitySum as (select distinct fips, (sum(%s) + sum(fug_%s)) as x from %s where description ilike '%s' group by fips), totalSum as (select distinct r.fips, (sum(r.%s) + sum(r.fug_%s)) as x from %s r group by r.fips), ratios as (select t.fips, (a.x/t.x) as x from activitySum a, totalSum t where a.fips = t.fips), maxRatio as (select r.fips, r.x as x from ratios r group by r.fips, r.x order by x desc limit 1), minRatio as (select r.fips, r.x as x from ratios r group by r.fips, r.x order by x asc limit 1) select mx.x, mn.x from maxRatio mx, minRatio mn; """ % (pollutant, pollutant, rawTable, '%'+activity+'%', pollutant, pollutant, rawTable) . . . Lots more complex elif statements </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T21:03:41.157", "Id": "31588", "Score": "1", "body": "I'm not sure it's possible to answer this without knowing more about the range of possible parameters and return values. It might be worth creating more variables with meaningful names that would help make clear why certain combinations of parameter values result in a particular output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T22:19:50.857", "Id": "31590", "Score": "0", "body": "@Stuart, should I include the full if/elif structure in the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T00:03:34.130", "Id": "31594", "Score": "0", "body": "It might help if it's not *terribly* long. To start with, though, I would note that there is a lot of repetition in the long query string `\"\"\"with activitySum etc.` which appears twice with only minor changes. Maybe see if you can use the `if/elif` structure to set values of variables with meaningful names which are then sanitised and fed into a single 'template' query string at the end." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T16:24:03.633", "Id": "31630", "Score": "0", "body": "@Stuart, thanks for pointing out the code duplicate, by removing the duplicates, the code is looking more reasonable. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T20:40:02.157", "Id": "31639", "Score": "0", "body": "It can't be right to return a SQL query in some cases, and the string `'No Activity'` in others." } ]
[ { "body": "<p>My thought would be to create a collection of objects that can be iterated over. Each object would have an interface like the following.</p>\n\n<pre><code>def _getQuery(activity,pollutant,feedstock):\n for matcher in MATCHERS:\n if matcher.matches(activity,pollutant,feedstock):\n return matcher.get_result(activity,pollutant,feedstock)\n raise Exception('Not matched')\n</code></pre>\n\n<p>Then you build up the set of matcher classes for the various cases and ad an instance of each to <code>MATCHERS</code>. Just remember that earlier elements in the list take precedence to later ones. So the most specific cases should be first in the list ans the most general cases should be at the end.</p>\n\n<p><strong>NOTE</strong>: \nYour string building code is vulnerable to <a href=\"http://en.wikipedia.org/wiki/SQL_injection\">SQL-injection</a>. If you do go forward with manually building your selection strings, your input needs to be more thoroughly sanitized.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T16:24:51.607", "Id": "31631", "Score": "0", "body": "thanks for your comments, especially the part about SQL-injection! I was hoping for a more object-oriented approach and this seems quite reasonable!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T22:36:48.600", "Id": "19756", "ParentId": "19753", "Score": "6" } } ]
{ "AcceptedAnswerId": "19756", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T19:54:14.617", "Id": "19753", "Score": "2", "Tags": [ "python", "sql" ], "Title": "Constructing an SQL expression from three parameters" }
19753
<p>So I started wondering why it takes 3.5 seconds to <code>AcceptChanges</code> for one changed record in a large <code>DataTable</code>. I wrote another implementation of <code>AcceptChanges</code> (VB.NET) - <code>Me</code> is a <code>DataTable</code> here:</p> <pre class="lang-vb prettyprint-override"><code>Public Shadows Sub AcceptChanges() 'this way AcceptChanges is 35 to 700 faster than Microsoft's way '35 is a speed factor when all rows were changed, and 700 is when a few 'Tested on sets of 13K and 65K records Dim updatedRows() As DataRow = Me.Select(Nothing, Nothing, _ DataViewRowState.Added Or DataViewRowState.Deleted Or _ DataViewRowState.ModifiedCurrent Or DataViewRowState.ModifiedOriginal) For Each row As DataRow In updatedRows row.AcceptChanges() Next End Sub </code></pre> <p>It appears to be from 35 to 700 times faster than Microsoft's implementation. Did I just uncover/solve a great mystery of ADO.NET, or am I missing something here?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T15:01:17.397", "Id": "31953", "Score": "0", "body": "I am not fluent in VB, but there must be a reason why they put _two_ try clauses in the function. My guess is that your function is more efficient but less robust." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T15:51:03.897", "Id": "31954", "Score": "0", "body": "@DennisJaheruddin: there isn't anything VB-specific in the above code. Do you have trouble reading it? I can translate into C# for you, if you want. Wrapping it into a Try clause will not decrease performance. Main side of my question is when I will regret about changing to this implementation, instead of Microsoft's AcceptChanges. Every single test I did, performance wise, points that I am on the right track." } ]
[ { "body": "<p>It's quite easy to answer your question by looking at the <a href=\"http://typedescriptor.net/browse/members/388932-System.Data.DataTable.AcceptChanges%28%29\" rel=\"nofollow\"><code>DataTable.AcceptChanges</code> source code</a>.</p>\n\n<p>As you can see they copy all <code>DataRow</code> objects into new array before iterating them. I suspect that your code will work incorrectly when rows are deleted (accepting changes for deleted rows means removing them from <code>DataTable</code>), most likely you'll get exception since it's not allowed to change collection while iterating it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T21:45:19.333", "Id": "31821", "Score": "1", "body": "Thanks for your feedback. `Me.Select` returns an array of `DataRow`, which is not the original `DataRows` collection. So I cannot see a problem here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T21:46:46.540", "Id": "31822", "Score": "0", "body": "A good question would be when `SuspendIndexEvents` and `RestoreIndexEvents` would play a part (i.e. make it faster than my implementation), if ever." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T21:19:10.357", "Id": "19906", "ParentId": "19754", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T20:13:32.343", "Id": "19754", "Score": "2", "Tags": [ "vb.net", ".net-datatable" ], "Title": "A faster implementation of AcceptChanges?" }
19754
<p>I want your suggestions on this algorithm:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace FCFS_Console { class Program { static void Main(string[] args) { //----------------------------------------Reading I/O File-------------------------------------- string s = Environment.CurrentDirectory.ToString(); // returns the directory of the exe file if (File.Exists(s + @"\input.txt")) //checking if the input files exists Console.WriteLine("File Exists"); else { Console.WriteLine("File Not Found"); Console.WriteLine("_________________________________________________________________"); return; } Console.WriteLine("_________________________________________________________________"); //----------------------------------------Data Into List-------------------------------------- string FileText = File.ReadAllText(s + @"\input.txt"); //reading all the text in the input file string[] lines = FileText.Split('\n'); //splitting the lines List&lt;Process&gt; processes = new List&lt;Process&gt;(); for (int i = 1; i &lt; lines.Length; i++) { string[] tabs = lines[i].Split('\t');//splitting the tabs to get objects' variables Process x = new Process(tabs[0], int.Parse(tabs[1]), int.Parse(tabs[2]), int.Parse(tabs[3]));//creating object processes.Add(x);//adding object to the list } // ----------------------------------------Sorting The List-------------------------------------- Process temp; for (int k = 0; k &lt; processes.Count; k++) { for (int i = k + 1; i &lt; processes.Count; i++) { if (processes[k].arrivalTime &gt; processes[i].arrivalTime || (processes[k].arrivalTime == processes[i].arrivalTime &amp;&amp; processes[k].brust &gt; processes[i].brust)) { temp = processes[i]; processes[i] = processes[k]; processes[k] = temp; } } } Console.WriteLine("Processes After Sorting"); Console.WriteLine("_________________________________________________________________"); Console.WriteLine("Name\tArrival\tBrust\tPriority"); for (int i = 0; i &lt; processes.Count; i++) { Console.Write(processes[i].name + "\t" + processes[i].arrivalTime + "\t" + processes[i].brust + "\t" + processes[i].priority); Console.WriteLine(); } Console.WriteLine("_________________________________________________________________"); //----------------------------------------Gantt Chart-------------------------------------- Console.WriteLine("Gantt Chart"); Console.WriteLine("_________________________________________________________________"); int counter = 0; for (int i = 0; i &lt; processes.Count; i++) { Console.Write(processes[i].name + "\t"); if (processes[i].arrivalTime &lt; counter) printSpaces(counter); else { printSpaces(processes[i].arrivalTime); counter = processes[i].arrivalTime; } printHashes(processes[i].brust); counter += processes[i].brust; Console.WriteLine(); } Console.WriteLine("_________________________________________________________________"); //-----------------------------------Completing Data And final Table------------------------- int clock = 0, totalwait = 0, totalturnAround = 0; for (int i = 0; i &lt; processes.Count; i++) { if (processes[i].arrivalTime &gt; clock) { processes[i].start = processes[i].arrivalTime; clock += processes[i].start - processes[i].arrivalTime; clock += processes[i].brust; } else { if (i &gt; 0) processes[i].start = processes[i - 1].end; clock += processes[i].brust; } if (processes[i].start &gt; processes[i].arrivalTime) processes[i].wait = processes[i].start - processes[i].arrivalTime; else processes[i].wait = 0; processes[i].end = processes[i].start + processes[i].brust; processes[i].turnAround = processes[i].wait + processes[i].brust; totalwait += processes[i].wait; totalturnAround += processes[i].turnAround; } Console.WriteLine("Name\tArrival\tBrust\tStart\tEnd\tWait\tturnaround"); for (int i = 0; i &lt; processes.Count; i++) { Console.Write(processes[i].name + "\t" + processes[i].arrivalTime + "\t" + processes[i].brust + "\t" + processes[i].start + "\t" + processes[i].end + "\t" + processes[i].wait + "\t" + processes[i].turnAround); Console.WriteLine(); } double att = 0, awt = 0; awt = (double)totalwait / (double)processes.Count; att = (double)totalturnAround / (double)processes.Count; Console.WriteLine("A.W.T= " + awt + "\t A.T.T= " + att); Console.ReadKey(); } public static void printSpaces(int counter) { for (int i = 0; i &lt; counter; i++) { Console.Write(" "); } } public static void printHashes(int brust) { for (int i = 0; i &lt; brust; i++) { Console.Write("#"); } } } } </code></pre> <p>Process Class</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FCFS_Console { class Process { public Process(string name, int arrivalTime, int brust, int priority) { this.name = name; this.arrivalTime = arrivalTime; this.brust = brust; this.priority = priority; } public Process() { } public string name; public int arrivalTime; public int brust; public int priority; public int wait; public int end; public int start; public int turnAround; } } </code></pre> <p>Procedure:</p> <ol> <li>created the <code>Process</code> class</li> <li>received my input from a text file</li> <li>used a list to store my processes</li> <li>created objects from the class</li> <li>sorted the list</li> <li>printed the Gantt Chart</li> <li>completed the rest of the process data like start, end, turn around, wait</li> <li>printed the final table</li> <li>calculated the average wait time and the average turn around time</li> </ol>
[]
[ { "body": "<p>Here is a sample solution you can use to improve you code,. I have created a simple processor class to do processing logic in which input string will be passed from you console application and processor will generate the according to configured writer. (This code can be re factored too).let me know if you have doubts.</p>\n\n<pre><code> public interface IWriter\n {\n void WriteMessage(string msg);\n }\n\n\n public class ConsoleWriter : IWriter\n {\n #region Implementation of IWriter\n\n public void WriteMessage(string msg)\n {\n Console.WriteLine(msg);\n }\n\n #endregion\n }\n\n public class Processor\n {\n private readonly string _inputText;\n private IEnumerable&lt;string&gt; _lines;\n private IEnumerable&lt;Process&gt; _processes;\n private IWriter _writer;\n\n public Processor(string inputText)\n {\n _processes=new List&lt;Process&gt;();\n _inputText = inputText;\n _lines = inputText.Split('\\n');\n InitializeComponent();\n }\n\n private void InitializeComponent()\n {\n _processes= _lines.Select(line =&gt; line.Split('\\t')).\n ToList().\n Select(elem =&gt; new Process(elem[0], int.Parse(elem[1]),\n int.Parse(elem[2]),\n int.Parse(elem[3])));\n\n }\n\n public void Process(IWriter writer)\n {\n _writer = writer;\n Sort();\n PrepareGantt();\n CompletingDataAndfinalTable();\n }\n\n private void CompletingDataAndfinalTable()\n {\n _writer.WriteMessage(\"Your implementation!\");\n\n }\n\n private void PrepareGantt()\n {\n _writer.WriteMessage(\"Your implementation!\");\n }\n\n private void Sort()\n {\n _writer.WriteMessage(\"Your implementation!\");\n }\n }\n</code></pre>\n\n<p>Actually what i understood from your code is that you want two thing : </p>\n\n<blockquote>\n <ol>\n <li>Processing the string in different format </li>\n <li>Displaying the result.</li>\n </ol>\n</blockquote>\n\n<p>For this reason I have abstracted out the processor and logger code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T18:42:55.067", "Id": "31635", "Score": "0", "body": "looks good but thats not very different i want to improve the algorithm if possible if u could help me i'd be thankful" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T18:51:49.423", "Id": "31636", "Score": "0", "body": "what you want to improve in algo improvement? cleaner code, timing issues, give me more insights on the same" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T21:00:27.413", "Id": "31640", "Score": "0", "body": "I Want it To Be Cleaner And Faster.especially faster is more important to me" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T11:08:28.873", "Id": "19775", "ParentId": "19755", "Score": "1" } }, { "body": "<pre><code>//Don't use this code. Bubble Sort is slow.\nfor (int k = 0; k &lt; processes.Count; k++)\n{\n for (int i = k + 1; i &lt; processes.Count; i++)\n {\n if (processes[k].arrivalTime &gt; processes[i].arrivalTime || \n (processes[k].arrivalTime == processes[i].arrivalTime &amp;&amp;\n processes[k].brust &gt; processes[i].brust))\n {\n temp = processes[i];\n processes[i] = processes[k];\n processes[k] = temp;\n }\n }\n}\n</code></pre>\n\n<p>Bubble sort is very slow when run on medium or large lists. I recommend using a faster sort algorithm (e.g., Quick Sort), or using C#'s built-in sorting functions (e.g., the <code>OrderBy</code> extension method). If you prefer to minimize how much you need to change your existing code, the code for Comb Sort is almost identical to that of bubble sort, while still running significantly faster. That said, Comb sort is a bit less popular (and thus less well-understood) than other algorithms of similar efficiency.</p>\n\n<p>You may want extract each step in your algorithm (Sort, Chart, etc.) into a separate method.</p>\n\n<p>If speed is important to you, a profiler will tell you which step is worth optimizing first.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T13:04:07.077", "Id": "31660", "Score": "0", "body": "could u show me how to use comb sort or quick sort" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T14:02:09.393", "Id": "31665", "Score": "0", "body": "The C implementation of comb sort on wikipedia should be pretty easy to convert to C# code: http://en.wikipedia.org/w/index.php?title=Comb_sort&oldid=526829614#C . The difference between comb sort and bubble sort is that the initial iterations of comb sort swaps elements that are far apart whereas in bubble sort every iteration swaps only adjacent elements." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T21:47:24.407", "Id": "19788", "ParentId": "19755", "Score": "2" } }, { "body": "<p>Instead of</p>\n\n<p><code>s + @\"\\input.txt\"</code></p>\n\n<p>use <code>Path.Combine</code>.</p>\n\n<p>According to StyleCop (and I agree), <code>using</code> blocks should be on the inside of the namespace declaration.</p>\n\n<p><code>FileText</code> should be camelCase.</p>\n\n<p>You should not <code>Split('\\n')</code>. Use <code>File.ReadLines</code>.</p>\n\n<p>Wherever appropriate, you should be using <code>foreach</code> instead of <code>for</code> with a counter.</p>\n\n<p>You should not implement your own sorting algorithm. The built-in .NET sorting methods should be used.</p>\n\n<p><code>printSpaces</code> should be replaced by printing <code>new String(' ', counter)</code> (similar for <code>printHashes</code>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-29T02:33:53.820", "Id": "71135", "ParentId": "19755", "Score": "1" } } ]
{ "AcceptedAnswerId": "19788", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T20:53:15.497", "Id": "19755", "Score": "4", "Tags": [ "c#", "algorithm" ], "Title": "First-come first-serve (FCFS) algorithm" }
19755
<p>This is a command line BlackJack game created in Java as my final project for an advanced programming class.</p> <ul> <li>What do you think about it? </li> <li>Have I used OOP correctly?</li> <li>What grade should I get for this? :D</li> <li>Any concept in game that could be improved? </li> </ul> <p>I used JRE 1.7. And to make Unicode characters work you must use Unicode in Eclipse.</p> <p>This is my Class Diagram:</p> <p><img src="https://i.stack.imgur.com/6oSKu.png" alt="enter image description here"></p> <p><strong>BlackJack.java</strong></p> <pre><code>import java.io.*; public class BlackJack { private static int BLACKJACK = 21; private static int DECKSIZE = 52; private static boolean isPlayerDone; public static void main(String[] args) throws IOException { Deck deck = null; Hand playersHand = null; Hand splitHand = null; Hand dealersHand = null; System.out.println("--------------------------------------------------------"); System.out.println("- BLACK JACK -"); System.out.println("--------------------------------------------------------\n"); boolean runGame = true; while(runGame) switch(options()) { case "deal": dealersHand = new Hand("Dealer"); playersHand = new Hand("Player"); splitHand = null; isPlayerDone = false; deck = initialDraw(deck, playersHand, splitHand, dealersHand); if (playersHand.getHandTotal() == BLACKJACK) { System.out.print("Player has BLACKJACK!\n\n"); isPlayerDone = true; System.out.print("Dealer uncovers card...\n\n"); showHands(playersHand, splitHand, dealersHand); System.out.print("Dealer's move...\n\n"); deck = dealerDraw(deck, playersHand, splitHand, dealersHand); showHands(playersHand, splitHand, dealersHand); compareHands(playersHand, splitHand, dealersHand); } // end if() break; // end case "deal" case "hit": if(!isPlayerDone) deck = hit(deck, playersHand, splitHand, dealersHand); else System.out.print("You must deal cards first!\n\n"); break; // end case "hit" case "stand": if(!isPlayerDone) { isPlayerDone = true; deck = stand(deck, playersHand, splitHand, dealersHand); } // end if() else System.out.print("You must deal cards first!\n\n"); break; // end case "stand" case "split": if(!isPlayerDone) splitHand = split(playersHand, splitHand, dealersHand); else System.out.print("You must deal cards first!\n\n"); break; // end case "split" case "exit": runGame = false; System.out.print("Game ended.\n\n"); break; // end case "exit" default: System.out.print("Invalid entry\n\n"); } // end switch() } // end main() private static Hand split(Hand player, Hand split, Hand dealer) { if(player == null) System.out.print("You must deal cards first!\n\n"); else if(player.getHandSize() == 2 &amp;&amp; player.bothEqual()) { split = new Hand("Player"); split.insert(player.deleteFirst()); showHands(player, split, dealer); compareHands(player, split, dealer); } // end else if() else if(!player.bothEqual()) System.out.print("Both card values must be the same!\n\n"); else System.out.print("You must have no more than 2 cards to split!\n\n"); return split; } // end split() private static Deck stand(Deck deck, Hand player, Hand split, Hand dealer) { if(player == null) System.out.print("You must deal cards first!\n\n"); else { isPlayerDone = true; System.out.print("Dealer uncovers card...\n\n"); showHands(player, split, dealer); System.out.print("Dealer's move...\n\n"); deck = dealerDraw(deck, player, split, dealer); showHands(player, split, dealer); compareHands(player, split, dealer); } // end else return deck; } // end stay() private static Deck hit(Deck deck, Hand player, Hand split, Hand dealer) { if(player == null) System.out.print("You must deal cards first!\n\n"); else { deck = drawFromDeck(deck, player); System.out.print("\n"); if(split != null) { deck = drawFromDeck(deck, split); System.out.print("\n"); } // end if() showHands(player, split, dealer); compareHands(player, split, dealer); if (player.getHandTotal() == BLACKJACK) { System.out.print("Player has BLACKJACK!\n\n"); isPlayerDone = true; System.out.print("Dealer uncovers card...\n\n"); showHands(player, split, dealer); System.out.print("Dealer's move...\n\n"); deck = dealerDraw(deck, player, split, dealer); showHands(player, split, dealer); compareHands(player, split, dealer); } // end if() else if(player.getHandTotal() &gt; BLACKJACK) { System.out.print("Player Busted!\n\n"); isPlayerDone = true; System.out.print("Dealer uncovers card...\n\n"); showHands(player, split, dealer); compareHands(player, split, dealer); } } // end else return deck; } // end hit() private static Deck dealerDraw(Deck deck, Hand player, Hand split, Hand dealer) { if(player.getHandTotal() &lt;= BLACKJACK) { // Dealer takes a precaution and only draws // if hand total is less than or equal to 16. while(dealer.getHandTotal() &lt;= 16 &amp;&amp; (dealer.getHandTotal() &lt;= player.getHandTotal() || (split != null &amp;&amp; dealer.getHandTotal() &lt;= split.getHandTotal()))) deck = drawFromDeck(deck, dealer); // Player has reached BLACKJACK! // There's no or little chance to win, // dealer risks and draws even if total is high. if (player.getHandTotal() == BLACKJACK || (split != null &amp;&amp; split.getHandTotal() == BLACKJACK)) while(dealer.getHandTotal() &lt; BLACKJACK) deck = drawFromDeck(deck, dealer); } // end if() return deck; } // dealerDraw() private static Deck drawFromDeck(Deck deck, Hand hand) { deck = checkDeck(deck); Card temp = new Card(deck.pop()); if (hand.getName().equals("Dealer") &amp;&amp; !isPlayerDone) { if(hand.getHandSize() &lt; 1) System.out.print("Drawing Dealer's card... X_X"); else System.out.print("Drawing Dealer's card... " + temp.toString()); } // end if() else { if(hand.getName().equals("Dealer")) System.out.print("Drawing Dealer's card... " + temp.toString() + "\n"); else System.out.print("Drawing Player's card... " + temp.toString()); } // end else System.out.print("\n"); hand.insert(temp); return deck; } // end drawFromDeck() private static void compareHands(Hand player, Hand split, Hand dealer) { if (isPlayerDone) { if(player.getHandTotal() &gt; BLACKJACK || (split != null &amp;&amp; split.getHandTotal() &gt; BLACKJACK)) { System.out.print("Player Busted!\n"); if(dealer.getHandTotal() &lt;= BLACKJACK) System.out.print("Dealer Wins!\n\n"); } // end if() else if(dealer.getHandTotal() &gt; BLACKJACK) { System.out.print("Dealer Busted!\n"); if(player.getHandTotal() &lt;= BLACKJACK || (split != null &amp;&amp; split.getHandTotal() &lt;= BLACKJACK)) System.out.print("Player Wins!\n\n"); } // end else if() else if(dealer.getHandTotal() &gt; BLACKJACK &amp;&amp; (player.getHandTotal() &gt; BLACKJACK || (split != null &amp;&amp; split.getHandTotal() &gt; BLACKJACK))) { System.out.print("Both Busted!\n"); } // end else if() else { if((player.getHandTotal() &gt; dealer.getHandTotal() &amp;&amp; player.getHandTotal() &lt;= BLACKJACK) || (split != null &amp;&amp; (split.getHandTotal() &gt; dealer.getHandTotal() &amp;&amp; player.getHandTotal() &lt;= BLACKJACK))) System.out.print("Player Wins!\n\n"); else if((player.getHandTotal() &lt; dealer.getHandTotal() &amp;&amp; dealer.getHandTotal() &lt;= BLACKJACK) || (split != null &amp;&amp; (split.getHandTotal() &lt; dealer.getHandTotal() &amp;&amp; dealer.getHandTotal() &lt;= BLACKJACK))) System.out.print("Dealer Wins!\n\n"); if(player.getHandTotal() == BLACKJACK || (split != null &amp;&amp; split.getHandTotal() == BLACKJACK)) System.out.print("Player has BLACKJACK!\n\n"); if(dealer.getHandTotal() == BLACKJACK) System.out.print("Dealer has BLACKJACK!\n\n"); } // end else } // end if() } // end compareHands() private static Deck checkDeck(Deck deck) { if(deck == null) deck = createDeck(); else if(deck.isEmpty()) { System.out.print("\nDeck is empty! You must create and shuffle new deck of cards!\n\n"); deck = createDeck(); } // end else if() return deck; } // end checkDeck() private static Deck createDeck() { System.out.println("Creating deck..."); Deck deck = new Deck(DECKSIZE); deck.createDeck(); System.out.println("Shuffling deck..."); deck.shuffleDeck(); System.out.print("\n"); return deck; } // end createDeck() private static Deck initialDraw(Deck deck, Hand player, Hand split, Hand dealer) { deck = drawFromDeck(deck, player); deck = drawFromDeck(deck, dealer); deck = drawFromDeck(deck, player); deck = drawFromDeck(deck, dealer); System.out.print("\n"); showHands(player, split, dealer); compareHands(player, split, dealer); return deck; } // end initialDraw() private static void showHands(Hand player, Hand split, Hand dealer) { System.out.print("Dealers Hand:"); if(!isPlayerDone) { dealer.peek(); System.out.print(" X_X = " + dealer.peekValue() + "\n"); } // end if() else { dealer.displayHand(); System.out.print(" = " + (dealer.getHandTotal() == BLACKJACK ? dealer.getHandTotal() + " : BLACKJACK!" : ((dealer.getHandTotal() &gt; BLACKJACK) ? dealer.getHandTotal() + " : BUSTED!" : dealer.getHandTotal())) + "\n"); } // end else System.out.print("Players Hand:"); player.displayHand(); System.out.print(" = " + (player.getHandTotal() == BLACKJACK ? player.getHandTotal() + " : BLACKJACK!" : ((player.getHandTotal() &gt; BLACKJACK) ? player.getHandTotal() + " : BUSTED!" : player.getHandTotal())) + "\n"); if (split != null) { System.out.print("Players Hand:"); split.displayHand(); System.out.print(" = " + (split.getHandTotal() == BLACKJACK ? split.getHandTotal() + " : BLACKJACK!" : ((split.getHandTotal() &gt; BLACKJACK) ? split.getHandTotal() + " : BUSTED!" : split.getHandTotal())) + "\n\n"); } // end if() else System.out.print("\n"); } // end showHands() private static String options() throws IOException { System.out.print("deal, hit, split, stand, exit: "); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); System.out.print("\n"); return s; } // end options() } // end BlackJack </code></pre> <p><strong>Hand.java</strong></p> <pre><code>class Hand { private Card first; private int cardTotal; private String name; private int handSize; public Hand(String name) { first = null; this.name = name; cardTotal = 0; handSize = 0; } // end Hand() public void insert(Card card) { Card newLink = new Card(card); newLink.next = first; if (card.getRank() == 1 &amp;&amp; cardTotal + card.getValue() &gt; 21) cardTotal = cardTotal + (card.getValue() - 10); else cardTotal = cardTotal + card.getValue(); handSize = handSize + 1; first = newLink; } // end insert() public Card deleteFirst() { Card temp = first; first = first.next; cardTotal = cardTotal - temp.getValue(); handSize = handSize - 1; return temp; } // end deleteFirst() public void displayHand() { Card current = first; while(current != null) { current.showCard(); current = current.next; } // end while() } // end displayHand() public boolean isEmpty() { return first == null; } // end isEmpty() public boolean bothEqual() { Card temp = first; return temp != null &amp;&amp; (temp.getValue() == temp.next.getValue()); } // end bothEqual() public void peek() { first.showCard(); } // end peek() public int peekValue() { return first.getValue(); } // end peekValue() public int getHandSize() { return handSize; } // end getHandSize() public String getName() { return name; } // end getName() public int getHandTotal() { return cardTotal; } // end getHandTotal() } // end Hand </code></pre> <p><strong>Deck.java</strong></p> <pre><code>class Deck { private int maxSize; private Card[] stackArray; private int top; public Deck(int s) { maxSize = s; stackArray = new Card[maxSize]; top = -1; } // end Deck() private void push(Card card) { stackArray[++top] = new Card(card); } // end push() public Card pop() { return stackArray[top--]; } // end pop() public boolean isEmpty() { return top == -1; } // end isEmpty() public void shuffleDeck() { Card swap; for (int i = 0; i &lt; stackArray.length; i++) { int r = i + (int) (Math.random() * (stackArray.length - i)); swap = stackArray[i]; stackArray[i] = stackArray[r]; stackArray[r] = swap; } // end for() } // end shuffleDeck() public void createDeck() { String[] suit = {"\u2663", "\u2666", "\u2665", "\u2660"}; int[] rank = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; for (int i = 0; i &lt; rank.length; i ++) { for (int j = 0; j &lt; suit.length; j++) { push(new Card(suit[j], rank[i])); } // end for() } // end for() } // end createDeck() } // end Deck </code></pre> <p><strong>Card.java</strong></p> <pre><code>class Card { public Card next; private String suit; private int rank; Card(String suit, int rank) { this.suit = suit; this.rank = rank; } // end Card() Card(Card card) { suit = card.suit; rank = card.rank; } // end Card() private String getRankName() { if (rank == 1) return "A"; else if (rank == 11) return "J"; else if (rank == 12) return "Q"; else if (rank == 13) return "K"; else return String.valueOf(rank); } // end getRankName() public int getValue() { if (rank == 1) return 11; else if (rank == 11 || rank == 12 || rank == 13) return 10; return rank; } // end getValue() public String getSuit() { return suit; } // end getSuit() public int getRank() { return rank; } // end getRank() public void showCard() { System.out.print(" " + getRankName() + "_" + suit); } // end showCard() @Override public String toString() { return getRankName() + "_" + suit; } // end toString() } // end Card </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T18:58:28.443", "Id": "31638", "Score": "3", "body": "If you ever have a class with only static methods, it is should only be a Utility class (such as for static operations, extracting variables etc). This class is not OO!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-21T14:42:39.807", "Id": "141621", "Score": "0", "body": "what happens if you draw an ace, then a 2, then a 10? (you are supposed to be at 13, but apparently your `Hand.insert` method puts you at 23, it does not appear to keep track of previous aces.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-21T16:22:18.827", "Id": "141639", "Score": "0", "body": "Njzk2, you are right. Never had a time to do this part." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-21T16:24:02.247", "Id": "141640", "Score": "0", "body": "I guess, we could solve this problem by checking the hands after each turn and do compare of the total with both upper and lower bound value of the aces." } ]
[ { "body": "<p>A few notes:</p>\n\n<ol>\n<li><p>I don't think you're utilizing OOP to its full potential in your <code>BlackJack</code> class; all its methods are static and you're passing around too many variables. A cleaner alternative would be to make <code>deck</code>, <code>playersHand</code>, <code>splitHand</code>, and <code>dealersHand</code> class-level variables, change the methods to be non-static, and then you won't have to pass them all around. So something like this:</p>\n\n<pre><code>public class BlackJack {\n\n ...\n\n private Deck deck;\n private Hand splitHand;\n private Hand playersHand;\n private Hand dealersHand;\n private boolean isPlayerDone;\n\n public static void main(String[] args) throws IOException {\n BlackJack blackjack = new BlackJack();\n blackjack.start();\n }\n\n public void start() {\n while(runGame) {\n switch(options()) {\n case \"deal\":\n deal();\n break;\n case \"hit\":\n hit();\n break;\n case \"stand\":\n stand();\n break;\n ...\n }\n }\n }\n\n public void deal() {\n playersHand = new Hand(\"Player\");\n dealersHand = new Hand(\"Dealer\");\n splitHand = null;\n isPlayerDone = false;\n\n ...\n }\n\n ...\n\n}\n</code></pre></li>\n<li><p>The <code>Hand</code> class doesn't really need a <code>name</code> because there are only 2 types of hands: dealer and player. So you can just pass in a <code>boolean</code> for <code>drawFromDeck()</code>:</p>\n\n<pre><code>private Deck drawFromDeck(boolean drawForPlayer) {\n Hand hand = drawForPlayer ? playersHand\n : dealersHand;\n\n ...\n}\n</code></pre></li>\n<li><p>You have several different places where you're checking for blackjack, and I can't easily follow the logic. <code>compareHands()</code> checks for blackjack, but there are a couple other places with some checks too. These might be necessary (I don't know the rules of Blackjack that well), but you should try to minimize duplicate logic as much as possible. For example, this block of code is in both <code>main()</code> and <code>hit()</code>:</p>\n\n<pre><code>if (player.getHandTotal() == BLACKJACK)\n{\n System.out.print(\"Player has BLACKJACK!\\n\\n\");\n isPlayerDone = true;\n System.out.print(\"Dealer uncovers card...\\n\\n\");\n showHands(player, split, dealer);\n System.out.print(\"Dealer's move...\\n\\n\");\n deck = dealerDraw(deck, player, split, dealer);\n showHands(player, split, dealer);\n compareHands(player, split, dealer);\n} // end if()\n</code></pre></li>\n</ol>\n\n<p>I think fixing those (mostly points 1 &amp; 3) would go a long way to making the code easier to read and maintain. I skimmed over your other classes and they seemed fine at a glance, having good <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\">separation of concerns</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T21:35:13.213", "Id": "31641", "Score": "0", "body": "Thanks for yourr feedback. I was wondering with con/pros for global class variables but then decided to try to have as little global variables as possible. I know they would have reduced amount of variables. Overall I guess you are right with your comments. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T15:19:59.387", "Id": "31723", "Score": "0", "body": "@HelpNeeder: is there anything else you wanted me to critique specifically or are you just looking for other opinions?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T04:32:21.353", "Id": "19766", "ParentId": "19760", "Score": "8" } }, { "body": "<p>Some remarks:</p>\n\n<ol>\n<li>Your main method is HUGE, consider splitting it</li>\n<li><p>This code:</p>\n\n<pre><code>deck = drawFromDeck(deck, player);\ndeck = drawFromDeck(deck, dealer);\ndeck = drawFromDeck(deck, player);\ndeck = drawFromDeck(deck, dealer);\n</code></pre>\n\n<p>can be reduced to this:</p>\n\n<pre><code>for(int i = 0; i &lt; 4; i++)\n deck = drawFromDeck(deck, dealer);\n</code></pre></li>\n<li><p>This code:</p>\n\n<pre><code>System.out.print(\" = \" + (player.getHandTotal() == BLACKJACK ? \n player.getHandTotal() + \" : BLACKJACK!\" : \n ((player.getHandTotal() &gt; BLACKJACK) ? \n player.getHandTotal() + \" : BUSTED!\" : \n player.getHandTotal())) + \"\\n\");\n</code></pre>\n\n<p>is duplicated the lines below, you can create a method that accepts an <code>Hand</code> and does its calculations</p></li>\n<li>getRankName() in Card.java could be rewritten more cleanly with a switch</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T22:33:39.363", "Id": "31861", "Score": "1", "body": "#2, how would you rewrite this? I mean first we must draw player's card, then dealer's, then player's, then dealer's. The for loop does not do this..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T18:26:34.540", "Id": "31884", "Score": "2", "body": "#2 could be done like so (typed without a compiler): `for(hand : new Hand[]{player,dealer,player,dealer}) deck = drawFromDeck(deck,hand);` . Not sure if that is actually better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T19:25:57.350", "Id": "31888", "Score": "0", "body": "@HelpNeeder oh, I'm sorry, I misread that code :|" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T22:17:56.747", "Id": "31902", "Score": "1", "body": "@Brian, this is interesting. I never used an array within for loop like you did. Thanks. But I wouldn't do this, in this situation, like this because it's unnecessary to allocate more memory space for such array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T22:33:28.280", "Id": "31903", "Score": "1", "body": "@HelpNeeder: This is a pretty inexpensive allocation. Keep in mind that it is an array of `Hand` references, not an array of `Hand` values. As a general rule, you should ignore minor inefficiencies in favor of cleaner code. Though I am not sure if my proposal is actually cleaner; I am merely extending miniBill's answer to handle your situation." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T18:52:50.830", "Id": "19930", "ParentId": "19760", "Score": "3" } } ]
{ "AcceptedAnswerId": "19766", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T00:55:22.077", "Id": "19760", "Score": "8", "Tags": [ "java", "object-oriented", "game", "playing-cards" ], "Title": "How is my BlackJack game design?" }
19760
<p>I would like a review regarding the following code in which I index and search the City model. Currently both solr (with sunspot gem) and elaticsearch (with the tire gem) are show. I am migrating from solr to ES and want to make sure I am not making any major mistakes.</p> <p>I am new to ES. </p> <pre><code>class City &lt; ActiveRecord::Base include Tire::Model::Search include Tire::Model::Callbacks class &lt;&lt; self def search(params) tire.search(load: false, page: params[:page], per_page: (params[:per_page] || 50)) do query do boolean do should { string 'has_seo_doctors:true' } end term :state_id, params[:state_id] end sort { by :name_sortable, "asc" } end end def search_total Tire.search('cities', search_type: 'count') {}.results.total end end # elasticsearch mapping do indexes :name, type: 'multi_field', stored: 'yes', fields: { name: { type: 'string', analyzer: 'snowball' }, name_sortable: { type: 'string', index: :not_analyzed } } indexes :id, type: 'integer' indexes :seo_name, type: 'string', stored: 'yes' indexes :state_id, type: 'integer', stored: 'yes', as: 'state.try(:id)' indexes :has_seo_doctors, type: 'boolean', stored: 'yes', as: 'has_seo_doctors?' indexes :state_seo_name, type: 'string', stored: 'yes', as: 'state.try(:seo_name)' end # solr (sunspot) indexing searchable(auto_index: true, auto_remove: true, include: :state) do boolean :has_seo_doctors, stored: true do has_seo_doctors? end string :id string :name, stored: true string :seo_name, stored: true string :state_id, stored: true do state.try(:id) end string :state_seo_name, stored: true do state.try(:seo_name) end end handle_asynchronously :solr_index unless Rails.env.test? end </code></pre> <p>Performing a search is as easy as:</p> <pre><code>City.search({ state_id: State.first.id, page: 1 }) </code></pre> <p>We have an admin dashboard which relies on the total indexes number of cities, so I have created the following convenience method:</p> <pre><code>City.search_total </code></pre> <p>A few comments: </p> <ul> <li>I don't exactly understand when to use to_indexed_json</li> <li>If 'as:' is the proper way of handling custom indexed methods</li> </ul> <p>Thank you</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T03:29:27.147", "Id": "31598", "Score": "0", "body": "Is this Ruby? Please add a language tag, it will give your question better visibility to those who can answer it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T02:09:52.133", "Id": "19762", "Score": "3", "Tags": [ "ruby", "ruby-on-rails", "search" ], "Title": "Moving from Solr (Sunspot) to ElasticSearch (Tire), Review needed" }
19762
<p>I have a dropdown that contains around 100,000 rows which make up a list.</p> <pre><code>&lt;input id="search" type="text" /&gt; &lt;ul&gt; &lt;li&gt;item 1&lt;/li&gt; &lt;li&gt;item 2&lt;/li&gt; ... &lt;li&gt;item 100,000&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I have a text box which acts as a search, so as you type it matches the input to items in the list, removing what does not match. This is the class I wrote to perform the removing of list elements.</p> <p><a href="http://jsfiddle.net/bWtpy/10/" rel="nofollow">See the fiddle (list has about 2000 items)</a> </p> <pre><code>// requires jQuery var Search = (function(){ var cls = function (name) { var self = this; self.elem = $('#' + name); self.list = $('#' + name).next('ul').children(); self.elem.bind('keyup', function () { self.change(); }); }; cls.prototype = { change: function () { var self = this; // gets the closest ul list var typed = self.elem.val(); // only do something if there is something typed if (typed !== '') { // remove irrelevent items from the list self.list.each(function () { var item = $(this).html(); if (item.indexOf(typed) === -1) { $(this).addClass('zero'); // tried using a class with visibility hidden } else { $(this).removeClass('zero'); } }); } else { // check what list items are 'hidden' and unhide them self.list.each(function () { if ($(this).hasClass('zero')) { $(this).removeClass('zero'); } }); } } }; return cls; }()); </code></pre> <p>I am just adding a class which adds a <code>height: 0</code>, and no <code>margin</code>, <code>padding</code>, etc, but I have also tried using <code>visibility: hidden</code>. I have also tried using the detach method in jQuery but this is about the same in terms of speed. </p> <p>Are there any JavaScript experts who can see any problems with the code, or offer some optimization techniques?</p>
[]
[ { "body": "<p>A couple notes:</p>\n\n<ol>\n<li><p><code>display: none</code> does everything you're trying to do with your existing CSS class; it hides and completely removes the element from the layout. So instead of adding the <code>zero</code> class you would set <code>display</code> to <code>none</code>, and instead of removing it you would set <code>display</code> to <code>block</code>.</p></li>\n<li><p>As far as optimization goes, one thing you could do is iterate the list items and store all the strings in an array as part of the initialization for your function. Then when you're iterating <code>self.list</code>, fetch the string from your cached array with the current index instead of calling <code>$(this).html()</code>. That would most likely be faster because it eliminates a DOM lookup.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T03:23:24.030", "Id": "19764", "ParentId": "19763", "Score": "5" } }, { "body": "<p>I've generated a list of 100K items and compared 2 approaches to hiding every second item.</p>\n\n<p><strong>1. Setting display to block/none</strong></p>\n\n<pre><code>for (var i = 0, len=items.length; i &lt; len; i++) {\n items[i].style.display = i % 2 ? 'none' : 'block';\n}\n</code></pre>\n\n<p>Completed in 2 seconds in Chrome, never completed in Firefox.</p>\n\n<p><strong>2. Building HTML as one long string</strong></p>\n\n<pre><code>// texts = ['facikufugo', 'xacabimuzo', ... 100K];\nfor (var html = '', i = 0; i &lt; texts.length; i+=2) {\n html += '&lt;li&gt;' + texts[i] + '&lt;/li&gt;'; // may need escaping\n}\nul.innerHTML = html;\n</code></pre>\n\n<p>Completed in 2 seconds in Chrome, 6 seconds in Firefox.</p>\n\n<hr>\n\n<p>The exact duration is hard to measure because of async rendering, console.time doesn't give the exact number.</p>\n\n<p>There's absolutely no way to make this fast enough given 100 000 items. Even trying to select that many elements using jQuery results in 'Maximum call stack size exceeded' error in Chrome. Maybe you'll need to rethink your approach and have only a small number of <code>&lt;li&gt;</code> elements in the document at any given time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T18:26:41.623", "Id": "19784", "ParentId": "19763", "Score": "5" } }, { "body": "<p>Simply displaying or hiding an entire list of 100,000 elements can take a second or two - that is probably the main bottleneck. But probably in most cases you will want to display much less than the full list, right? In which case you could do something like this. <a href=\"http://jsfiddle.net/dw9sr/9/\" rel=\"nofollow\">(fiddle)</a></p>\n\n<pre><code>var texts = [], maxResults = 3000;\n// (then fill texts with the desired items)\n\ndocument.getElementById('search').onkeyup = function() {\n var results = [],\n typed = document.getElementById('search').value;\n if (typed) {\n for (var p, t = texts.slice(), i = maxResults; i &amp;&amp; (p = t.pop());) {\n if (p.indexOf(typed) &gt; -1) {\n results.push(p);\n i--;\n }\n }\n }\n else results = texts.slice(0, maxResults);\n document.getElementById('results').innerHTML = \n '&lt;ul&gt;&lt;li&gt;' + results.join('&lt;/li&gt;&lt;li&gt;') + '&lt;/li&gt;&lt;/ul&gt;';\n}\n</code></pre>\n\n<p>An alternative with similar effects would be only to update the list when at least 2 or 3 characters have been typed. But then you have to decide what to do when the user backspaces, which could once again result in a massive list having to be displayed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T00:49:56.750", "Id": "19795", "ParentId": "19763", "Score": "3" } }, { "body": "<p>I gave this a try using a WebWorker. The WebWorker helped out, I think, mostly by creating a time-window for additional text-input to be entered. Then, when a search result is recieved and it doesn't match the latest text-input, the search result is ignored. That prevents the DOM manipulation, which is what slows everything down. </p>\n\n<p>For testing, I'm working with ~75k items. It's kinda spotty on FF, but works pretty well in Chrome and Safari. Even works on the iPhone, although some queries, like 'i' which returns ~50k items, can take ~10 seconds to render (but cached can be down to ~550ms). (I have to admit, my method for measuring these times is in need of improvement.)</p>\n\n<p>A couple of things I did in trying to improve the performnce:</p>\n\n<ul>\n<li>Worked with <code>&lt;ul&gt;</code>s instead of <code>&lt;li&gt;</code>s, per <a href=\"https://codereview.stackexchange.com/a/19784/20138\">Alexey's answer</a></li>\n<li>Worked with an array of strings instead of the <code>&lt;li&gt;</code>s, per <a href=\"https://codereview.stackexchange.com/a/19764/20138\">seand's answer</a></li>\n<li>The <code>&lt;ul&gt;</code>s use absolute positioning</li>\n<li>The full list is never deleted, it's moved off screen</li>\n<li>The <code>&lt;ul&gt;</code>s for the last 7 searches are kept attached to the DOM and moved off-screen</li>\n<li>The removal of a <code>&lt;ul&gt;</code> (when it's not in the last 7) is done 1 second after it's no longer needed </li>\n</ul>\n\n<p>Here is an excerpt of the code:</p>\n\n<pre><code>// keep a record of the last 7 searches\nrecents.setMaxLen(7);\n\n$inTx.on('keyup.search-ftr chnage.search-ftr', function() {\n\n var tx = $inTx.val(),\n recent;\n\n // skip if same query\n if (tx === lastQuery) {\n return;\n }\n\n // full list is never removed from the DOM, just moved off screen\n // so, for the empty search move the full list back on screen\n if (tx === '') {\n ++curSearchId;\n // $curList is whatever search results are showing\n $curList.css('left', -9999);\n $ulWtihAll.css('left', 10);\n // $count shows is text of current # showing\n $count.text(fullCount);\n lastQuery = tx;\n $diffSearch.text('search: ');\n $diffRender.text('render: ');\n return;\n }\n\n // have a non-empty search, so move full list off screen if needed\n if (lastQuery === '') {\n $ulWtihAll.css('left', -9999);\n }\n\n lastQuery = tx;\n // the `&lt;ul&gt;` elements for last 7 searches are cached \n // `recents` is a map (assoc array) capped at length 7\n recent = recents.getAndRenew(tx);\n if (recent) {\n useRecent(recent);\n return;\n }\n // start a search - in web worker if have it\n $ind.css('visibility', 'visible');\n searchStartMs = +new Date(); \n searchFunc({searchStr: tx, createStr: true, id: ++curSearchId});\n});\n\nfunction searchCallback(e) {\n\n // ignore if not the results for most recent search\n if (e.data.id !== curSearchId) {\n return;\n }\n lastResultId = e.data.id;\n renderStartMs = +new Date();\n\n // update the counter\n $count.text(e.data.count);\n $diffSearch.text('search: ' + (+new Date() - searchStartMs));\n $ind.css('visibility', 'hidden');\n\n // DOM adding / removal is the slowest part (esp removal) so\n // move the current (now old) search result off screen instead\n // of removing it\n $curList.css('left', -9999);\n // create the new `&lt;ul&gt;` and add it to the DOM\n $curList = $('&lt;ul&gt;' + (e.data.result || '') + '&lt;/ul&gt;').css(onCSS);\n $holder.append($curList);\n\n // add the latest &lt;ul&gt; to the recents capped map\n // if something was kicked out of the map, the .add() \n // method will return it\n var removed = recents.add(e.data.searchStr, {\n $elm: $curList,\n count: e.data.count\n });\n // if am item was kicked out of the `recents` map, \n // schedule it for removal from DOM\n if (removed) {\n setTimeout(function() {\n removed.$elm.remove();\n }, 1000);\n }\n // update the height of the div that holds the &lt;ul&gt;s\n // (can't seem to get this to work right in FF)\n setTimeout(function() {\n $holder.css('height', 100 + $curList.height());\n $diffRender.text('render: ' + (+new Date() - renderStartMs));\n }, 0);\n}\n\n// the search matches one of the cached &lt;ul&gt;s\nfunction useRecent(recent) {\n\n // move the current list off screen, know it won't\n // be removed from the recent set bc not adding \n // anything new to the recent set\n $curList.css('left', -9999);\n $count.text(recent.count);\n $curList = recent.$elm;\n $curList.css('left', 10);\n $diffSearch.text('search: (cached)');\n\n renderStartMs = +new Date();\n setTimeout(function() {\n $holder.css('height', 100 + $curList.height());\n $diffRender.text('render: ' + (+new Date() - renderStartMs));\n }, 0);\n}\n\nfunction workerSearch(params) {\n worker.postMessage(params);\n}\n\nfunction localSearch(params) {\n var res = findMatches(params.searchStr, true);\n searchCallback({\n data: {\n id: curSearchId,\n result: res.resultStr,\n count: res.count\n }\n });\n}\n</code></pre>\n\n<p>A demo: <a href=\"http://jsfiddle.net/bWtpy/38/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/bWtpy/38/</a></p>\n\n<p>The full code is a bit demonic, but I wanted to give it a shot.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T19:21:15.487", "Id": "19902", "ParentId": "19763", "Score": "3" } }, { "body": "<p>You should try to optimize your algoritmic approach to searching, in addition to the JavaScript performance described in Alexey's comment. Your problem is (in most cases) not algoritmically equivalent to hiding every second list item, thus we can make use of an optimized data structure for the problem to take advantage of this. You are searching with \"indexOf\", which is relatively slow for such a large dataset. Build a suffix array to locate the substrings in your set (see <a href=\"https://codereview.stackexchange.com/questions/19200/efficient-looping-procedure-to-find-the-longest-common-substring-java/19213#19213\">this</a> or <a href=\"http://en.wikipedia.org/wiki/Suffix_array\" rel=\"nofollow noreferrer\">this</a>), then hide these elements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-04T01:54:46.913", "Id": "20140", "ParentId": "19763", "Score": "0" } } ]
{ "AcceptedAnswerId": "19784", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T02:16:17.203", "Id": "19763", "Score": "5", "Tags": [ "javascript", "jquery", "optimization" ], "Title": "Fastest way to remove/hide a lot of elements from a list" }
19763
<p>I am writing an object in C# to mimic jQuery's various functions. That is, calling the constructor is akin to calling the <code>$()</code> function of jQuery. For example,</p> <pre><code>var a = new JQuery("div").eq(0); Assert.AreEqual("$(\"div\").eq(0)", a.ToString()); </code></pre> <p>I also have an Append function which concatenates two or more existing JQuery objects into one, changing the $ of all but the first into a find. For example,</p> <pre><code>var a = new JQuery("body").find("ul").eq(0); var b = new JQuery("li").filter("div").eq(0); var c = new JQuery("span").filter("a"); var d = JQuery.Append(a, b, c); Assert.AreEqual("$(\"body\").find(\"ul\").eq(0).find(\"li\").filter(\"div\").eq(0).find(\"span\").filter(\"a\")", d.ToString()); </code></pre> <p>The code is below. There is a bit of recursion in the <code>ChangeLastPredecessor</code> and in the <code>ToString</code> methods. How do you suggest I clean up those two methods?</p> <pre><code>internal struct Parameter { private readonly object @object; internal Parameter(object parameter) { @object = parameter; } public override string ToString() { if (@object == null) { return string.Empty; } // convert string to quoted and escaped string var objString = @object as string; return objString == null ? Convert.ToString(@object, CultureInfo.InvariantCulture) : string.Concat("\"", objString.Replace("\"", "\\\""), "\""); } } public class JQuery { public JQuery(string selector) { Function = "$"; Parameters = new List&lt;Parameter&gt; { new Parameter(selector) }; Predecessor = null; } public JQuery(JQuery obj) { Function = "$"; Parameters = new List&lt;Parameter&gt; { new Parameter(obj) }; Predecessor = null; } private JQuery(JQuery predecessor, string function, params object[] parameters) { Function = function; Parameters = parameters.Select(x =&gt; new Parameter(x)); Predecessor = predecessor; } // the current function in the chain private string Function { get; set; } // the parameters to the current function private IEnumerable&lt;Parameter&gt; Parameters { get; set; } // the previous function in the chain private JQuery Predecessor { get; set; } public static JQuery Append(JQuery appendee, params JQuery[] appendices) { if (appendices == null) { throw new ArgumentNullException("appendices"); } if (appendices.Length == 0) { return appendee; } for (var i = 0; i &lt; appendices.Length - 1; ++i) { ChangeLastPredecessor(appendices[i], appendices[i + 1]); } ChangeLastPredecessor(appendee, appendices[appendices.Length - 1]); return appendices[appendices.Length - 1]; } private static void ChangeLastPredecessor(JQuery appendee, JQuery changee) { if (changee.Predecessor == null) { changee.Function = "find"; changee.Predecessor = appendee; return; } var predecessor = changee.Predecessor; ChangeLastPredecessor(appendee, predecessor); changee.Predecessor = predecessor; } public override string ToString() { return (Predecessor == null) ? string.Format(CultureInfo.InvariantCulture, "{0}({1})", Function, string.Join(",", Parameters.Select(x =&gt; x.ToString()))) : string.Format(CultureInfo.InvariantCulture, "{0}.{1}({2})", Predecessor, Function, string.Join(",", Parameters.Select(x =&gt; x.ToString()))); } public JQuery eq(int index) { return new JQuery(this, "eq", index); } public JQuery find(string selector) { return new JQuery(this, "find", selector); } public JQuery find(JQuery obj) { return new JQuery(this, "find", obj); } public JQuery filter(string selector) { return new JQuery(this, "filter", selector); } public JQuery filter(JQuery obj) { return new JQuery(this, "filter", obj); } } </code></pre>
[]
[ { "body": "<p>Here are few comment: </p>\n\n<ol>\n<li><p>it seems like ChangeLastPredecessor is an implementation of linked list. </p></li>\n<li><p>instead of returning a new object in every function , return by modifying the same object.</p></li>\n<li><p>you may use Builder pattern (this is under investigation).</p></li>\n<li><p>use of extension method can be exploited.</p></li>\n</ol>\n\n<p>let me know in case of any concern.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T09:17:26.923", "Id": "31606", "Score": "0", "body": "Why would you want to use extension methods here? I don't see any reason to use them in this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T09:40:41.580", "Id": "31607", "Score": "0", "body": "extension method should be used when you want to add methods to a class even it is not allowing you to change it, by the help of extension method this library can be more useful" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T09:47:32.147", "Id": "31608", "Score": "1", "body": "But the OP can freely change the class itself, because they wrote it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T05:52:16.120", "Id": "19767", "ParentId": "19765", "Score": "0" } }, { "body": "<p>Your code looks mostly good to me. My notes:</p>\n\n<ol>\n<li><p>The recursions you mentioned are entirely appropriate, I think. Especially the one in <code>ToString()</code>. The one in <code>ChangeLastPredecessor()</code> could be simplified using <code>while</code> to:</p>\n\n<pre><code>private static void ChangeLastPredecessor(JQuery appendee, JQuery changee)\n{\n JQuery current = changee;\n while (current.Predecessor != null)\n current = current.Predecessor;\n\n current.Predecessor = appendee;\n current.Function = \"find\";\n}\n</code></pre>\n\n<p>Probably the biggest problem with recursion is the possibility of stack overflow. But that doesn't seem to be a possibility here, since you're not going to have one query containing hundreds of subqueries.</p></li>\n<li><p>If you're going to keep recursive <code>ChangeLastPredecessor()</code>, then you can remove the last line (<code>changee.Predecessor = predecessor;</code>). That's because all it does is to set the property to a value it already has.</p></li>\n<li><p>I think that in cases like this, it's useful to use immutable objects. This way, you could reuse one <code>JQuery</code> object in multiple queries. Doing this would effectively turn your structure from a normal singly-linked list to functional immutable linked list.</p></li>\n<li><p>In <code>ToString()</code>, you shouldn't repeat the part that joins parameters. Instead, you should extract a variable out of that and use that in both branches.</p></li>\n<li><p>You should try to avoid using identifiers that are the same as keywords. I think that in your case, using <code>obj</code> instead of <code>@object</code> wouldn't reduce clarity,.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T09:36:43.433", "Id": "19772", "ParentId": "19765", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T04:05:25.120", "Id": "19765", "Score": "3", "Tags": [ "c#", "recursion" ], "Title": "JQuery typed wrapper in C#; possible recursion" }
19765
<p>I want to convert a <code>java.lang.String</code> to a <code>java.lang.Integer</code>, assigning a default value of <code>0</code> if the <code>String</code> is not convertible. Here is what I came up with. I would appreciate an assesment of this approach.</p> <p>To be honest, it feels a little squirrely to me:</p> <pre><code>String strCorrectCounter = element.getAttribute("correct"); Integer iCorrectCounter = new Integer(0); try { iCorrectCounter = new Integer(strCorrectCounter); } catch (Exception ignore) { } </code></pre>
[]
[ { "body": "<p>here is a solution :</p>\n\n<pre><code>int tryParseInt(String value) { \n try { \n return Integer.parseInt(value); \n } catch(NumberFormatException nfe) { \n // Log exception.\n return 0;\n } \n}\n</code></pre>\n\n<p>you should catch NumberFormatException instead of exception.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T14:09:58.510", "Id": "31617", "Score": "5", "body": "+1 for catching the correct exception and using `parseInt()` so a cached `Integer` can be returned instead of guaranteeing that a new instance is returned." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T11:19:53.213", "Id": "19776", "ParentId": "19773", "Score": "25" } }, { "body": "<p>You should not use <code>new Integer( string )</code> instead use <code>Integer.valueOf( string )</code>. As discussed before in many other threads, <code>valueOf</code> may be faster due to the fact it can lookup small integer values and reduces the overhead of creating a new object.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T18:46:28.540", "Id": "19785", "ParentId": "19773", "Score": "5" } }, { "body": "<p>As others have noted, your code should never catch Exception. Doing so causes all sorts of problems. In addition to the answers given I would also suggest that you don't default the value to 0 but make it more generic. For example</p>\n\n<pre><code>public static int parseInteger( String string, int defaultValue ) {\n try {\n return Integer.parseInt(string);\n }\n catch (NumberFormatException e ) {\n return defaultValue;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T19:50:12.590", "Id": "19853", "ParentId": "19773", "Score": "8" } }, { "body": "<p>Just to be a bit(?) pedantic:</p>\n\n<pre><code>public static final int iDEFAULT_DEFAULT_PARSED_INT = 0;\n\npublic static int ifIntFromString( String sToParse) {\n return ifIntFromString( sToParse, iDEFAULT_DEFAULT_PARSED_INT );\n}\n\npublic static int ifIntFromString( String sToParse, int iDefaultValue ) {\n int iReturnValue = null;\n try {\n iReturnValue = Integer.parseInt(sToParse);\n } catch ( NumberFormatException e ) {\n iReturnValue = iDefaultValue;\n }\n assert (null != iReturnValue) : \"Impossible - no return value has been set!\";\n return iReturnValue;\n}\n</code></pre>\n\n<p>It would be really great if there were a way to accomplish this without having to catch an exception (due to performance concerns) and without having to write the parsing code yourself - but this is what the base libraries give us.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T19:37:23.463", "Id": "31814", "Score": "3", "body": "Hungarian notation is really not necessary..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T00:41:46.517", "Id": "32120", "Score": "0", "body": "@assylias : Well, it is only necessary in order to maintain a high level of pedanticism... :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T22:16:16.130", "Id": "32469", "Score": "0", "body": "It does not compile (`Cannot convert from null to int`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T22:32:45.793", "Id": "32473", "Score": "1", "body": "@palacsint Ack! Thanks - bother. Too many languages - my apologies. In Java, null is a first-order token having identity only with itself (if I recall correctly) whereas in many other languages (such as C/C++) it equates to the integer zero. In this instance, my intent was to use null as the \"non-value\" to indicate a failure to set the variable while still having it be initialized. I ought to have used an Integer object rather than an int type, then converted the Integer to an int for the return value." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T00:17:12.157", "Id": "19861", "ParentId": "19773", "Score": "1" } }, { "body": "<p>I'd consider using <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/math/NumberUtils.html#toInt-java.lang.String-int-\" rel=\"noreferrer\"><code>NumberUtils.toInt</code></a> from <a href=\"http://commons.apache.org/lang/\" rel=\"noreferrer\">Apache Commons Lang</a> which does exactly this:</p>\n\n<pre><code>public static int NumberUtils.toInt(java.lang.String str, int defaultValue)\n</code></pre>\n\n<p><a href=\"http://grepcode.com/file/repo1.maven.org/maven2/commons-lang/commons-lang/2.6/org/apache/commons/lang/math/NumberUtils.java#171\" rel=\"noreferrer\">The implementation uses the already mentioned <code>Integer.parseInt</code></a> with an additional <code>null</code> check.</p>\n\n<p>See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-19T16:56:49.030", "Id": "334012", "Score": "3", "body": "excellent suggestion! I am very thankful for the Apache Commons libraries." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T20:31:36.977", "Id": "20555", "ParentId": "19773", "Score": "25" } }, { "body": "<h3>Parsing Methods in Java Convert String to Int</h3>\n<p>In Java there are two methods to convert String to Int, they are:</p>\n<pre><code>Integer.parseInt()\nInteger.valueOf()\n</code></pre>\n<ol>\n<li>Convert String to Int using <code>Integer.parseInt()</code>\nThe <code>Integer.parseInt()</code> is a static method of Integer class used in Java to converts string to primitive integer.</li>\n</ol>\n<p>Example:</p>\n<p>String ‘100’ to primitive integer 100</p>\n<p>Note:Parsing is a process of converting one data type to another. For example String to integer. Coding part please refer this: <a href=\"http://beyondcorner.com/java-convert-string-int/\" rel=\"nofollow noreferrer\">best way to convert string to int</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-06T07:21:19.340", "Id": "191381", "ParentId": "19773", "Score": "1" } }, { "body": "<p>The performance cost of creating and throwing an <code>Exception</code> in Java can, and normally always is significantly more taxing than pre-validating a value can be converted. For all JVM's I am aware of (IBM's Java, Oracle's Java, OpenJDK, etc.) the cost of the exception also often linearly scales relative to the depth of the call stack when the exception is thrown, so deeply-nested exceptions are more costly than exceptions in the main-method....</p>\n\n<p>The bottom line is that in good code you should never <sup>(with very few exceptions)</sup> make exceptions part of the normal/expected flow of the code.</p>\n\n<p>So, in your case, I would minimalize the possibility of exceptions by trying as hard as reasonable to eliminate exception cases, while still handling the exceptions appropriately.</p>\n\n<p>Note that the documentation for <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#valueOf-java.lang.String-\" rel=\"nofollow noreferrer\">Double.valueOf(String)</a> alludes to this and also provides a regular expression useful for checking whether valueOf may throw an exception.</p>\n\n<pre><code>private static final Pattern isInteger = Pattern.compile(\"[+-]?\\\\d+\");\n\npublic static final int tryParseInt(String value) {\n if (value == null || !isInteger.matcher(value).matches()) {\n return 0;\n }\n try { \n return Integer.parseInt(value); \n } catch(NumberFormatException nfe) { \n return 0;\n } \n}\n</code></pre>\n\n<p>While the additional checks may slow down valid numbers slightly, it drastically improves the performance of handling invalid numbers in the majority of the cases, and the trade-off is, in my experience more than worth it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-06T17:51:06.440", "Id": "191428", "ParentId": "19773", "Score": "1" } } ]
{ "AcceptedAnswerId": "19776", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T10:32:52.940", "Id": "19773", "Score": "24", "Tags": [ "java" ], "Title": "Convert String to Integer with default value" }
19773
<p>I have a child <code>iframe</code> in my page that will load content from a different web application in a different virtual directory than the parent page.</p> <p>The DOM will look roughly like this:</p> <pre><code>&lt;html&gt; &lt;!-- Content from www.contoso.com/WebApp1/Home --&gt; &lt;div id="parentDiv" /&gt; &lt;iframe&gt; &lt;!-- Content from www.contoso.com/WebApp2/Home --&gt; &lt;div id="childDiv" /&gt; &lt;/iframe&gt; &lt;/html&gt; </code></pre> <ol> <li>The user will log in to <code>www.contoso.com/WebApp1</code>.</li> <li>The user will load <code>www.contoso.com/WebApp1/Home</code> which contains an <code>iframe</code> with content from <code>www.contoso.com/WebApp2/Home</code>.</li> <li>To load content from <code>www.contoso.com/WebApp2/Home</code> the user must be logged in.</li> </ol> <p><strong>My Question</strong>:</p> <ul> <li>Could I simply load the <code>iframe</code> with <code>src=www.contoso.com/WebApp2/Home?sessionId={sessionIdFromTheParentCookie}</code>, and write server-side code to trust the incoming sessionId and set a cookie for the child <code>iframe</code>?</li> <li>At present, I can't see how this is any worse than the reality that a user could tamper with his/her client-side cookie an insert an arbitrary sessionId in it.</li> <li>The sessionId must always be validated at the server, so what's the harm in supplying an arbitrary sessionId in the query string and asking the server to set the cookie?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T01:36:45.100", "Id": "31645", "Score": "3", "body": "I thought that cookies were shareable across an entire domain, unless you explicitly set the path when creating the cookie. Any cookies set when the user logs in should be available to the parent page and the iframe. This question on SO seems to support my notion: http://stackoverflow.com/questions/6578334/same-domain-iframe-cookies. Did I miss something?" } ]
[ { "body": "<p><strong>My Answer (best guess)</strong></p>\n\n<ul>\n<li>Tag is correct, out of security concer i would still not pass the session id as parameter(only if there is no other way)</li>\n<li>It makes it harder to tamper with, if it is httplony see <a href=\"http://en.wikipedia.org/wiki/HTTP_cookie#HttpOnly_cookie\" rel=\"nofollow noreferrer\">wikipedia</a></li>\n<li>Links with sessionids could be bookmarked and after the end of the session they wont work, or they could beforwarded, and sesssions could be passed/shared, ... </li>\n</ul>\n\n<p>Btw.: i found this link <a href=\"https://security.stackexchange.com/questions/14093/why-is-passing-the-session-id-as-url-parameter-insecure\">https://security.stackexchange.com/questions/14093/why-is-passing-the-session-id-as-url-parameter-insecure</a> covering more or less the same topic.</p>\n\n<p>I hope it helps</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T14:38:28.197", "Id": "23487", "ParentId": "19781", "Score": "2" } } ]
{ "AcceptedAnswerId": "23487", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T13:54:40.623", "Id": "19781", "Score": "5", "Tags": [ "javascript", "html", "security" ], "Title": "Need to pass cookie information to a child iFrame - Are there any security concerns?" }
19781
<p>I've written a couple of functions to check if a consumer of the API should be authenticated to use it or not.</p> <p>Have I done anything blatantly wrong here?</p> <p><strong>Config</strong></p> <pre><code>API_CONSUMERS = [{'name': 'localhost', 'host': '12.0.0.1:5000', 'api_key': 'Ahth2ea5Ohngoop5'}, {'name': 'localhost2', 'host': '127.0.0.1:5001', 'api_key': 'Ahth2ea5Ohngoop6'}] </code></pre> <p><strong>Exceptions</strong></p> <pre><code>class BaseException(Exception): def __init__(self, logger, *args, **kwargs): super(BaseException, self).__init__(*args, **kwargs) logger.info(self.message) class UnknownHostException(BaseException): pass class MissingHashException(BaseException): pass class HashMismatchException(BaseException): pass </code></pre> <p><strong>Authentication methods</strong></p> <pre><code>import hashlib from flask import request from services.exceptions import (UnknownHostException, MissingHashException, HashMismatchException) def is_authenticated(app): """ Checks that the consumers host is valid, the request has a hash and the hash is the same when we excrypt the data with that hosts api key Arguments: app -- instance of the application """ consumers = app.config.get('API_CONSUMERS') host = request.host try: api_key = next(d['api_key'] for d in consumers if d['host'] == host) except StopIteration: raise UnknownHostException( app.logger, 'Authentication failed: Unknown Host (' + host + ')') if not request.headers.get('hash'): raise MissingHashException( app.logger, 'Authentication failed: Missing Hash (' + host + ')') hash = calculate_hash(request.method, api_key) if hash != request.headers.get('hash'): raise HashMismatchException( app.logger, 'Authentication failed: Hash Mismatch (' + host + ')') return True def calculate_hash(method, api_key): """ Calculates the hash using either the url or the request content, plus the hosts api key Arguments: method -- request method api_key -- api key for this host """ if request.method == 'GET': data_to_hash = request.base_url + '?' + request.query_string elif request.method == 'POST': data_to_hash = request.data data_to_hash += api_key return hashlib.sha1(data_to_hash).hexdigest() </code></pre>
[]
[ { "body": "<p>Exception itself actually inherits from a class called BaseException so: </p>\n\n<pre><code>class BaseException(Exception):\n</code></pre>\n\n<p>Seems backwards.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T22:50:08.113", "Id": "19858", "ParentId": "19786", "Score": "6" } }, { "body": "<p>Building on @Drewverlee's answer, I would consider renaming <code>BaseException</code> to <code>APIException</code>, or something of the like.</p>\n\n<p>Also, I don't think passing app as an argument is best practice, I would recommend using the function as a decorator on your endpoints instead:</p>\n\n<pre><code># Your imports\nfrom application import app # Or whatever your non-relative reference is\n\ndef is_authenticated(func):\n def func_wrapper():\n # Your code here without the original def call\n return func_wrapper\n</code></pre>\n\n<p>You can then use this on each endpoint, adding the <code>@is_authenticated</code> decorator, to ensure the app is properly authenticated.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-26T23:41:59.233", "Id": "136029", "ParentId": "19786", "Score": "4" } } ]
{ "AcceptedAnswerId": "136029", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T19:10:36.143", "Id": "19786", "Score": "4", "Tags": [ "python", "authentication", "web-services", "flask" ], "Title": "Authentication for a Flask API" }
19786
<p>I have a string that must be splitted into an <strong>array</strong> of strings so using strtok makes perfect sense but before that I want to allocate the array of strings and thus I count how many words in it.</p> <pre><code>static inline int countWords(char *str) { int count = 0; char *buf = str; if(isgraph(*buf) &gt; 0)//checking for the first word count++; while(*buf != '\0') { if(isblank(*buf) &gt; 0){//reached a blank while(*buf == ' ' || *buf == '\t')//keep ignoring them buf++; if(*buf == '\0')//return if string is over return count; count++;//no more blank and string didn't end=new word } buf++; } return count; } </code></pre> <p>Am I doing this right? I've tested all weird cases that can come to my mind and it seems to work; but is there a faster way to do this? I am mainly concerned about the performance of the above code.</p>
[]
[ { "body": "<p>Here are some impressions:</p>\n\n<pre><code> if(isgraph(*buf) &gt; 0)\n</code></pre>\n\n<p>Why <code>&gt; 0</code>? Why not just <code>if (isgraph(*buf))</code>?</p>\n\n<pre><code> while(*buf != '\\0')\n</code></pre>\n\n<p>You don't have to write <code>'\\0'</code>. You can just write <code>0</code>. Or you can just write <code>while (*buf)</code>. This is a style thing though, different people make different choices.</p>\n\n<pre><code> if(isblank(*buf) &gt; 0){//reached a blank\n while(*buf == ' ' || *buf == '\\t')//keep ignoring them\n buf++;\n</code></pre>\n\n<p>It's weird that you do <code>isblank(*buf)</code> in the <code>if</code> statement, but <code>*buf == ' ' || *buf == '\\t'</code> in the loop. I would do <code>isblank</code> in both places. (Seems also like you could fold the <code>if</code> into the <code>while</code> entirely...)</p>\n\n<pre><code> if(*buf == '\\0')//return if string is over\n return count;\n</code></pre>\n\n<p>Why do you need this? Your loop termination condition is already <code>while (*buf)</code>, so the check almost seems redundant... Now, it does seem like the upcoming <code>count++</code> and <code>buf++</code> will create problems omitting this, but I would rather re-arrange those than make this loop look overly complicated. Just my opinion. YMMV.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T07:41:07.110", "Id": "31648", "Score": "3", "body": "\"You don't have to write '\\0'\" Why not? It makes it clear to the reader that the code is checking for a string null termination and not something else. This is how you make the code self-documenting. To replace '\\0' with 0 is just plain bad advice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T16:23:46.153", "Id": "31667", "Score": "1", "body": "@Lundin - I personally think that `'\\0'` is weird and verbose. 3 chars you don't need to type. And if you're working in Win32 you'll end up with `L'\\0'` which is just madness. But I'm one of those people who would rather write `while (*buf)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T16:46:17.783", "Id": "31669", "Score": "2", "body": "'\\0' is not \"style\", it is a necessity, so that the reader won't confuse it with integer 0, or NULL, or a boolean. '\\0' means that you are dealing with a string null termination and nothing else. Furthermore, my own arrogant opinion is that programmers who obfuscate their programs because they are too lazy to type a few more letters, should find another career." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T20:10:53.527", "Id": "31682", "Score": "1", "body": "@Lundin - If it is necessity why does the compiler accept it the other way? :-) I don't consider it obfuscation, if it appears in `while` or `if` it's clearly a boolean - and if there is ambiguity (there hardly ever is due to context, consistent naming patterns, and if need be, comments) then the reader can just glance over at the type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T07:17:10.603", "Id": "31699", "Score": "1", "body": "Because character literals are int in C, not char as in C++. C allows countless of really bad things. To assume that the C standard is rational is a grave mistake: when the C language was created, nobody knew what was good programming style. What I meant with boolean is the intended type. `if(x==0)` is a boolean expression, so is `if(my_bool)`. But not `if(my_int)`, that is bad style. For example, the MISRA-C committee even considered such code to be a safety hazard, since the MISRA-C standard requires all control expressions to be \"effectively boolean\"." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T00:43:37.417", "Id": "19794", "ParentId": "19787", "Score": "5" } }, { "body": "<p>Code comments:</p>\n\n<ul>\n<li>The parameter to the function should be const - \"const correctness\".</li>\n<li>Don't use the variable name \"buf\" for a variable that is not a memory buffer of some sort.</li>\n<li>You have 3 different ways of checking for spaces in your code, you need to check for them in a consistent manner. Either use !isgraph which is the same as checking for ' '. Or isblank, which is the same as checking for ' ' and '\\t'. Or possibly isspace, which checks for any form of white space character. I'll use isblank in my suggestion, since I don't know the nature of the string input.</li>\n<li>Your code is a bit hard to follow, with several nested loops and if statements.</li>\n</ul>\n\n<p>When I spontaneously rewrite your code to improve readability, I end up with this:</p>\n\n<pre><code>#include &lt;ctype.h&gt;\n\nstatic int countWords (const char* str)\n{\n int count = 0;\n\n while (*str != '\\0')\n {\n while (*str != '\\0' &amp;&amp; isblank(*str)) // remove all spaces between words\n {\n str++;\n }\n if(*str != '\\0')\n {\n count++;\n }\n\n while (*str != '\\0' &amp;&amp; !isblank(*str)) // loop past the found word\n {\n str++;\n }\n }\n\n return count;\n}\n</code></pre>\n\n<p>This code is very easy to understand. However, you asked for optimization and my code doesn't look all that effective; it is possibly slower than the original. Particularly, we have multiple checks for '\\0' all over the place. </p>\n\n<p>Note that any truly meaningful optimization requires that 1) we have actually encountered and measured a real performance problem, 2) we have noticed that the compiler is doing a poor job at optimizing that particular problematic code, and 3) we have fairly good knowledge of the target CPU and hardware. It a bad idea to manually optimize code if those 3 above conditions are not met.</p>\n\n<p>Still, I'll attempt a manual optimization of this, since it was requested. It may or may not be more effective. Branch prediction may be a more serious concern than the number of comparisons executed, for example. For what it is worth, here you go:</p>\n\n<pre><code>#include &lt;ctype.h&gt;\n#include &lt;stdbool.h&gt;\n\nstatic inline int countWords (const char* str)\n{\n int count = 0;\n bool look_for_data = true;\n\n while (*str != '\\0')\n {\n if( (look_for_data ^ isblank(*str)) != 0) // is it a character of interest?\n {\n count += (int)look_for_data; // increase count if we are looking for data\n look_for_data = !look_for_data;\n }\n str++;\n }\n\n return count;\n}\n</code></pre>\n\n<p>With this optimization we have managed to reduce the number of instructions and the number of branches both. But as you can tell, the code now turned quite obscure. </p>\n\n<p>Explanation:\nThe fundament of this code is that one lap in the loop corresponds to one character in the input string. The bool variable keeps track of whether the code is currently looking for spaces or non-spaces. </p>\n\n<p>We are only interested in the places in the string where we go from looking for spaces to looking for data, or vice versa. When that happens, we should start looking for data if we were looking for spaces, and the other way around. Also, in the case where we go from spaces to data, we should increase the word counter.</p>\n\n<p>The boolean logic truth table is:</p>\n\n<pre><code>look_for_data isblank of interest comment\nfalse false false we are at symbols and found another symbol\nfalse true true we are at symbols and found a space\ntrue true false we are at spaces and found another space\ntrue false true we are at spaces and found a symbol\n</code></pre>\n\n<p>We can see that this happens to be the truth table for logical XOR.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T12:25:20.453", "Id": "19810", "ParentId": "19787", "Score": "8" } }, { "body": "<p>Adel, why are you so concerned about the performance of your code?\n Readability is more important, unless there is a <strong>strong</strong> need to optimise\n (for example, if you have to count the number of words in strings all the time\n in you application).</p>\n\n<p>You code fails in readability for me but others have indicated where the\n problems lie. </p>\n\n<p>For what it is worth, here is my version of word counting. It is probably not efficient but I think it is clear once you know what <code>strspn</code> and <code>strcspn</code> do (count the length of sequences containing/not-containing the defined char-set)</p>\n\n<pre><code>static int\ncount_words(const char *s)\n{\n const char *cset = \" \\t\\n\\r\\v\\f\";\n size_t len;\n int word = 0;\n\n s += strspn(s, cset);\n\n while ((len = strcspn(s, cset)) &gt; 0) {\n ++word;\n s += len;\n s += strspn(s, cset);\n }\n return word;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T12:54:46.813", "Id": "19812", "ParentId": "19787", "Score": "5" } }, { "body": "<p>Taking a different approach, I'll question why you need to count the number of words at all. The performance and readability of code you don't have to write is not an issue! Unless you are very short of memory, why not not just allocate enough elements in your array to handle the most words that <code>strtok</code> could possibly find?</p>\n\n<p>Since <code>strtok</code> will skip over repeated separator characters, the most words that it can find is <code>(strlen(str)+1)/2</code> which happens in the worst case where there are alternating space and non-space characters. The +1 is to handle the worst case of an odd length string which starts and ends in a non-space character (for example <code>x x</code> has length 3 and 2 words). You will need an extra element if you are using a null pointer to delimiter the array itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T19:09:45.483", "Id": "19932", "ParentId": "19787", "Score": "3" } } ]
{ "AcceptedAnswerId": "19810", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T21:28:03.843", "Id": "19787", "Score": "11", "Tags": [ "optimization", "c", "strings" ], "Title": "Count words in a C string" }
19787
<p>I've planning to create crosswords game for Android platform. Basically, crossword is a matrix of <code>TextFields</code> (<code>EditTexts</code>) and <code>TextViews</code>. Each crossword might be in american style (first <code>TextView</code> in every question stores question number, and there's no TextView with clue) or swedish (first <code>TextView</code> stores arrow indicating question's 'direction', and there is <code>TextView</code> with clue visible). Every entry (Question + correct answer) might use the same <code>TextField</code> if entries share position for typing letter. Clicking on <code>TextField</code> leads to showing question and higlighting all other <code>TextFields</code> inside entry. User has to change horizontal/vertical entries easily. </p> <p>This is swedish style: <a href="http://finecrosser.com/img/crossword2.jpg" rel="nofollow">http://finecrosser.com/img/crossword2.jpg</a> and this is american style: <a href="http://upload.wikimedia.org/wikipedia/commons/8/86/American_crossword.png" rel="nofollow">http://upload.wikimedia.org/wikipedia/commons/8/86/American_crossword.png</a></p> <p>Basic plan for classes:</p> <p><strong>Views</strong></p> <pre><code>public class CrosswordEntryView { private List&lt;TextField&gt; textFields = new ArrayList&lt;TextField&gt;(); private ClueView clueView; public CrosswordEntryView(ClueView clueView) { super(); this.clueView = clueView; } public void addTextField(TextField textField) { this.textFields.add(textField); } public void highlight() { for (TextField textfield : textFields) { textfield.setBackgroundColor(Color.RED); } } } public class ClueView extends TextView { // some additional functionality? } public class TextField extends EditText { // highlight, blink, etc. } </code></pre> <p><strong>Model:</strong></p> <pre><code>public class CrosswordEntryModel { private String clue; private String answer; private Orientation orientantion; private int row, column; } public enum Orientation { HORIZONTAL, VERTICAL; } public class CrosswordMatrixModel { private int width, height; private CrosswordEntryModel matrix[][]; public CrosswordMatrixModel(int width, int height) { super(); this.matrix = new CrosswordEntryModel[width][height]; this.width = width; this.height = height; } public void addEntryModel(CrosswordEntryModel entryModel, int column, int row) throws MatrixOutOfBoundsException { if (isWrongPosition(column, row)) throw new MatrixOutOfBoundsException(column, row); this.matrix[column][row] = entryModel; } private boolean isWrongPosition(int column, int row) { if (column &lt; 0 || column &gt;= width) return true; if (row &lt; 0 || row &gt;= height) return true; return false; } } </code></pre> <p><strong>Controller</strong></p> <pre><code>public class CrosswordEntryController { CrosswordEntryModel entryModel; CrosswordEntryView entryView; // capturing view's input events, highlighting textfields, // showing question after focusing, checking if entry is solved, etc. // should I store entry position's in crossword matrix? // how can I find controller which shares TextField with this object? } </code></pre> <p><strong>Building crossword:</strong></p> <pre><code>public class CrosswordFactory { public static CrosswordView build(CrosswordMatrixModel matrix) { View root; // loop through CrosswordEntryModels, look for mutual position for TextFields // create proper CrosswordEntryView's, add them to root // if crossword style is swedish - add arrows to TextFields and show TextView // if crossword style is american - add numbers to TextFields and hide TextView // create CrosswordEntryControllers ? return root; } } </code></pre> <p>What do you think about this structure? What if I will find out that I can't use a grid with <code>TextViews</code> and <code>TextFields</code> since bad performance and I will have to switch to <code>ListView</code> and row-based rendering (then using <code>CrosswordEntryControllers</code> to find what and in which row should be displayed might be really painful). How can I try to be prepared for such situation without rebuilding whole app? How should I handle switching from horizontal to vertical entry when users taps on something? Should <code>TextFields</code> be awared of its both parents (vertical or/and horizontal entry)? What are other drawbacks of proposed solution and what can I do better here? I think that I should use <code>AbstractFactory</code> pattern to create swedish/american crosswords based on user's preference, and then use it without changing any code in game's logic. Which design pattern would you use here?</p> <p>I would really appreciate any tips. Thanks!</p>
[]
[ { "body": "<pre><code> // loop through CrosswordEntryModels, look for mutual position for TextFields\n</code></pre>\n\n<p>You need to have a model of a actual crossword letter grid. (which can initially some object wrapping a char[][])</p>\n\n<p>You need to <em>look for mutual position</em> because you do not have the above grid.\nYou will also need to <em>look for mutual position</em> as user enters answers.\nbecause modifying a user's answer for an across question modifies/constrains several of user's down answers, and vice versa.</p>\n\n<p>In the current design, the answers, partial answers or guesses of the user seems to reside in the value of the text fields. The program state should have been encapsulated in the model, that's one of the reasons why changing the user interface implementation details would have such a big impact on the overall software.</p>\n\n<p>Users expect to \"write letters to squares\" not \"enter text\". Because they may assume the last letter of a question is \"s\" if the clue states that the answer is plural. or first letter is something else if all the probable answers start with the same letter. they would one to have a usable way of achieving their intention of entering partial answers.</p>\n\n<pre><code>// create proper CrosswordEntryView's, add them to root\n</code></pre>\n\n<p><em>proper CrosswordEntryView</em> you mean align textfields? maybe you should have a grid in your view layer that is a reflection of your grid in the model layer.</p>\n\n<pre><code> // if crossword style is swedish - add arrows to TextFields and show TextView\n // if crossword style is american - add numbers to TextFields and hide TextView\n</code></pre>\n\n<p>these codes should be somewhere else, preferably in their respective swedish/american packages. something like in the <code>onDraw()</code> method of a <code>SwedishCrosswordView</code> class or <code>SwedishCroswordDisplayStrategy</code> or some such .</p>\n\n<p>These are object construction methods, not object interaction methods:</p>\n\n<pre><code>addTextField(TextField textField)\naddEntryModel(CrosswordEntryModel entryModel, int column, int row)\n</code></pre>\n\n<p>they should not be public methods. In your examples you can just pass in lists of things you want to add one-by-one to the constructor. Also note that your crossword is not in a valid state until all the questions are added. And no more questions can be added one the construction is complete.</p>\n\n<pre><code>public CrosswordMatrixModel(int width, int height, List&lt;CrosswordEntryModel&gt; entryModels) {\n super();\n this.acrossMatrix = new CrosswordEntryModel[width][height];\n this.downMatrix = new CrosswordEntryModel[width][height];\n this.width = width;\n this.height = height;\n\n //matrix = acrossmatrix or downmatrix depending on entrymodel direction\n for(CrosswordEntryModel entryModel) {\n // start at the (row, column) of entry model\n // move in the direction of entry model\n // set matrix[currentrow][currentposition] to entrymodel.\n }\n\n}\n</code></pre>\n\n<p>after construction each question letter square in the <code>matrix</code> points to the question it is contained in. using a single matrix you cannot represent 1-across (0,0,horizontal) and 1-down(0,0,vertical) at the same time. what will the matrix[0][0] would point to?</p>\n\n<blockquote>\n <p>How should I handle switching from horizontal to vertical entry when users taps on something? </p>\n</blockquote>\n\n<p>If you plan to user that way of interaction then somewhere in your model classes you should have a current direction property, no.</p>\n\n<p>there is a crossword on yahoo games you can draw UI inspiration from there;)</p>\n\n<p>your current state may include current entry position and current direction. (as well as letters entered so far)</p>\n\n<p>your view representing the current state may consist of a grid of buttons, (table layout or whatever android specific bullshit), for example. \nbutton labels show letters entered so far. button at the current position has a border of some color. other buttons that corresponds to the current question have border of some other color. clicking a button at a position other than the current position set the current position to the position of the clicked button.\nclicking or dblclicking the button at the current position changes the current direction. when current direction, or current position changes displayed clue is updated.</p>\n\n<p>other things you have not mentioned are End-Game logic. Checking whether user have completed the game. etc.</p>\n\n<p>Another important design constraint is where will the crosswords come from.\nIf the puzzle will be designed by humans they will decide what type of puzzle the are preparing <strong>at the beginning</strong>, since there is not a one to one relationship with swedish and american puzzles. (swedish style crosswords always have top-left square full, whereas american style ones <strong>usually</strong> don't. Moreover, american crosswords are expected to be symmetrical, although they are not required to be so technically, whereas swedish style ones are usually not.) Abstract factory may not be a sensible thing in that case. Instead you would want something like \"get me a random puzzle of some certain type\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T12:18:30.687", "Id": "31991", "Score": "0", "body": "Thanks, that's amazing.I thought about using AbstractFactory to create TextView's based on crossword's style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T22:05:54.427", "Id": "34573", "Score": "0", "body": "One question - how would you connect Views and Models - let's say I am clicking on TextField and write a letter. How do you know which model is it pointing at? Would you create Controller class with reference to Question Box and all TextFields for every entry? Let's say I want to highlight current entry - when would you put this logic? Should I have create another grid of controllers...? Or would you put information about column/row in every view, and then after clicking on it you would search for proper views in view grid and highlight them in more general GameController?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T22:27:51.533", "Id": "34575", "Score": "0", "body": "One more thing. Could you take a look at this UML diagram: http://www.imagebanana.com/view/unf6bjwy/uml.png It's presenting my idea of using Abstract factory in order to make GridViews with TextFields and TextViews based on provided matrix model. What do you think about it? Basically, CrosswordGridViewFactory it's looping through models and creating TextFields/TextViews with selected style. On the end, it's passing it to new CrosswordGridView object. But still I'm not sure if every entry should have seperate controller for borders/highlighting/etc. Thank you for any tips (:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T08:13:52.047", "Id": "34651", "Score": "0", "body": "and last thing - as I understand, in your solution, you ask CrosswordMatrixModel for a specific model on position x,y and orientation horizontal/vertical, right? Or would you set 'orientation' field inside MatrixModel, and then just ask for position x,y?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T10:19:52.083", "Id": "19991", "ParentId": "19789", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T22:00:51.697", "Id": "19789", "Score": "1", "Tags": [ "java", "android" ], "Title": "Crossword game - designing class structure" }
19789
<p>I just learned about <code>Maybe</code> in Haskell, so I decided to try to use it with a binary search.</p> <p>Here's the function:</p> <pre><code>binarySearch :: (Ord a, Int b) =&gt; [a] -&gt; a -&gt; b -&gt; b -&gt; Maybe b binarySearch l e beg last | lookat &lt; e = (binarySearch l e i last) | lookat &gt; e = (binarySearch l e beg i) | lookat == e = Just i | otherwise = Nothing where i = floor ((beg+last)/2) lookat = l !! i </code></pre> <p><code>l</code> is a list, <code>e</code> is the element of interest, <code>beg</code> is the start of the section of interest and <code>end</code> is the end of said section. The error I am getting is:</p> <pre><code>BinarySearch.hs:1:25: `Int' is applied to too many type arguments In the type signature for `binarySearch': binarySearch :: (Ord a, Int b) =&gt; [a] -&gt; a -&gt; b -&gt; b -&gt; Maybe b </code></pre> <p>I have tried a few other things including:</p> <pre><code>binarySearch :: Ord a =&gt; [a] -&gt; a -&gt; Int -&gt; Int -&gt; Maybe b </code></pre> <p>Yielding the error:</p> <pre><code>BinarySearch.hs:6:23: Could not deduce (b ~ Int) from the context (Ord a) bound by the type signature for binarySearch :: Ord a =&gt; [a] -&gt; a -&gt; Int -&gt; Int -&gt; Maybe b at BinarySearch.hs:(3,1)-(9,22) `b' is a rigid type variable bound by the type signature for binarySearch :: Ord a =&gt; [a] -&gt; a -&gt; Int -&gt; Int -&gt; Maybe b at BinarySearch.hs:3:1 In the first argument of `Just', namely `i' In the expression: Just i In an equation for `binarySearch': binarySearch l e beg last | lookat &lt; e = (binarySearch l e i last) | lookat &gt; e = (binarySearch l e beg i) | lookat == e = Just i | otherwise = Nothing where i = floor ((beg + last) / 2) lookat = l !! i </code></pre> <p>I am not sure what I am doing wrong. Any corrections or comments on style or solution would be highly appreciated.</p>
[]
[ { "body": "<p>You don't want <code>Int b</code>, you just want <code>Int</code>:</p>\n\n<pre><code>Ord a =&gt; [a] -&gt; a -&gt; Int -&gt; Int -&gt; Maybe Int\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T23:22:22.323", "Id": "31643", "Score": "0", "body": "Thank you! To make it fully work I also had to get rid of `float` and use `quot` instead of `/` when calculating `i`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T22:56:53.453", "Id": "19792", "ParentId": "19790", "Score": "2" } } ]
{ "AcceptedAnswerId": "19792", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T22:28:57.203", "Id": "19790", "Score": "1", "Tags": [ "haskell", "beginner", "binary-search" ], "Title": "Errors with binary search in Haskell" }
19790
<p>I have been coding for some time (3 years I think), and have recently been wondering if my coding pattern is any good. Any kind of feedback is welcome:</p> <p>EDIT: The thing that concerns me most is that I have read a lot around that getters/setters are bad for OOP. Is this true?</p> <pre><code>//Point3D.as public class Point3D { private var _x:int; private var _y:int; private var _z:int; public function Point3D(tx:int = 0, ty:int = 0, tz:int = 0) { _x = tx; _y = ty; _z = tz; } public function get x():int { return _x; } public function set x(tv:int):void { _x = tv; } public function get y():int { return _y; } public function set y(tv:int):void { _y = tv; } public function get z():int { return _z; } public function set z(tv:int):void { _z = tv; } } //Geometry3D.as public class Geometry3D { private var _indices:Vector.&lt;uint&gt;; private var _vertices:Vector.&lt;Number&gt;; public function Geometry3D(tindices:Vector.&lt;uint&gt;, tvertices:Vector.&lt;Number&gt;) { _indices = tindices; _vertices = tvertices; } public function get indices():Vector.&lt;uint&gt; { return _indices; } public function get vertices():Vector.&lt;Number&gt; { return _vertices; } } //Primitive3D.as public class Primitive3D { private var _position:Point3D; private var _geometry:Geometry3D; public function Primitive3D(tx:int, ty:int, tz:int, tgeometry:Geometry3D) { _position = new Point3D(tx, ty, tz); _geometry = tgeometry; } public function get position():Point3D { return _position; } public function get geometry():Geometry3D { return _geometry; } public function render():void { //add render code here } } //TrianglePrimitive.as public class TrianglePrimitive extends Primitive3D { public function TrianglePrimitive(tx:int, ty:int, tz:int) { var indices:Vector.&lt;uint&gt; = Vector.&lt;uint&gt;([ 0, 1, 2]); var vertices:Vector.&lt;Number&gt; = Vector.&lt;Number&gt;([ ]); var geo:Geometry3D = new Geometry3D(indices, vertices); super(tx, ty, tz, geo); } public function spin(tradians:Number):void { //add spin code here } } //Main.as ... var tri:TrianglePrimitive = new TrianglePrimitive(0, 0, 0); tri.position.z = -4; tri.spin(Math.PI / 2); //90 degrees tri.render(); ... </code></pre> <p>Again, thanks a bunch for any feedback!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T00:19:18.363", "Id": "31644", "Score": "0", "body": "You should mention what kind of things concern you about what you wrote." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T16:06:59.707", "Id": "37887", "Score": "0", "body": "I wouldn't consider using getters and setters a good practice in Actionscript, as function calls are pretty expensive there. Especially when you just create them for future changes (one of benefits of getter/setter is that you can easily replace a property with it without changing the rest of code). Also, as a side note, consider creating methods getValue() instead of getters to indicate there's some extra work and it's better to cache the value than call the getter several times in one place." } ]
[ { "body": "<p>Looks good to me. Only thing I would say is:</p>\n\n<ul>\n<li>The accessor methods (<code>get</code> / <code>set</code>) in <code>Point3D</code> are unnecessary as they don't do any processing or restrict any access. The class would be better suited to have simple, public <code>x</code>, <code>y</code>, <code>z</code> properties.</li>\n<li>I don't see the purpose of the <code>Geometry3D</code> class. Maybe it's because I don't know much about your intentions or programming for 3d, but looks like things would be more straight-forward if <code>indices</code> and <code>vertices</code> properties were directly on <code>Primitive3D</code>. If it make sense to separate them off because they're processed as a pair by other parts of your program, you might also consider creating a <code>IGeometry3D</code> interface, which the <code>Primitive3D</code> class can implement. This would prevent there from being any ambiguity around ownership. (Not sure if I'm describing my thoughts, clearly.) </li>\n</ul>\n\n<p>I don't think getters and setters are bad for OOP programming. I think they're fantastic. They allow for validation of property values, pre- and post-processing when changing properties, lazy execution of calculations that aren't always necessary, and a lot of other things. Admittedly, you could do all of that with functions. But, to my thinking, an important part of programming is managing complexity and thoughtful use of accessor methods can simplify APIs, which in turn makes life easier (fewer bugs and easier to maintain). </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T21:04:05.650", "Id": "19905", "ParentId": "19793", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T00:18:25.940", "Id": "19793", "Score": "0", "Tags": [ "object-oriented", "design-patterns", "actionscript-3" ], "Title": "Actionscript 3.0, good OOP?" }
19793
<p>I have three methods that are really similar but do slightly different things. This doesn't feel very DRY to me, but I can't think of a way to reduce the duplication. Here are the methods, I think they're fairly self explanatory:</p> <pre><code># Present a date as a string, optionally without a year # Example output: "December 1, 2011" def date_string(year=true) if date str = "%B %e" str += ", %Y" if year date.strftime(str).gsub(' ',' ') else "" end end # Present a time as a string, optionally with a meridian (am/pm) # Example output: "1:30 PM" def start_time_string(meridian=true) if start_time str = "%l:%M" str += " %p" if meridian start_time.strftime(str).lstrip else "" end end # Present a time as a string, optionally with a meridian (am/pm) # Example Output: "2:00" def end_time_string(meridian=true) if end_time str = "%l:%M" str += " %p" if meridian end_time.strftime(str).lstrip else "" end end </code></pre> <p>Each method just presents a time as a string with certain options, and if the time object they're trying to present is nil, they return an empty string.</p> <p>Any ideas how to DRY this up?</p>
[]
[ { "body": "<p>Well, I don't see much you can do with the first method (being as it has a different responsibility than the other two). You can just combine the latter two methods into one and make the time object a parameter, like such:</p>\n\n<pre><code>def time_string(time_obj, meridian=true)\n if time_obj\n str = \"%l:%M\"\n str += \" %p\" if meridian\n time_obj.strftime(str).lstrip\n else\n \"\"\n end\nend\n</code></pre>\n\n<p>This should reduce complexity some, since both latter methods have essentially the same responsibility.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T01:24:11.107", "Id": "19797", "ParentId": "19796", "Score": "3" } }, { "body": "<p>To complement @mjgpy3's answer, some notes:</p>\n\n<ul>\n<li><p><code>def date_string(year=true)</code>. That's idiomatic Python, but in Ruby the idiomatic is <code>def date_string(year = true)</code>. Personally I don't like positional optional values, specially booleans; when you call them you have no idea what the argument stands for. You can use an options hash instead. Do you remember the old Rails <code>obj.save(false)</code>? wisely changed in Rails 3 to <code>obj.save(:validate =&gt; false)</code>.</p></li>\n<li><p>How to build string with conditional values: This is the pattern I use:</p>\n\n<pre><code>str = [\"%B %e\", *(\", %Y\" if year)].join\n</code></pre></li>\n<li><p>the <code>else</code> returns an empty string, why? it's better if it returns <code>nil</code>.</p></li>\n<li><p>Check <a href=\"http://api.rubyonrails.org/classes/String.html#method-i-squish\" rel=\"nofollow\">String#squish</a>.</p></li>\n</ul>\n\n<p>To sum it up, I'd write the first method like this:</p>\n\n<pre><code>def date_string(options = {})\n format = [\"%B %e\", *(\", %Y\" if options[:year])].join\n date.strftime(format).squish\nend\n</code></pre>\n\n<p>Just as a side note: does it make sense to have all these methods in a model? (or a presenter, it doesn't matter). Think of an orthogonal approach, create helper methods available for everbody to use (and send them date object), this way you achieve real modularity.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T19:00:39.390", "Id": "31677", "Score": "0", "body": "The reason for returning an empty string is these methods get chained together in some places, so if one of them returns nil it actually needs to be an empty string so I can join it to another string without checking for nil. Great suggestions though, this is really helpful to consider. I think you're right about extracting it to be more general purpose formatting helpers, I'll move the code that direction. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T19:02:19.200", "Id": "31678", "Score": "0", "body": "Also, string.squish is awesome, wow. Thanks for showing me that!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T20:45:36.263", "Id": "31687", "Score": "0", "body": "Regarding the empty string, yeah, sometimes is handy to return an empty string. But usually empty strings are not that useful, you want to let the caller decide how to handle it: `method_that_may_return_nil || default_value`. With empty strings you still can do it, but it's more verbose: `method_that_may_return_empty_string.presence || default_value`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T17:46:48.637", "Id": "19818", "ParentId": "19796", "Score": "2" } } ]
{ "AcceptedAnswerId": "19818", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T00:52:31.760", "Id": "19796", "Score": "3", "Tags": [ "strings", "ruby", "datetime" ], "Title": "Presenting a time as a string" }
19796
<p>I need to write a jQuery plugin that doesn't take an element to work.</p> <p>Example call:</p> <pre><code>$.funkyTown(); </code></pre> <p>... <strong>not</strong> called like this:</p> <pre><code>$('#foo').funkyTown(); </code></pre> <p>...in other words, I need this plugin to act more like a "utility" plugin (vs. apply itself directly to a matched element(s)).</p> <p>Here's what I have written so far:</p> <pre><code>;(function($, window, document, undefined) { var console = this.console || { log : $.noop, warn: $.noop }, // http://api.jquery.com/jQuery.noop/ defaults = { foo : 'bar', // Callbacks: onInit : $.noop, // After plugin data initialized. onAfterInit : $.noop // After plugin initialization. // Using $.noop shorter than function() {} and slightly better for memory. }, settings = {}, methods = { // Initialize! // Example call: // $.funkyTown({ foo : 'baz' }); // @constructor init : function(options) { settings = $.extend({}, defaults, options); settings.onInit.call(this, 'that'); console.log('1. init:', settings.foo, _foo_private_method(), methods.foo_public_method()); console.warn('2. I\'m a warning!'); settings.onAfterInit.call(this); return this; // Is this needed for chaining? }, // Example call: // console.log($.funkyTown('foo_public_method', 'Wha?')); foo_public_method : function(arg1) { arg1 = (typeof arg1 !== 'undefined') ? arg1 : 'Boo!'; return 'foo_public_method(), arg1: ' + arg1; }, // Might need to give users the option to destroy what this plugin created: destroy : function() { // Undo things here. } }, // The _ (underscore) is a naming convention for private members. _foo_private_method = function() { return '_foo_private_method(), settings.foo: ' + settings.foo; }; // Method calling logic/boilerplate: $.funkyTown = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if ((typeof method === 'object') || ( ! method)) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.funkyTown.'); } }; }(jQuery, window, document)); </code></pre> <p>The above is called like so:</p> <pre><code>$(document).ready(function() { // Calls init and modifies default options: $.funkyTown({ foo : 'baz' }); // Access to public method: console.log($.funkyTown('foo_public_method', 'Wha?')); }); </code></pre> <h3>My questions:</h3> <ol> <li>Do you see anything out of the ordinary with my above plugin template? If so, how could it be improved?</li> <li>Related to #1 above: As you can probably see, I'm trying to account for the various needs like passing <code>options</code>, <code>private</code> and <code>public</code> methods and <code>console</code> handling... What am I missing in terms of useful features? </li> <li><s>This line <code>$.funkyTown = function(method) {</code> makes the javascript linter throw a warning: <strong>"warning: anonymous function does not always return a value"</strong>; is there anyway for me to fix this? Could I just add <code>return false</code> to the end (right before the closing <code>};</code>?</s> <strong>Update:</strong> <a href="http://jshint.com" rel="nofollow noreferrer">Looks like I just needed to use a different tool</a>.</li> <li>Because I'm writing a utility plugin (one that will never be used directly on an element) do I still need to <code>return this</code> in my public methods in order to make things chainable (see the <code>return this; // Is this needed for chaining?</code> line of code above)? Should I even worry about chaining for this type of plugin?</li> <li>Could you provide any other feedback to help me improve my code?</li> <li><s>What's the easiest/best way to pass <code>settings</code> from <code>init</code> to other <code>private</code> and <code>public</code> functions? Normally, I'd use <code>.data()</code> on <code>$(this)</code> to store <code>settings</code> and other stateful vars... Because there's not element, should I just pass <code>settings</code> as an argument to the other methods?</s> <strong>Update:</strong> Doi! <a href="https://stackoverflow.com/a/5163338/922323">This was an easy one</a>! I simply needed to initialize my <code>settings</code> outside of my public methods object.</li> </ol> <hr> <p><strong>UPDATE 1:</strong></p> <p>I've updated my code (above) to reflect the things I've learned (i.e. the strike-through lines in numeric list above) since posting this question.</p> <p>I've also added a new feature:</p> <pre><code>;(function($, window, document, undefined) { // ... }(jQuery, window, document)); </code></pre> <p>I found that I needed access to <code>window</code> a few times already in my real script... After some Googling, I found this awesome resource:</p> <p><a href="http://shichuan.github.com/javascript-patterns/" rel="nofollow noreferrer">JavaScript Patterns Collection</a></p> <p>... which led me to here:</p> <p><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/lightweight.html" rel="nofollow noreferrer">Lightweight - perfect as a generic template for beginners and above</a></p> <p>... specifically:</p> <pre><code>// the semi-colon before the function invocation is a safety // net against concatenated scripts and/or other plugins // that are not closed properly. ;(function ( $, window, document, undefined ) { // undefined is used here as the undefined global // variable in ECMAScript 3 and is mutable (i.e. it can // be changed by someone else). undefined isn't really // being passed in so we can ensure that its value is // truly undefined. In ES5, undefined can no longer be // modified. // window and document are passed through as local // variables rather than as globals, because this (slightly) // quickens the resolution process and can be more // efficiently minified (especially when both are // regularly referenced in your plugin). })( jQuery, window, document ); </code></pre> <p><strong>Update 2:</strong></p> <p>I've added callbacks. I've also decided to use <code>$.noop</code> in place of <code>function() {}</code>:</p> <blockquote> <p>... typing $.noop is 6 chars shorter than function(){}. Also if you use this everywhere instead of creating new, anonymous, empty functions, you'll slightly cut down on memory. – <a href="http://api.jquery.com/jQuery.noop/#comment-29875717" rel="nofollow noreferrer">Marco</a></p> </blockquote> <p>Now I'm wondering what my callbacks should return in a utility plugin? Sending <code>this</code> doesn't seem that useful.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-28T15:42:07.520", "Id": "35878", "Score": "1", "body": "To answer your last update's question, you should probably still return `this` to continue chaining. Yeah it might not seem useful, but it's what someone would expect if they just walked in on the plugin." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T20:11:17.697", "Id": "37289", "Score": "0", "body": "@JonnySooter If you look at my `init` method (in my plugin example above), I'm returning `this` at the end of `init`; is this a good spot to do that? In my last update, I was asking specifically about my callback methods; I just wanted to clarify about my `init` method as well. Thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:16:19.757", "Id": "37326", "Score": "0", "body": "Answer to your comment is a bit long to fit here so I placed in answer." } ]
[ { "body": "<p>What I suggest is read the jQuery source. Check out how they do it. In their init method they return this for certain cases, but not for others.</p>\n\n<p>Like when there is no selector:</p>\n\n<pre><code>if ( !selector ) {\n return this;\n}\n</code></pre>\n\n<p>But if you check out other \"utility\" plugins in their source like $.map</p>\n\n<pre><code>map: function( elems, callback, arg ) {\nvar value,\n i = 0,\n length = elems.length,\n isArray = isArraylike( elems ),\n ret = [];\n\n // Go through the array, translating each of the items to their\n if ( isArray ) {\n for ( ; i &lt; length; i++ ) {\n value = callback( elems[ i ], i, arg );\n\n if ( value != null ) {\n ret[ ret.length ] = value;\n }\n }\n\n // Go through every key on the object,\n } else {\n for ( i in elems ) {\n value = callback( elems[ i ], i, arg );\n\n if ( value != null ) {\n ret[ ret.length ] = value;\n }\n }\n }\n\n // Flatten any nested arrays\n return core_concat.apply( [], ret );\n},\n</code></pre>\n\n<p>Here they don't return the jQuery object, since this utility is for arrays. My point here is that there's no one shoe fits all. It depends on what you're trying to get from your plugin. Also chaining is expected but not on something like $.map(). </p>\n\n<p>Also keep in mind, in your callbacks <code>this</code> should refer to the element in question (ie. in a click callback <code>this</code> refers to the clicked element). If you're not playing with an element, <code>this</code> should refer to the global(window) object.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:30:18.043", "Id": "24203", "ParentId": "19799", "Score": "3" } }, { "body": "<p>Late to the party I know but after looking into this for my own uses I found the jquery documentation for <code>$.extend</code> (<a href=\"http://api.jquery.com/jquery.extend/\" rel=\"nofollow\">http://api.jquery.com/jquery.extend/</a>) seems to be the answer:</p>\n\n<blockquote>\n <p>If only one argument is supplied to $.extend(), this means the target\n argument was omitted. In this case, the jQuery object itself is\n assumed to be the target. By doing this, you can add new functions to\n the jQuery namespace. This can be useful for plugin authors wishing to\n add new methods to JQuery.</p>\n</blockquote>\n\n<p>I create a simple proof of concept:</p>\n\n<p><a href=\"http://jsbin.com/cixik/1/edit?js\" rel=\"nofollow\">http://jsbin.com/cixik/1/edit?js</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-11T18:14:11.873", "Id": "54007", "ParentId": "19799", "Score": "2" } } ]
{ "AcceptedAnswerId": "24203", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T05:26:47.550", "Id": "19799", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "A jQuery \"utility\" plugin template" }
19799
<p>I wrote a small script as an <a href="https://stackoverflow.com/questions/13927204/how-to-get-php-comment-lines-code-lines-count-in-ruby-on-rails-using-regular-ex/13964135#13964135">answer for a Stack Overflow question</a>, which referred to counting lines of code and comments (in C and C++ style).</p> <pre><code>f = File.open("test.txt") loc = 0 comments = 0 while line = f.gets if commented ||= line.match(/^\/\*/) commented = nil if line.match(/\*\/$/) comments += 1 elsif line.match(/^\s*\/\//) comments += 1 else loc +=1 unless line.match(/^\s*\n/) end end puts loc puts comments </code></pre> <p>I'm just looking for a review.</p>
[]
[ { "body": "<p>Your code looks pretty good to me, only that it's very imperative. I know it's not for everybody's taste, but a functional approach on text processing is also feasible. </p>\n\n<p>My take: you start by defining an object (which may be a hash) to store the state (needed for in intermediate iterations and the final result), and then fold (<code>reduce</code>/<code>inject</code>) over the input lines, returning the next state on each step.</p>\n\n<p>There are some edge cases (lines with multiple or nested comment) which I won't consider, let's keep it simple. I'd write:</p>\n\n<pre><code>initial_state = {lines: 0, comments: 0, in_multiline_comment: false}\nfinal_state = open(\"test.txt\").lines.inject(initial_state) do |state, line|\n state_update = if state[:in_multiline_comment]\n {comments: state[:comments] + 1, in_multiline_comment: !line.match(/\\*\\//)}\n else\n case line \n when /\\/\\*/\n {comments: state[:comments] + 1, in_multiline_comment: !line.match(/\\*\\//)}\n when /\\/\\//\n {comments: state[:comments] + 1}\n else\n {lines: state[:lines] + (line.strip.empty? ? 0 : 1)}\n end\n end\n state.merge(state_update)\nend\n</code></pre>\n\n<p>Notice that you don't worry about stateful variables anymore, we just think \"if I have this input and this current state, what output would I want?\". Once you've covered all scenarios, the algorithm is done (hopefully leaving behind a declarative and maintainable code).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T23:17:18.143", "Id": "31741", "Score": "0", "body": "Thanks, definitively a whole different way of solving it. Plus a nice explanation of how it's done." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T13:07:43.990", "Id": "19813", "ParentId": "19800", "Score": "3" } } ]
{ "AcceptedAnswerId": "19813", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T07:17:25.473", "Id": "19800", "Score": "3", "Tags": [ "ruby", "regex" ], "Title": "Count comments and lines of code" }
19800
<p>I am trying to solve <a href="https://www.interviewstreet.com/challenges/dashboard/#problem/4e14b2cc47f78" rel="nofollow">the "Meeting Point" problem from interviewstreet.com</a>:</p> <blockquote> <p>There is an infinite integer grid at which <strong>N</strong> people have their houses on. They decide to unite at a common meeting place, which is someone's house. From any given cell, all 8 adjacent cells are reachable in 1 unit of time. eg: (x,y) can be reached from (x-1,y+1) in a single unit of time. Find a common meeting place which minimises the sum of the travel times of all the persons.</p> </blockquote> <p>For example, if the input is:</p> <pre><code>4 0 1 2 5 3 1 4 0 </code></pre> <p>the output must be 8. Here's my solution:</p> <pre><code>def pos(a): if a&lt;0: return -a else: return a n = long(raw_input()) min =0 inputs = [] for i in range(n): temp = raw_input().split() inputs.append([long(temp[0]),long(temp[1])]) x = inputs[0][0] y = inputs[0][1] for i in range(n): min += max(pos(x-inputs[i][0]),pos(y-inputs[i][1])) for i in range(1,n): x = inputs[i][0] y = inputs[i][1] temp =0 for j in range(n): temp += max(pos(x-inputs[j][0]),pos(y-inputs[j][1])) if min&gt;temp: min =temp print min </code></pre> <p>I know I am brute forcing the answer but I couldn't find an algorithm that fits the problem. I have been thinking about the problem statement for a while yet I don't have any clue how to optimize it. If any of you could help me with the code in Python or C.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T09:55:18.843", "Id": "31654", "Score": "0", "body": "Dont have an idea for a fancy algorithm, but on the code: Instead of your pos function, you can use math.fabs() and try to use list comprehensions.\n`for i in range(n):\n min += max(pos(x-inputs[i][0]),pos(y-inputs[i][1]))`\nwould become something like\n`min = sum([max(pos(x-inputs[i][0]),pos(y-inputs[i][1])) for i in range(n)])`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T12:35:41.043", "Id": "31658", "Score": "0", "body": "\"an infinite integer grid\" And just what it that? Can we assume that people live in one big square of x*y cells? Or do they live \"anywhere\"? Are there empty lots? The specification is too poorly worded to give an answer. If you just start to blindly code away without asking such questions, you aren't going to perform well on an interview." } ]
[ { "body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>Your function <code>pos</code> computes the <a href=\"http://en.wikipedia.org/wiki/Absolute_value\" rel=\"nofollow noreferrer\">absolute value</a> of <code>a</code>, and is already built into Python under the name <a href=\"http://docs.python.org/2/library/functions.html#abs\" rel=\"nofollow noreferrer\"><code>abs</code></a>.</p></li>\n<li><p>You'd benefit from structuring your code into functions. For example, the expression <code>max(pos(x-inputs[j][0]),pos(y-inputs[j][1]))</code> appears twice. Your code would be clearer if you'd written a function with a docstring, for example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def distance(A, B):\n \"\"\"Return the Chebyshev distance from A to B.\"\"\"\n return max(abs(a - b) for a, b in zip(A, B))\n</code></pre>\n\n<p>(\"<a href=\"http://en.wikipedia.org/wiki/Chebyshev_distance\" rel=\"nofollow noreferrer\">Chebyshev distance</a>\" is a name that mathematicians give to this function.)</p></li>\n<li><p>You have code near the start for finding the total distance if the meeting point is at house number 0, but then you repeat that code inside a loop over the other meeting points. This seems like a waste. I guess you're doing this because you need an initial value for <code>min</code>.</p>\n\n<p>But instead you could use Python's built-in function <a href=\"http://docs.python.org/2/library/functions.html#min\" rel=\"nofollow noreferrer\"><code>min</code></a>, which avoids the need for a special case to get the initial value. This needs a bit of re-organization, but it comes out quite simple:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def total_distance(Q, points):\n \"\"\"Return the total distance from Q to each of the points in the\n sequence points.\n \"\"\"\n return sum(distance(Q, P) for P in points)\n\ndef min_total_distance(points):\n \"\"\"Find that point that minimizes the total distance to the\n other points, and return the minimum total distance.\n \"\"\"\n return min(total_distance(P, points) for P in points)\n</code></pre>\n\n<p>If you are a fan of hard-to-read code, then you could write the entire computation in a single expression:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>min(sum(max(abs(a - b) for a, b in zip(P, Q)) for P in points) for Q in points)\n</code></pre></li>\n</ol>\n\n<h3>2. A better algorithm</h3>\n\n<p>Your algorithm is \\$Θ(n^2)\\$: it has to compute the distance between every pair of houses. In the interviewstreet.com version of the problem, they say that \\$n ≤ 10^5\\$ so your approach takes up to \\$10^{10}\\$ distance computations. That's not utterly intractable, but it's not going to be doable within the time limits at interviewstreet.com.</p>\n\n<p>So is there an approach which scales better as \\$n\\$ becomes large?</p>\n\n<p>Well, if we weren't restricted to the meeting point being one of the houses, then the best meeting point would be the <a href=\"http://en.wikipedia.org/wiki/Geometric_median\" rel=\"nofollow noreferrer\">geometric median</a>. The geometric median is hard to compute, but it can be approximated by an iterative procedure due to <a href=\"http://en.wikipedia.org/wiki/Endre_Weiszfeld\" rel=\"nofollow noreferrer\">Endre Weiszfeld</a>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def median_approx(P, points):\n \"\"\"Return a new approximation to the geometric median of points by\n applying one iteration of Weiszfeld's algorithm to the old\n appromixation P.\n \"\"\"\n W = x = y = 0.0\n for Q in points:\n d = distance(P, Q)\n if d != 0:\n w = 1.0 / d\n W += w\n x += Q[0] * w\n y += Q[1] * w\n return x / W, y / W\n\ndef geometric_median(points, epsilon):\n \"\"\"Return an approximation to the geometric median for points.\n Start with the centroid and apply Weiszfeld's algorithm until the\n distance between steps is less than epsilon.\n \"\"\"\n n = float(len(points))\n P = tuple(sum(P[i] for P in points) / n for i in range(2))\n while True:\n Q = median_approx(P, points)\n if distance(P, Q) &lt; epsilon:\n return Q\n P = Q\n</code></pre>\n\n<p>Unfortunately, for this problem, the meeting point must be one of the original points, so the geometric median doesn't solve it.</p>\n\n<p>However, if the set of points is fairly random (that is, not chosen adversarially), then the best meeting point seems likely to be one of the closest points in the set to the geometric median.</p>\n\n<p>So we have a chance of finding the best meeting point by taking a heuristic approach: compute an approximation \\$G\\$ to the geometric median, sort the points by their distance from \\$G\\$, look at the closest \\$k\\$ points, and pick the best one. If we choose \\$ε\\$ to be small enough, and \\$k\\$ to be large enough (but not so large that the computation takes too long), then we'll get the right answer.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from heapq import nsmallest\n\ndef best_meeting_point(points, epsilon, k):\n \"\"\"Return (a guess at) the point in points that minimizes the sum\n of distances to the other points, by computing an approximation\n G to the geometric median (using epsilon) and then taking the\n best point among the closest k points to G.\n \"\"\"\n G = geometric_median(points, epsilon)\n closest_k = nsmallest(k, points, key = lambda P: distance(G, P))\n return min(closest_k, key = lambda P: total_distance(P, points))\n</code></pre>\n\n<p>This runs in \\$O(jn + kn)\\$ where \\$j\\$ iterations are needed for Weiszfeld's algorithm to converge. \\$j\\$ doesn't grow proportionally with \\$n\\$ (it depends on \\$ε\\$ and on the magnitude of the coordinates in the input), so this is \\$o(n^2)\\$.</p>\n\n<p>But beware: if the points are chosen adversarially, I think \\$k\\$ might have to grow like \\$Ω(n)\\$. I don't know an efficient algorithm for finding the answer in this case. So whether you can use this algorithm to pass the challenge at interviewstreet.com depends on how nice their test cases are. Good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T21:12:38.363", "Id": "31691", "Score": "0", "body": "i have a doubt the median is the best place if literal distance between the points is concern or sum of positive values of difference between x coordinates and y coordinates is taken but the distance considered is neither it is the max value of difference between x coordinates or y coordinates which is not necessarily proportional to literal distance between the points" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T21:20:31.310", "Id": "31692", "Score": "0", "body": "You can compute a geometric median for any [metric](http://en.wikipedia.org/wiki/Metric_(mathematics)), not only for the [Euclidean metric](http://en.wikipedia.org/wiki/Euclidean_metric)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T11:13:31.723", "Id": "19804", "ParentId": "19801", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T09:14:04.683", "Id": "19801", "Score": "5", "Tags": [ "python", "performance" ], "Title": "Meeting Point problem from interviewstreet.com" }
19801
<p>i am trying to learn Trie Data Structure and just implemented it without giving much attention to the code standards , its a raw implementation , can you guys help me to understand whether this implementation make some good progress?</p> <p>Thanks</p> <pre><code>public class TrieNode { public string Word { get; set; } public IList&lt;TrieNode&gt; Childs { get; set; } } public class TheNobalTrie { public TheNobalTrie() { RootNode = new TrieNode { Word = string.Empty, Childs = new List&lt;TrieNode&gt;() }; } public bool AddWord(string word) { TrieNode firstNode = null; word = word.ToLower(); int levelDepth = 0; while (true) { var tempWord = word[levelDepth]; firstNode = RootNode.Childs.FirstOrDefault(x =&gt; x.Word[levelDepth].Equals(tempWord)); if(firstNode==null) { RootNode.Childs.Add(AddNode(word, tempWord,0)); return true; } var immidiateParentNode = firstNode; while (firstNode != null) { levelDepth++; //if below condition is true , it means word is being repeated so don't add it again. if (levelDepth == word.Length) return false; tempWord = word[levelDepth]; immidiateParentNode = firstNode; firstNode = firstNode.Childs.FirstOrDefault(x =&gt; x.Word[0].Equals(tempWord)); } immidiateParentNode.Childs.Add(AddNode(word, tempWord,levelDepth)); return true; } } public IList&lt;string&gt; GetMatchingWords(string word) { var list = new List&lt;string&gt;(); word = word.ToLower(); int levelDepth = 0; if (string.IsNullOrEmpty(word)) return list; var tempWord = word[0]; var firstNode = RootNode.Childs.FirstOrDefault(x =&gt; x.Word[0].Equals(tempWord)); if (firstNode == null) { return list; } var nodePath = new Queue&lt;TrieNode&gt;(); var sb = new StringBuilder(); while (firstNode != null) { levelDepth++; if (levelDepth == word.Length) { break; } tempWord = word[levelDepth]; firstNode = firstNode.Childs.FirstOrDefault(x =&gt; x.Word[0].Equals(tempWord)); } if (firstNode != null) nodePath.Enqueue(firstNode); while (nodePath.Any()) { var tempNode = nodePath.Dequeue(); PopulateWords(tempNode, sb, ref list); } var tempList= list.Select(x =&gt; word + x).ToList(); return tempList; } private void PopulateWords(TrieNode node, StringBuilder sb, ref List&lt;string&gt; list) { if (node.Childs.Any()) { foreach (var temp in node.Childs) { if (temp.Childs.Any()) { var tempBuilder = new StringBuilder(); tempBuilder.Append(sb); tempBuilder.Append(temp.Word); PopulateWords(temp, tempBuilder, ref list); } else { sb.Append(temp.Word); list.Add(sb.ToString()); } } } else { list.Add(sb.ToString()); } } private TrieNode AddNode(string word, char tempWord, int levelDepth) { var node = new TrieNode { Word = tempWord.ToString(), Childs = new List&lt;TrieNode&gt;() }; var tempNode = node; for (int j = levelDepth+1; j &lt; word.Length; j++) { var t = new TrieNode { Word = word[j].ToString(), Childs = new List&lt;TrieNode&gt;() }; tempNode.Childs.Add(t); tempNode = t; } return node; } public TrieNode RootNode { get; private set; } </code></pre> <p>}</p>
[]
[ { "body": "<p>It looks like valid implementation, but it could be simplified. Also there are some naming issues: <code>tempWord</code> in <code>AddWord</code> method is actually a <code>char</code> and not a string. <code>TrieNode.Word</code> carries a single char but is declared as <code>string</code>.</p>\n\n<p>You have a lot of trie management code inside <code>TheNobalTrie</code> class while it would be more readable to have the logic in <code>TrieNode</code> class: each node would be responsible for making decisions on its own level, delegating further decisions to its children. Also there is a common trie optimization that groups several chars in one node, e.g. if you have only <code>dine</code> and <code>dinner</code> words you would have 3 nodes: <strong>din</strong> with children (din)<strong>e</strong> and (din)<strong>ner</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T16:30:55.233", "Id": "19815", "ParentId": "19802", "Score": "1" } } ]
{ "AcceptedAnswerId": "19815", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T09:47:23.780", "Id": "19802", "Score": "1", "Tags": [ "c#", "algorithm", "trie" ], "Title": "Is this a valid implementation of trie Data structure?" }
19802
<p>I have written a little bit of code which illustrates DI(dependency injection) and IoC(Inversion of control) container. The point of this exercise is to illustrate the two methods by which you can actieve inversion of control.</p> <p>Please let me know if this code achieves the objective. (That is, if I have illustrated the two concepts clearly. Let me know if there is any improvement possible. (In any area like coding style, naming style, comments)</p> <p>I have 4 classes for this:</p> <ol> <li><code>Dependencies</code>: This class holds the interface and the two concrete implementations</li> <li><code>CoreClassDI</code>: This class illustrates dependency injection</li> <li><code>ControlInversionAid</code>: This holds a simple IoC container following instructions from <a href="http://kenegozi.com/Blog/2008/01/17/its-my-turn-to-build-an-ioc-container-in-15-minutes-and-33-lines" rel="nofollow">here</a>. Hence I will not be sharing this code for review.</li> <li><code>Program</code>: This is the console application that illustrates the concepts</li> <li><code>WritePredictions</code>: This invokes the method on the dependency</li> </ol> <p>Now, for the code:</p> <p><strong>Dependencies</strong></p> <pre><code>namespace Dependencies { public interface IPredictingFuture { string WhatWillBeGoodNextYear(); } public class EartAndSkyPrediction : IPredictingFuture { public EartAndSkyPrediction() { Console.ForegroundColor = ConsoleColor.DarkGreen; } public string WhatWillBeGoodNextYear() { return ("Everything will be good next year, especially if you are good!"); } } public class BadConnections : IPredictingFuture { public BadConnections() { Console.ForegroundColor = ConsoleColor.Red; } public string WhatWillBeGoodNextYear() { return ("Take care!! It is a terrible year :-("); } } } </code></pre> <p><strong>CoreClassDI</strong></p> <pre><code>namespace CoreClassDI { public class TheOracle { //Property Injection. This is injecting the correct concrete implementation //through a property. One can also use a constructor or an //interface implementation to inject dependencies. public IPredictingFuture FuturePredictions { get; private set; } //This is a predict function in which you "inject" the concrete class //in the property. The property injection is achieved through the constructor. //We can also alternatively inject dependencies through the WriteOutPredictions() //function. public TheOracle(IPredictingFuture predictionType) { FuturePredictions = predictionType; } } } </code></pre> <p><strong>WritePredictions</strong></p> <pre><code>namespace ClientCode { //This is the class which actually writes out the predictions based on the //actual class loaded either through Injection or the IoC container public class WritePredictions { public static void WritePredictionsOnScreen(IPredictingFuture predictIt) { Console.WriteLine("How will my year be?"); Console.WriteLine(predictIt.WhatWillBeGoodNextYear()); Console.WriteLine("**********"); } } } </code></pre> <p><strong>Program</strong></p> <pre><code>namespace ClientCode { //This is the main program which controls and illustrates the different types of DI //You need to start debug in one of these programs to understand the concepts //of DI and IoC class Program { static void Main(string[] args) { string choice; string input; Console.WriteLine("Choose the correct option"); Console.WriteLine("1 for dependency injection"); Console.WriteLine("2 for IoC container"); input = Console.ReadKey().KeyChar.ToString(); switch (input) { case "1": Console.WriteLine("Welcome! Do you want a good prediction? Or a Bad prediction?"); Console.WriteLine("Hit G for good predictions and B for bad predictions"); choice = Console.ReadKey().KeyChar.ToString(); IPredictingFuture predictionObj = null; //The dependency is loaded based on run time choice switch (choice) { case "G": case "g": //Setting good predictions predictionObj = new EartAndSkyPrediction(); break; case "B": case "b": //Setting bad predictions on the same object predictionObj = new BadConnections(); break; default: Console.WriteLine("Good going! Who cares anyway?"); break; } //Injecting the prediction object and calling the client code with it TheOracle oracleObj = new TheOracle(predictionObj); WritePredictions.WritePredictionsOnScreen(oracleObj.FuturePredictions); Console.ReadKey(true); break; case "2": Console.WriteLine("Welcome! Do you want a good prediction? Or a Bad prediction?"); Console.WriteLine("Hit G for good predictions and B for bad predictions"); choice = Console.ReadKey().KeyChar.ToString(); switch (choice) { case "G": case "g": //Registering the good predictions IoC.Register&lt;IPredictingFuture, EartAndSkyPrediction&gt;(); break; case "B": case "b": //Loading the bad predictions IoC.Register&lt;IPredictingFuture, BadConnections&gt;(); break; default: Console.WriteLine("Good going! Who cares anyway?"); Console.ReadKey(true); break; } //Resolving to the registered predictions WritePredictions.WritePredictionsOnScreen(IoC.Resolve&lt;IPredictingFuture&gt;()); Console.ReadKey(true); break; default: Console.WriteLine("Invalid choice"); Console.ReadKey(true); break; } } } } </code></pre>
[]
[ { "body": "<p>Possible Improvements of above code:</p>\n\n<p>WritePredictions class should not be responsible for calling the WhatWillBeGoodNextYear method of Prediction, this is the job of TheOracle Class.I have created IWriter interface for switching out the Output console. so WritePredictions class is not needed.</p>\n\n<pre><code> public class TheOracle\n {\n public IWriter Writer { get; set; }\n\n public IPredictingFuture FuturePredictions { get; private set; }\n\n //This is a predict function in which you \"inject\" the concrete class\n //in the property. The property injection is achieved through the constructor.\n //We can also alternatively inject dependencies through the WriteOutPredictions()\n //function.\n public TheOracle(IPredictingFuture predictionType)\n {\n FuturePredictions = predictionType;\n }\n\n public void PredictAndWriteToLogger()\n {\n Writer.WriteMsg(FuturePredictions.WhatWillBeGoodNextYear());\n }\n }\n\n public interface IWriter\n {\n void WriteMsg(string message);\n }\n</code></pre>\n\n<p>rest of code looks okay to me.You can also return string from your Predict method and let client to decide whether to write.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T11:46:47.780", "Id": "31655", "Score": "0", "body": "Thanks for this tip. It definitely makes the code more elegant!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T11:08:11.310", "Id": "31708", "Score": "0", "body": "Paritosh, I did take your idea of adding IWriter interface. I moved the message writing functionality to the concrete implementation of `IPrediction` interface. `TheOracle` class is used to illustrate dependency injection. Hence I did not add this there. I will be renaming that class to avoid confustion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T11:21:16.913", "Id": "31710", "Score": "0", "body": "No problem,my intent is that you understood aspects of DI and IOC. No code is gud or bad , untill it serve it purpose." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T11:38:19.903", "Id": "19805", "ParentId": "19803", "Score": "2" } }, { "body": "<p>Your example does show <a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow\">IoC</a> tecnhique by passing interface to <code>WritePredictionsOnScreen</code> rather than actual implementation, but doesn't show the power of DI containers like auto-wiring and object lifetime management. </p>\n\n<p>In your example IoC container looks like just a replacement of a local variable that holds the instance <code>IPredictingFuture</code>.</p>\n\n<p>Example of DI autowiring using Autofac (use <code>Install-Package Autofac</code> in NuGet console to install it). I borrowed <code>paritosh</code>'s definition of Oracle, it is more appropriate and demonstrates the IoC better than original code. I register <code>TheOracle</code> before registering classes it depends on to show that the order is not significant here. </p>\n\n<p>Note that <code>FuturePredictions</code> is initialized through constructor while <code>Writer</code> is injected via property (just for demonstration, it would be better to use common approach):</p>\n\n<pre><code>public interface IPredictingFuture\n{\n string WhatWillBeGoodNextYear();\n}\n\npublic interface IWriter\n{\n void WriteMsg(string message);\n}\n\npublic class EartAndSkyPrediction : IPredictingFuture\n{\n public EartAndSkyPrediction()\n {\n Console.ForegroundColor = ConsoleColor.DarkGreen;\n }\n\n public string WhatWillBeGoodNextYear()\n {\n return (\"Everything will be good next year, especially if you are good!\");\n }\n}\n\npublic class BadConnections : IPredictingFuture\n{\n public BadConnections()\n {\n Console.ForegroundColor = ConsoleColor.Red;\n }\n\n public string WhatWillBeGoodNextYear()\n {\n return (\"Take care!! It is a terrible year :-(\");\n }\n}\n\npublic class TheOracle\n{\n public IWriter Writer { get; set; }\n\n public IPredictingFuture FuturePredictions { get; private set; }\n\n //This is a predict function in which you \"inject\" the concrete class\n //in the property. The property injection is achieved through the constructor.\n //We can also alternatively inject dependencies through the WriteOutPredictions()\n //function.\n public TheOracle(IPredictingFuture predictionType)\n {\n FuturePredictions = predictionType;\n }\n\n public void PredictAndWriteToLogger()\n {\n Writer.WriteMsg(FuturePredictions.WhatWillBeGoodNextYear());\n }\n}\n\npublic class WritePredictions : IWriter\n{\n public void WriteMsg(string message)\n {\n Console.WriteLine(\"How will my year be?\");\n Console.WriteLine(message);\n\n Console.WriteLine(\"**********\");\n }\n}\n\ninternal class Program\n{\n private static void Main()\n {\n var builder = new ContainerBuilder();\n builder.RegisterType&lt;TheOracle&gt;().PropertiesAutowired();\n builder.RegisterType&lt;WritePredictions&gt;().AsImplementedInterfaces();\n\n Console.WriteLine(\"Welcome! Do you want a good prediction? Or a Bad prediction?\");\n Console.WriteLine(\"Hit G for good predictions and B for bad predictions\");\n\n var choice = Console.ReadKey().KeyChar.ToString();\n switch (choice)\n {\n case \"G\":\n case \"g\":\n //Registering the good predictions\n builder.RegisterType&lt;EartAndSkyPrediction&gt;().AsImplementedInterfaces();\n break;\n case \"B\":\n case \"b\":\n //Loading the bad predictions\n builder.RegisterType&lt;BadConnections&gt;().AsImplementedInterfaces();\n break;\n default:\n Console.WriteLine(\"Good going! Who cares anyway?\");\n Console.ReadKey(true);\n break;\n }\n\n var container = builder.Build();\n var theOracle = container.Resolve&lt;TheOracle&gt;();\n theOracle.PredictAndWriteToLogger();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T11:48:53.440", "Id": "31656", "Score": "0", "body": "Can you give me a small example for illustrating the power of DI? Also, how else do you think an IoC container needs to be used? Can you give me an example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T12:15:00.527", "Id": "31657", "Score": "0", "body": "@TheSilverBullet updated my answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T13:50:56.693", "Id": "31662", "Score": "0", "body": "I wanted to use my own IoC container so that I would understand it better. I would ofcourse shift to Autofac later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T13:52:39.780", "Id": "31663", "Score": "0", "body": "Looks like you have included DI and use of IoC container in lesser piece of code than I originally wrote. This is good! Thanks! But one thing I did not understand is how you injected the Writer. Can you point me to the line specifically... (Sorry!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T13:59:13.690", "Id": "31664", "Score": "0", "body": "`builder.RegisterType<WritePredictions>().AsImplementedInterfaces();` - I got the line. So once this line executes, would the `IWriter` property be set to `WritePredictions`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T16:33:54.637", "Id": "31668", "Score": "0", "body": "The IoC framework makes decision what to inject at the time of resolving the instance (`container.Resolve<TheOracle>()`). At that time it injects all the instance it is aware of." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T11:11:52.677", "Id": "31709", "Score": "0", "body": "This is interesting! I did not think the IoC container could be used this way! I have re-written my code taking some of your inputs. I will be making another question on this site and will link it up to this questions. Your comments there would be appreciated! Thanks, almaz." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T11:38:40.797", "Id": "19806", "ParentId": "19803", "Score": "3" } } ]
{ "AcceptedAnswerId": "19806", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T10:06:45.050", "Id": "19803", "Score": "2", "Tags": [ "c#", "dependency-injection" ], "Title": "Illustrating DI and IoC concepts : Simple code requesting review" }
19803
<p>I'm working on the Rails project where I have many-to-many :through relationship. Each setting has many notifications through email_notification model where the notification can be primary or a secondary.</p> <p><code>schema.rb</code></p> <pre><code>create_table "email_notifications", :force =&gt; true do |t| t.integer "setting_id" t.integer "notification_id" t.boolean "primary" t.boolean "secondary" create_table "notifications", :force =&gt; true do |t| t.string "name" create_table "settings", :force =&gt; true do |t| t.string "truck_identification" t.string "email_periods" t.integer "email_recepient_id" t.datetime "created_at", :null =&gt; false t.datetime "updated_at", :null =&gt; false t.integer "truck_fleet_id" </code></pre> <p>In models</p> <pre><code>class EmailNotification &lt; ActiveRecord::Base attr_accessible :notification_id, :setting_id, :primary, :secondary belongs_to :notification belongs_to :setting class Notification &lt; ActiveRecord::Base attr_accessible :name has_many :settings, :through =&gt; :email_notifications has_many :email_notifications end class Setting &lt; ActiveRecord::Base # TODO: refactor this bullshit attr_accessible :email_periods, :email_recepient_id, :truck_identification, :truck_fleet_id has_many :notifications, :through =&gt; :email_notifications has_many :email_notifications validates_uniqueness_of :truck_fleet_id # validates :email, :email_format =&gt; true end </code></pre> <p>I used this many-to-many relationship because I need flexibility to add up new Notifications over the time, and keep ability to make notifications flexible as possible. For example, I might add a column <code>frequency</code>, or <code>interval</code> etc. </p> <p>Let me know if you can find a better solution.</p>
[]
[ { "body": "<pre><code># TODO: refactor this bullshit\n</code></pre>\n\n<p>While amusing to devs, swear words probably don't belong in production code.</p>\n\n<p>In your copypasta of <code>schema.rb</code>, I do believe you forgot to paste the <code>end</code> keywords. </p>\n\n<p>As a side note, you can also write <code>null: false</code> instead of <code>:null =&gt; false</code>; as far as I can tell, this is the accepted syntax. You can do the same thing with <code>through: :email_notifications</code> and anything of the form <code>Symbol =&gt; BasicObject</code>. This syntax was added after this question was posted, but if you're still interested in updating it, that's what I'd do.</p>\n\n<p>Personally, I prefer to use Symbols instead of Strings as table names, though that's entirely personal preference.</p>\n\n<p>In your models, you also forgot an <code>end</code> at the end of your first class.</p>\n\n<p>Aside from that... Well, honestly, it looks good to me. Since I can't really tell what <code>Setting</code> and <code>Notification</code> are supposed to represent on a more concrete level than their names alone can give, I can't give good advice on how to link them together. However, I don't see why you need a many-to-many, if I'm understanding the purpose of <code>Setting</code> and <code>Notification</code> correctly. It seems like it could be a one-to-many relationship, though I'm not sure which side should be the one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-28T13:21:39.367", "Id": "173211", "Score": "0", "body": "To be fair to OP, `schema.rb` is auto-generated. It's not intended to be edited manually (the spacing is Rails' fault). Also, since it's a 3 year old question, the hashrocket syntax (`=>`) was perhaps the only syntax available at the time. The JSON-like `key: value` syntax didn't appear until Ruby 1.9." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-28T13:25:03.287", "Id": "173212", "Score": "1", "body": "@Flambino Oh, I wasn't aware that `schema.rb` was autogenerated. I'm just gonna delete that point and pretend it never existed... (And yes, I'm aware of the latter. I had a sentence in there like \"It was introduced in 1.9\" somewhere but I guess it got lost while I was shuffling around the points in my answer.) Fixed both points." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-28T04:24:54.723", "Id": "94962", "ParentId": "19807", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T11:44:26.817", "Id": "19807", "Score": "7", "Tags": [ "ruby", "ruby-on-rails", "email", "active-record" ], "Title": "Email notifications system in Rails project" }
19807
<p>Having an issue optimising has_many through relationship</p> <p>To quickly introduce I have Setting model and Notification model (that is mainly used as a storage of all notification types).</p> <p>They have through relationship :email_notification, where notification can be specified as primary or secondary.</p> <p>I think I have hardcoded the new, create, edit and update actions:</p> <pre><code> def new @setting = Setting.new(:truck_fleet_id =&gt; current_user.truck_fleet.id) if !current_user.admin? @setting = Setting.new(:truck_fleet_id =&gt; 3) if current_user.admin @notifications = Notification.all respond_to do |format| format.html # new.html.erb format.json { render json: @setting } end end # GET /settings/1/edit def edit @setting = Setting.find(params[:id]) @notifications = Notification.all @notifications.each do |n| @setting.email_notifications.build(:notification_id =&gt; n.id) end if @setting.email_notifications.blank? end # POST /settings # POST /settings.json def create @setting = Setting.new(params[:setting]) @notifications = Notification.all respond_to do |format| if @setting.save @notifications.each do |n| if params[:fields][n.id.to_s].nil? @setting.email_notifications.create!(:notification_id =&gt; n.id.to_s, :primary =&gt; false, :secondary =&gt; false) else @setting.email_notifications.create!(:notification_id =&gt; n.id.to_s, :primary =&gt; params[:fields][n.id.to_s][:primary] ||= false, :secondary =&gt; params[:fields][n.id.to_s][:secondary] ||= false) end end format.html { redirect_to @setting, notice: 'Setting was successfully created.' } format.json { render json: @setting, status: :created, location: @setting } else format.html { render action: "new" } format.json { render json: @setting.errors, status: :unprocessable_entity } end end end # PUT /settings/1 # PUT /settings/1.json def update @setting = Setting.find(params[:id]) @notifications = Notification.all respond_to do |format| if @setting.update_attributes(params[:setting]) @notifications.each do |n| em = @setting.email_notifications.where(:notification_id =&gt; n.id).first if params[:fields][n.id.to_s].nil? em.update_attributes(:notification_id =&gt; n.id.to_s, :primary =&gt; false, :secondary =&gt; false) else em.update_attributes(:notification_id =&gt; n.id.to_s, :primary =&gt; params[:fields][n.id.to_s][:primary] ||= false, :secondary =&gt; params[:fields][n.id.to_s][:secondary] ||= false) end end format.html { redirect_to @setting, notice: 'Setting was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @setting.errors, status: :unprocessable_entity } end end end </code></pre> <p>and in the <code>app/views/settings/_form.html.erb</code></p> <pre><code>&lt;%= form_for @setting, :html =&gt; { :class =&gt; 'form-horizontal' } do |f| %&gt; &lt;% @setting.email_notifications.each do |e, i| %&gt; &lt;%= f.fields_for e do |builder| %&gt; &lt;%= render "update_email_notifications", :f =&gt; builder, :emails =&gt; e, :index =&gt; i if !e.notification.nil? %&gt; &lt;% end %&gt; &lt;% end if !@setting.created_at.nil? %&gt; &lt;% @notifications.each do |n| %&gt; &lt;%= f.fields_for n.email_notifications do |builder| %&gt; &lt;%= render "create_email_notifications", :f =&gt; builder, :notification =&gt; n, :index =&gt; n.id %&gt; &lt;% end %&gt; &lt;% end if @setting.created_at.nil? %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>in <code>app/views/settings/_update_email_notifications.html.erb</code></p> <pre><code>&lt;div class="control-group"&gt; &lt;b&gt;&lt;%= f.label :main, "#{emails.notification.name}", :class =&gt; 'control-label' if !emails.notification.nil? %&gt;&lt;/b&gt; &lt;div class="controls"&gt; &lt;%= puts emails.primary.inspect %&gt; &lt;%= check_box_tag "fields[#{emails.notification.id}][primary]", '1', emails.primary %&gt; Primary Contacts &lt;/br&gt; &lt;%= check_box_tag "fields[#{emails.notification.id}][secondary]", '1', emails.secondary %&gt; Secondary Contacts &lt;% days = [['1 day', 1],['2 days', 2],['3 days', 3],['4 days', 4],['5 days', 5],['6 days', 6],['7 days', 7]]%&gt; &lt;%= collection_select emails, "fields[#{emails.notification.id}][interval]", days, :last, :first if Notification.find(emails.notification_id).required_intervals %&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T17:35:53.900", "Id": "31672", "Score": "2", "body": "just two comments: 1) never, ever, hardcode ids in the code, 2) Move code to the model, these methods have too much code." } ]
[ { "body": "<p>This is just a starting point for you. Move the logic found in the new controller into the settings model. Refactor the constant id into a model constant. Move Notification.all into a before_filter since it is called in every controller action. In the edit, I do not like having the if statement after the block. I think it is less readable.</p>\n\n<p>Model:</p>\n\n<pre><code>class Setting &lt; ActiveRecord::Base\n ADMIN_TRUCK_FLEET_ID = 3\n\n def self.new_with_truck_id(user)\n fleet_id = user.admin? ? ADMIN_TRUCK_FLEET_ID : user.truck_fleet.id\n self.new(truck_fleet_id: fleet_id)\n end\nend\n</code></pre>\n\n<p>Controller (New and Edit):</p>\n\n<pre><code>class SettingsController\n before_filter :get_notifications\n\n def new\n @setting = Setting.new_with_truck_id(current_user)\n\n respond_to do |format|\n format.html\n format.json { render json: @setting }\n end\n end\n\n def edit\n @setting = Setting.find(params[:id])\n if @setting.email_notifications.blank?\n @notifications.each do |n|\n @setting.email_notifications.build(:notification_id =&gt; n.id)\n end\n end\n end\n\n private\n\n def get_notifications\n @notifications = Notification.all\n end\nend\n</code></pre>\n\n<p>Further to do: Move the conditionals in create and update out of the respond_to block. n.id.to_s can be refactored to n.to_param. Think about if more logic can be pushed to the model. Does email notification occur every time a model is saved? Maybe push it to a model callback (after_save) or an observer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T07:33:20.147", "Id": "19837", "ParentId": "19808", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T12:08:50.720", "Id": "19808", "Score": "-1", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Has many through relationship needs code review" }
19808
<p>Yesterday I got a sudden urge to go from writing Python to something, well, more UNIX core-ish. I read some examples on <a href="http://c.learncodethehardway.org/book/" rel="noreferrer">here</a> and decided I might as well put some of that stuff to use to test something else I'm working on: computability theory. Ergo: I wanted to write a basic, one tape, Turing machine simulator.</p> <p>It works, as far as I know. It's not brilliant, and the Turing machine is hard coded in this early version, but it is functional.</p> <p>I'd really like some review on the code. One thing I'm particularly curious about is whether I'm doing appropriate error checking and handling. e.g. are there specific cases where <code>assert</code> is more appropriate or where I should do more error checking?</p> <p><strong>turing.h</strong></p> <pre><code>#ifndef __turing_h__ #define __turing_h__ #define MAX_TRANSITIONS 5 #define MAX_STATES 25 // forward declare structs struct State; struct Transition; typedef enum { LEFT, RIGHT } Direction; typedef enum { FALSE, TRUE } Bool; struct Transition { char input; char write; Direction move; struct State *next; }; typedef struct Transition Transition; struct State { int id; int trans_count; struct Transition* transitions[ MAX_TRANSITIONS ]; Bool accept; Bool reject; }; typedef struct State State; struct Turing { int state_count; State* states[ MAX_STATES ]; State* current; int head; }; typedef struct Turing Turing; #endif </code></pre> <p><strong>turing.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;assert.h&gt; #include &lt;string.h&gt; #include "turing.h" // disable debug mode #define NDEBUG #include "debug.h" // used to hand out ids int state_id = 0; void die( char *message ) { if( message ) { printf( "Error: %s.\n", message ); } // exit unsuccesfully exit(1); } Transition* Transition_create( char input, char write, Direction move, State *next ) { // allocate memory Transition *trans = malloc( sizeof( Transition )); if( ! trans ) die( "Memory error" ); trans-&gt;input = input; trans-&gt;write = write; trans-&gt;move = move; trans-&gt;next = next; return trans; } void Transition_destroy( Transition* trans ) { free( trans ); } State* State_create( Bool accept, Bool reject ) { // allocate mem State *state = malloc( sizeof( State )); if( ! state ) die( "Memory error" ); state-&gt;id = state_id++; state-&gt;accept = accept; state-&gt;reject = reject; state-&gt;trans_count = 0; return state; } void State_add_transition( State *state, Transition *trans ) { // check if we can still add another transition if( state-&gt;trans_count == MAX_TRANSITIONS ) { char buffer[ 50 ]; sprintf( buffer, "State %d already has the maximum amount of transitions.", state-&gt;id ); die( buffer ); } // add the transition state-&gt;transitions[ state-&gt;trans_count ] = trans; state-&gt;trans_count++; } void State_destroy( State *state ) { int i = 0; // loop over its transitions for( i = 0; i &lt; state-&gt;trans_count; i++ ) { Transition *trans = state-&gt;transitions[ i ]; if( !trans ) die( "Could not fetch transition." ); Transition_destroy( trans ); } free( state ); } Turing* Turing_create() { // allocate mem Turing *machine = malloc( sizeof( Turing )); machine-&gt;state_count = 0; machine-&gt;current = NULL; machine-&gt;head = 0; return machine; } void Turing_destroy( Turing *machine ) { int i = 0; // loop over it's states for( i = 0; i &lt; machine-&gt;state_count; i++ ) { State *state = machine-&gt;states[ i ]; if( !state ) die( "Could not fetch turing state" ); State_destroy( state ); } free( machine ); } void Turing_add_state( Turing *machine, State *state ) { if( machine-&gt;state_count == MAX_STATES ) { die( "The turing machine already has the maximum amount of states" ); } // add the state machine-&gt;states[ machine-&gt;state_count++ ] = state; } State* Turing_step( Turing *machine, char* tape, int tape_len ) { int i = 0; char input = tape[ machine-&gt;head ]; State* state = machine-&gt;current; // look for a transition on the given input for( i = 0; i &lt; state-&gt;trans_count; i++ ) { Transition* trans = state-&gt;transitions[ i ]; if( !trans ) die( "Transition retrieval error" ); // check if this is a transition in the given char input if( trans-&gt;input == input ) { debug( "Found transition for input %c", input ); State *next = trans-&gt;next; if( !next ) die( "Transitions to NULL state" ); // write if nescesary if( trans-&gt;write != '\0' ) { debug( "Writing %c", trans-&gt;write ); tape[ machine-&gt;head ] = trans-&gt;write; debug( "Writing done" ); } // move the head if( trans-&gt;move == LEFT ) { if( machine-&gt;head &gt; 0 ) { machine-&gt;head--; debug( "Moved head left" ); } } else { if( machine-&gt;head + 1 &gt;= tape_len ) { die( "Machine walked of tape on right side" ); } machine-&gt;head++; debug( "Moved head right" ); } // move the machine to the next state debug( "Setting current state" ); machine-&gt;current = next; return next; } } char buffer[ 50 ]; sprintf( buffer, "Turing machine blocked: state %d for input %c", state-&gt;id, input ); die( buffer ); } void Turing_run( Turing *machine, char *tape, int tapelen ) { // check if the start state is configured properly if( !machine-&gt;current ) die( "Turing machine has now start state" ); while( TRUE ) { State* state = Turing_step( machine, tape, tapelen ); if( state-&gt;accept ) { printf( "Input accepted in state: %d\n", state-&gt;id ); break; } else if( state-&gt;reject ) { printf( "Input rejected in state: %d\n", state-&gt;id ); break; } else { printf( "Moved to state: %d\n", state-&gt;id ); } } } int main( int argc, char* argv[] ) { Turing* machine = Turing_create(); State* q1 = State_create( FALSE, FALSE ); State* q2 = State_create( FALSE, FALSE ); State* q3 = State_create( FALSE, FALSE ); State* q4 = State_create( FALSE, FALSE ); State* q5 = State_create( FALSE, FALSE ); State* qaccept = State_create( TRUE, FALSE ); State* qreject = State_create( FALSE, TRUE ); Transition* q1_r_space = Transition_create( ' ', '\0', RIGHT, qreject ); Transition* q1_r_x = Transition_create( 'x', '\0', RIGHT, qreject ); Transition* q1_q2_zero = Transition_create( '0', ' ', RIGHT, q2 ); Transition* q2_q2_x = Transition_create( 'x', '\0', RIGHT, q2 ); Transition* q2_a_space = Transition_create( ' ', '\0', RIGHT, qaccept ); Transition* q2_q3_zero = Transition_create( '0', 'x', RIGHT, q3 ); Transition* q3_q3_x = Transition_create( 'x', '\0', RIGHT, q3 ); Transition* q3_q4_zero = Transition_create( '0', '\0', RIGHT, q4 ); Transition* q3_q5_space = Transition_create( ' ', '\0', LEFT, q5 ); Transition* q4_q3_zero = Transition_create( '0', 'x', RIGHT, q3 ); Transition* q4_q4_x = Transition_create( 'x', '\0', RIGHT, q4 ); Transition* q4_r_space = Transition_create( ' ', '\0', RIGHT, qreject ); Transition* q5_q5_zero = Transition_create( '0', '\0', LEFT, q5 ); Transition* q5_q5_x = Transition_create( 'x', '\0', LEFT, q5 ); Transition* q5_q2_space = Transition_create( ' ', '\0', RIGHT, q2 ); State_add_transition( q1, q1_r_space ); State_add_transition( q1, q1_r_x ); State_add_transition( q1, q1_q2_zero ); State_add_transition( q2, q2_q2_x ); State_add_transition( q2, q2_a_space ); State_add_transition( q2, q2_q3_zero ); State_add_transition( q3, q3_q3_x ); State_add_transition( q3, q3_q4_zero ); State_add_transition( q3, q3_q5_space ); State_add_transition( q4, q4_q3_zero ); State_add_transition( q4, q4_q4_x ); State_add_transition( q4, q4_r_space ); State_add_transition( q5, q5_q5_zero ); State_add_transition( q5, q5_q5_x ); State_add_transition( q5, q5_q2_space ); Turing_add_state( machine, q1 ); Turing_add_state( machine, q2 ); Turing_add_state( machine, q3 ); Turing_add_state( machine, q4 ); Turing_add_state( machine, q5 ); Turing_add_state( machine, qaccept ); Turing_add_state( machine, qreject ); machine-&gt;current = q1; char* input = "0000000000000000 "; int len = strlen( input ); char* tape = malloc( len * sizeof( char )); strcpy( tape, input ); Turing_run( machine, tape, len ); // clean up Turing_destroy( machine ); free( tape ); } </code></pre> <p><strong>debug.h</strong></p> <pre><code>#ifndef __debug_h__ #define __debug_h__ #ifndef NDEBUG #define debug(M, ... ) fprintf( stderr, "DEBUG: %s:%d: " M "\n", __FILE__, __LINE__, ##__VA_ARGS__ ) #else #define debug(M, ... ) #endif #endif </code></pre> <p>For now the simulator is configured to accept on input strings from the language:</p> <blockquote> <pre><code>L = { 0^2^n | n &gt; 0 } </code></pre> </blockquote> <p>Or: all strings of 0s whose length is a power of 2.</p> <p>If you happen to have Sipser <em>Introduction to the Theory of Computation</em>. It's on page 145 of the 2<sup>nd</sup> edition.</p> <hr> <p><a href="https://github.com/ElessarWebb/turing.git" rel="noreferrer">GIT repo up</a> and documentation on the way (we have a <a href="https://github.com/ElessarWebb/turing/wiki" rel="noreferrer">tiny wiki</a> with basic usage)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T07:57:56.230", "Id": "31704", "Score": "0", "body": "You might find this page interesting: http://codegolf.stackexchange.com/questions/8787/turing-machine-simulator/8795#2381" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-29T22:08:47.103", "Id": "97620", "Score": "0", "body": "If you would like a review on the revised code, please [ask another question](http://meta.codereview.stackexchange.com/q/1763/9357)." } ]
[ { "body": "<p>Identifiers with two underscores are reserved for the implementation (so don't use them).\nAlso MACROS (things defined by #define) are traditionally all uppercase (because they do not obey scope rules (because they are not part of the C language but part of the pre-processor system) we make them all uppercase to make sure that we don't accidentally clash with other identifiers).</p>\n\n<pre><code>#ifndef __turing_h__\n#define __turing_h__\n</code></pre>\n\n<p>If you are going to forward declare these then also do the appropriate typedefs.</p>\n\n<pre><code>struct State;\nstruct Transition; \n\n// Add\ntypedef struct State State;\ntypedef struct Transition Transition;\n</code></pre>\n\n<p>Now you will be able to refer to then without using the prefix struct.</p>\n\n<p>Don't use all caps. A macro (with no scope boundary may play havake with these identifiers).</p>\n\n<pre><code>typedef enum {\n LEFT, RIGHT\n} Direction;\n</code></pre>\n\n<p>The system header files aready define FALSE/TRUE. Also in this situation you define TRUE as 1. This is not correct. The only thing you can say about <code>TRUE</code> is <code>(!FALSE)</code>. Which is not necessarily the same as 1.</p>\n\n<pre><code>typedef enum {\n FALSE, TRUE\n} Bool;\n</code></pre>\n\n<p>Nothing wrong with this.\nBut if you lay out your type with the chars first then you may not get the best packing arrangement. Always order them from largest to smallest (if you care about layout (usually it is not a big thing but if you have large space requirements and can become an issue)).</p>\n\n<pre><code>struct Transition {\n char input;\n char write;\n Direction move;\n State *next;\n};\n</code></pre>\n\n<p>So I would have layed it out like this:</p>\n\n<pre><code>typedef struct Transition {\n State *next; // At least as big as an int (but can be bigger).\n Direction move; // Enum is an int.\n char input; // Now chars.\n char write;\n} Transition;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T07:25:01.400", "Id": "31700", "Score": "0", "body": "\"Don't use all caps.\" Actually, all caps is a very common way to declare constants, enums and all manner of global identifiers, not just macros." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T07:27:46.633", "Id": "31701", "Score": "0", "body": "\"...you define TRUE as 1. This is not correct.\" Yes it is perfectly correct. Always make the code compatible with the C standard bool type, which is explicitly guaranteed to be 1 and not some magical \"not 0 maybe 1\". The best is of course to use the standard bool type from stdbool.h." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T10:29:29.593", "Id": "31707", "Score": "0", "body": "Ah `stdbool.h`. Another useful note!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T18:15:04.480", "Id": "19820", "ParentId": "19814", "Score": "7" } }, { "body": "<p>AJ, I like it. Very nicely coded.</p>\n\n<p>Here are some comments. I've omitted things already mentioned by @LokiAstari</p>\n\n<ul>\n<li><p>forward declaration of <code>struct Transition</code> is unnecessary.</p></li>\n<li><p><code>die</code>, prefer to print errors to <code>stderr</code> </p></li>\n<li><p><code>exit(1)</code> prefer <code>exit(EXIT_FAILURE)</code></p></li>\n<li><p>some noisey comments (\"exit unsucessfully\", \"allocate memory\" etc)</p></li>\n<li><p><code>State_create</code> does not initialise <code>transitions</code> (probably benign)</p></li>\n<li><p><code>sprintf</code> is often used badly, resulting in buffer overflows. <code>snprintf</code> is\npreferred. But as you use it only before dying, no risk.</p></li>\n<li><p><code>Turing_create</code> does not check <code>malloc</code> (other uses do).</p></li>\n<li><p>do you prefer <code>type* var</code> or <code>type *var</code>? I prefer the latter, but\nwhichever you use, consistency is best.</p></li>\n<li><p>don't you get a warning (control may reach end of non-void function, or\nsimilar) from <code>Turing_step</code>?</p></li>\n<li><p>in some places you can define loop variables in the loop: <code>for( int i = 0; ...</code></p></li>\n<li><p>make local functions static. This is good practice but for a small project\nlike this makes no difference.</p></li>\n<li><p>your list of Transition_create calls in <code>main</code> would be more readable if aligned.</p></li>\n<li><p>your <code>main</code> has some issues in the copying of <code>input</code>.</p>\n\n<ul>\n<li><code>strlen</code> returns <code>size_t</code> and <code>malloc</code> takes <code>size_t</code>. So best to use\n<code>size_t</code> (-Wsign-conversion)</li>\n<li>sizeof(char) is 1 by definition</li>\n<li>you malloced one too few bytes for the string copy.</li>\n<li>you could have used <code>strdup</code> if you have it.</li>\n<li>but note that mallocing a copy of <code>input</code> is not necessary. You can just declare the string as <code>char input[] = \"...\"</code> instead of <code>char* input = \"...\"</code> and it will be writable.</li>\n<li>if you use <code>char input[]</code> you need not do <code>strlen(input)</code> - just <code>sizeof input -1</code></li>\n</ul></li>\n<li><p>passing the length of the input string around seems unnecessary (users of\nthe string can check for the terminating '\\0')</p></li>\n</ul>\n\n<p>On error checking and use of <code>assert</code>, I think you have done a good job of\nchecking. I'm not a big user of asserts (so maybe my thoughts on them are not\nof much use to you). I'm always uneasy using an assert - they are funny\nthings. They say, in effect, that the tested condition is so important that it\nis worth exiting if it occurs during testing, <strong>but</strong> that if it occurs during\nnormal use (NDEBUG) it can be ignored. That is illogical unless you can be\nsure that all possible assert failures can be detected during testing. To me\nthat implies that asserts should be used only to test for errors that are\nintrinsic to the program and have no dependence upon the data or the runtime.\nFor example checking whether <code>malloc</code> failed would use an <code>if</code> condition\nwhereas checking for something that can only happen if an algorithm is wrongly\ncoded is a fair use of <code>assert</code>. In your case, I might be tempted to use\n<code>assert</code> where you check array entries are not NULL:</p>\n\n<pre><code> Transition *trans = state-&gt;transitions[ i ];\n assert( trans );\n</code></pre>\n\n<p>But I've seen asserts sprinkled around like confettii, so opinions clearly\ndiffer. Maybe other reviewers will be able to help.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T10:26:22.317", "Id": "31705", "Score": "0", "body": "Thank you. Some of these I already incorporated. Some of them I'll research a bit. I agree with you on the assert/if dilemma. I see alot of code (in other languages) that seem to forget that asserts are usually not for runtime checking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T10:28:44.833", "Id": "31706", "Score": "0", "body": "About passing around the string length: I'm getting the impressions there are several opinions on the matter. You either have to make SURE all strings are \\0 terminated and rely on C string tools and/or build in extra checks to prevent overflows. You clearly vote for the former. Anyone else?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T12:43:22.260", "Id": "31713", "Score": "0", "body": "AJ, strings should always be terminated with \\0 but arrays in general are not. But strings are arrays - maybe that is where the confusion arrises... Note that I corrected a piece of badly wrong advice above (using sizeof on a pointer!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T13:12:16.770", "Id": "31714", "Score": "0", "body": "No, there is no confusion. I'm just deliberating whether I should TRUST the strings in my program to be properly terminated. Should I?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T13:26:14.160", "Id": "31715", "Score": "0", "body": "Yes, if it is created by the compiler (from your quoted string, as in \"01234..\") it will definitely be terminated. If created by someone using strcpy (as in your original code) then it depends upon the code. But if the \\0 is missing, using strlen to find out how long it is will also fail, as strlen won't find the \\0 it needs. So in practice you have to assume it is correctly terminated." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T03:18:30.297", "Id": "19834", "ParentId": "19814", "Score": "12" } }, { "body": "<p>I just have one small note in addition to the other answers.</p>\n\n<p>Your <code>#include</code>s should be organized differently:</p>\n\n<blockquote>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;assert.h&gt;\n#include &lt;string.h&gt;\n#include \"turing.h\"\n</code></pre>\n</blockquote>\n\n<p>It's best to include your own headers first, in order to avoid any possible dependency issues with the system libraries. In other words, you shouldn't force your headers to be exposed to other libraries, especially if that is not intended to happen.</p>\n\n<p>In addition, you can sort your headers in a certain order, such as alphabetically. This will make it easier to keep track of them.</p>\n\n<pre><code>#include \"turing.h\"\n#include &lt;assert.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-29T17:01:21.973", "Id": "55617", "ParentId": "19814", "Score": "5" } }, { "body": "<p>as the malloc() return <code>void *</code> \nyou must correct all the memory allocation statements</p>\n\n<p><code>Turing *machine = malloc( sizeof( Turing ));</code></p>\n\n<p>---> <code>Turing *machine = (Turing*) malloc( sizeof( Turing ));</code></p>\n\n<p>and so on </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-21T10:36:21.610", "Id": "289632", "Score": "2", "body": "No, don't do that. http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-21T10:32:54.150", "Id": "153226", "ParentId": "19814", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T15:39:58.350", "Id": "19814", "Score": "24", "Tags": [ "c", "beginner", "error-handling", "simulation", "state-machine" ], "Title": "Simple Turing machine simulator" }
19814
<p>Is there better way to read from a file and connect all data in one big data than to use generators?</p> <p>At the moment, I do the following:</p> <ol> <li>use generators to read data from files.</li> <li>use NumPy to pack all files in 3D array.</li> <li>use pandas to stack it to 2D array so readable for next operations (e.g. plotting).</li> </ol> <h3>In my example:</h3> <p>I split reading from file operations generators in 2 modules, and have a third module for reading names (file is not connected with others generators_module). In the last separate file I import that generators_modules, and make arrays with NumPy, then pandas.</p> <p>In the code of modules I use <code>os.walk</code> to read from files, regex to read only that data which is needed. </p> <p>In the code of making arrays with NumPy, pandas: </p> <ul> <li>I enter variable parameters needed to get data with generator_modules</li> <li><p>I pass from generators to array with code:</p> <pre><code>xdata=np.array( [(float(line['PRESSURE']), float(line['CURVE'])) for line in dt_cols] ) </code></pre></li> </ul> <p>I have four python files, as below:</p> <h3>module1 (<code>gen_enter</code>):</h3> <pre><code>import re, matplotlib as mpl, matplotlib.pyplot as plt, os, fnmatch def gen_find(filepat,top): for path, dirlist, filelist in os.walk(top): for name in fnmatch.filter(filelist,filepat): yield os.path.join(path,name) def gen_open(filenames): for name in filenames: if name.endswith(".XL"): yield open(name) else: pass def gen_get(sources): for s in sources: for item in s: yield item def gen_grep(pattern, fileparse): for line in fileparse: inputlines = line[:].strip().replace(';',' ') if pattern.search(inputlines): yield inputlines else: pass def field_map(dictseq,name,func): for d in dictseq: d[name] = func(d[name]) yield d </code></pre> <h3>module2 (<code>gen_returnlines</code>):</h3> <pre><code>from gen_enter import * def lines_from_dir(filepat, dirname): findnames = gen_find(filepat, dirname) openfiles = gen_open(findnames) getlines = gen_get(openfiles) #patlines = gen_grep(pattern, getlines) return getlines </code></pre> <h3>module3 (<code>gen_shownames</code>):</h3> <pre><code>import re, matplotlib as mpl, matplotlib.pyplot as plt, os, fnmatch def gen_shownames(filepat,top): for path, dirlist, filelist in os.walk(top): for name in fnmatch.filter(filelist,filepat): yield name </code></pre> <h3>The main code:</h3> <pre><code>import numpy as np, pandas as pd, os, fnmatch, re from pylab import * from gen_returnlines import * from gen_shownames import * def dict_cols(lines): groups = (patlines.match(line) for line in getlines) tuples = (group.groups() for group in groups if group) colnames = ('PRESSURE','CURVE') line = (dict(zip(colnames,t)) for t in tuples) line = (field_map(line,"PRESSURE", lambda s: float(s))) line = (field_map(line,"CURVE",float)) return line dir='C:\\Users\\REDHOOD\\workspace\\Politechnika_python\\\silniki\\files' #note: all files from ../files/ pattern = re.compile(r'(\d{3}\.\d{1})\D*(\d{3}\.\d{1})\D*') pats = '(\d{3}\.\d{1})\D*(\d{3}\.\d{1})\D*' patlines = re.compile(pats) if __name__ == '__main__': names = gen_shownames('*', dir) getlines = lines_from_dir('*',dir) dt_cols = dict_cols(getlines) xdata = np.array( [(float(line['PRESSURE']), float(line['CURVE'])) for line in dt_cols] ) xrdata = np.reshape(xdata,(17,360,2)) datapanel = pd.Panel( xrdata, items=[k for k in names], ) datapaneldf = datapanel.to_frame() #pressure na curve -&gt; 360 stopni </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T15:06:38.810", "Id": "31670", "Score": "1", "body": "This all looks pretty good to me. Do you have a specific concern, or are you merely looking for review?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T15:26:57.190", "Id": "31671", "Score": "0", "body": "You should be able to use `read_csv` which will probably be faster (especially in pandas 0.10)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T15:12:11.857", "Id": "31721", "Score": "0", "body": "read_csv --- its for reading csv_files, right? so i should first rewrite file to csv format, if its in txt format files?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T13:04:59.883", "Id": "32421", "Score": "0", "body": "is it possible to write code, what will automaticly choose the dimensions of array, by the number of catalogues, files, lines, columns and rows?" } ]
[ { "body": "<blockquote>\n <p>Is there better way to read from a file and connect all data in one big data than to use generators?</p>\n</blockquote>\n\n<p>Whenever possible, using generators is better than collecting data in one big object.\nOne big object needs a lot of memory at once,\nusing a generator you can use a pipeline where only the data necessary for the current processing is in memory, and discarded when completed.</p>\n\n<p>I didn't look hard enough in your program if your operation can be fully streamlined.\nWhat I can see is that in the <code>dict_cols</code> method you effectively <em>collect</em> from all the generators:</p>\n\n<blockquote>\n<pre><code>def dict_cols(lines):\n groups = (patlines.match(line) for line in getlines)\n tuples = (group.groups() for group in groups if group)\n</code></pre>\n</blockquote>\n\n<p>Here, <code>getlines</code> and <code>group</code> are generators,\nbut you fully consume them.\nAt this point, it doesn't matter anymore if <code>getlines</code> and <code>group</code> were generators or lists, because everything will be loaded in memory anyway.\nI don't know if it's possible to change your processing to avoid fully consuming the generators at this point or later.\nIt would be great if you could.\nBut even if you cannot,\nit's still good that <code>getlines</code> and <code>group</code> are generators instead of lists,\nbecause maybe in the future you will find a better way to process the data in a more streamlined way without collecting.</p>\n\n<h3>Using <code>__name__</code> properly</h3>\n\n<p>The purpose of the <code>if __name__ == '__main__': ...</code> check is to make it possible to load a package without executing code. However, you have this:</p>\n\n<blockquote>\n<pre><code>if __name__ == '__main__':\n names = gen_shownames('*', dir)\n getlines = lines_from_dir('*',dir)\n dt_cols = dict_cols(getlines)\n\nxdata = np.array( [(float(line['PRESSURE']), float(line['CURVE'])) for line in dt_cols] )\nxrdata = np.reshape(xdata,(17,360,2))\n</code></pre>\n</blockquote>\n\n<p>This defeats the purpose. It would be better to move everything you do inside the <code>if</code> statement and afterward inside a <code>main</code> method, and call that from the <code>if</code> statement, like this:</p>\n\n<pre><code>def main():\n names = gen_shownames('*', dir)\n getlines = lines_from_dir('*',dir)\n dt_cols = dict_cols(getlines)\n\n xdata = np.array( [(float(line['PRESSURE']), float(line['CURVE'])) for line in dt_cols] )\n xrdata = np.reshape(xdata,(17,360,2))\n\n # ... and so on\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<h3>Coding style</h3>\n\n<p>It seems you're not following <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>,\nthe official style guide of Python.\nI suggest to give it a good read and follow it.</p>\n\n<p>There shouldn't be multiple statements on one line:</p>\n\n<blockquote>\n<pre><code> for name in fnmatch.filter(filelist,filepat): yield os.path.join(path,name)\n</code></pre>\n</blockquote>\n\n<p>Break the line after <code>:</code></p>\n\n<pre><code> for name in fnmatch.filter(filelist,filepat):\n yield os.path.join(path,name)\n</code></pre>\n\n<p>Do the same in other places too, always break the line after a <code>:</code>.</p>\n\n<hr>\n\n<p>The <code>else</code> is pointless here and should be removed:</p>\n\n<blockquote>\n<pre><code>def gen_open(filenames):\n for name in filenames:\n if name.endswith(\".XL\"): yield open(name)\n else: pass\n</code></pre>\n</blockquote>\n\n<p>I see the same in other methods too, fix it everywhere.</p>\n\n<hr>\n\n<p>Put a space after method parameters, so instead of:</p>\n\n<blockquote>\n<pre><code>def field_map(dictseq,name,func):\n for d in dictseq:\n</code></pre>\n</blockquote>\n\n<p>Write like this:</p>\n\n<pre><code>def field_map(dictseq, name, func):\n for d in dictseq:\n</code></pre>\n\n<hr>\n\n<p>Avoid wildcard imports like this:</p>\n\n<blockquote>\n<pre><code>from gen_enter import *\n</code></pre>\n</blockquote>\n\n<p>This practice limits the ability of IDEs and static analysis tools to check for invalid references.</p>\n\n<hr>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>dir='C:\\\\Users\\\\REDHOOD'\n</code></pre>\n</blockquote>\n\n<p>You can write simpler this way:</p>\n\n<pre><code>dir='C:/Users/REDHOOD'\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-20T10:40:29.650", "Id": "74260", "ParentId": "19817", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T14:59:23.490", "Id": "19817", "Score": "2", "Tags": [ "python", "numpy", "generator", "matplotlib" ], "Title": "Reading from a file and connect all data in one big data than to use generators" }
19817
<p>Looking for general feedback on this module. <code>remember</code> is property that a user sets via clicking "remember me" when logging in.</p> <p>A token identifies the user - h_token. If <code>localStorage.h_token</code> is set, it is assumed the user has clicked remember me, this is checked at load time.</p> <p>When the remember state is changed manually by the user <code>setRemember()</code> is called.</p> <p>Not looking for advice on any security issues or naming conventions at the moment it is not a concern.</p> <p>Just general things.</p> <pre><code>/*SClientStorage ** ** ** */ SStorage = NS.support({ Name: 'Storage', hold: {}, clientStorage: localStorage.h_token ? localStorage : sessionStorage, setRemember: function (remember) { this.clientStorage = remember ? localStorage : sessionStorage }, clear: function () { this.clientStorage.clear(); }, setAll: function (o) { var key; for (key in o) { if (o.hasOwnProperty(key)) { this.clientStorage[key] = o[key]; } } }, getAll: function () { var o = {}, key; for (key in this.clientStorage) { if (this.clientStorage.hasOwnProperty(key)) { o[key] = this.clientStorage[key]; } } return o; }, set: function (key, value) { this.clientStorage[key] = value; }, get: function (key) { return this.clientStorage[key]; } }); </code></pre>
[]
[ { "body": "<p>Looks really good. It's clear and easy to understand. Regarding this specific implementation, a couple of things that came to mind:</p>\n\n<ul>\n<li><p>In <code>setRemember()</code>, unless you specifically only want to support the values <code>1</code> or <code>0</code>, the code can be changed to:</p>\n\n<ul>\n<li><code>this.clientStorage = remember ? this.localStorage : this.sessionStorage;</code></li>\n</ul></li>\n<li><p>In <code>setRemember()</code>, when switching storage mechanisms it might make sense to copy the values out of the old mechanism into the new one so anything the user has previously set will be preserved. Similary, if the user is changing from <code>localStorage</code> to <code>sessionSorage</code>, would it make sense to also <em>clear</em> the old storage mechanism? If making either of these changes, the method could also first compare the new value against the old value and only continue if there is actually a change.</p></li>\n<li><p>What is <code>o</code> used for in <code>log()</code> method? </p></li>\n<li><p>In the <code>log()</code> method, depending on on the utility you're using for logging, you might consider logging the entire object, at once, as many console / logging utilities will allow you to inspect objects. This can sometimes be more informative, although here it's just about whatever would be more convenient because all values will be strings, anyway. If you go this route, you could rename the current function to something like <code>logEach()</code>. </p></li>\n<li><p>In the execution of <code>clear()</code>, should you preseve the <code>h_token</code> key?</p></li>\n</ul>\n\n<p>Taking a step back, here is an alternate API for the utilitiy. Just thinking out loud. </p>\n\n<ul>\n<li><code>ssn(key)</code> - Retrieves a value. Synonymous with <code>get()</code></li>\n<li><code>ssn(key, value)</code> - Sets a value. Synonymous with <code>set()</code></li>\n<li><code>ssn(obj)</code> - Set all values from obj. Synonymous with <code>setAll()</code></li>\n<li><code>ssn.clear()</code> - Unchanged.</li>\n<li><code>ssn.clone()</code> - Synonymous with <code>getAll()</code></li>\n<li><code>ssn.log()</code> - Log the <code>clientStorage</code> object as a whole, as described above.</li>\n<li><code>ssn.logEach()</code> - Log each property and corresponding value, one at a time.</li>\n<li><code>ssn.remember()</code> - Retrieves the current <code>remember</code> setting.</li>\n<li><code>ssn.remember(value)</code> - Sets the <code>remember</code> value. Synonymous with <code>setRemember()</code></li>\n</ul>\n\n<p>One final thought you may want to implement some sort of 'namespace' type of functionality to be able to differentiate between settings saved for different users. I don't suggest this for security reasons, but more from a user-experience perspective. I think, with the way it's set up, multiple users on the same computer will have their settings merged, which may get confusing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-06T11:39:02.990", "Id": "32301", "Score": "0", "body": "Session. Although, in a non-technical context I think it can also refer to a social security number." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T21:07:51.423", "Id": "41852", "Score": "0", "body": "I only allow the user to change remember me at login so there is no need to save the previous. Similarly I only use clear() when logging the user out, so I don't need to preserve anything." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T00:28:57.173", "Id": "19935", "ParentId": "19825", "Score": "2" } }, { "body": "<p>replace </p>\n\n<pre><code>if(remember === '1') {\n this.clientStorage = localStorage;\n} else if(remember === '0') {\n this.clientStorage = sessionStorage;\n}\n</code></pre>\n\n<p>with</p>\n\n<pre><code>this.clientStorage = [localStorage, sessionStorage][parseInt(remember)]\n</code></pre>\n\n<p>note: tiffon's </p>\n\n<pre><code>this.clientStorage = remember ? this.localStorage : this.sessionStorage\n</code></pre>\n\n<p>works very well, is nice and concise, and there is no confusion what is going on. However, if you have to add another option, e.g., '2', '3', '4' then my code suits better.</p>\n\n<p>replace </p>\n\n<pre><code>var key;\nfor (key in o) {\n</code></pre>\n\n<p>with</p>\n\n<pre><code>for (var key in o) {\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-04T10:49:41.907", "Id": "32193", "Score": "0", "body": "odd. works in chrome. As this is not universally accepted by all JS then lets not do this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T12:42:22.703", "Id": "20120", "ParentId": "19825", "Score": "1" } } ]
{ "AcceptedAnswerId": "19935", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T20:47:18.150", "Id": "19825", "Score": "1", "Tags": [ "javascript" ], "Title": "SStorage (remember) - v0" }
19825
<p>Is this the right way to do a singleton in Objective-C (coming from an Android background, with a little understanding of threading)?</p> <pre><code>#import "ItemsManager.h" #define kNumMaxSelectableItems 15 @implementation ItemsManager{ NSMutableArray *currentItems; } static ItemsManager *myself; -(id)init{ if(self=[super init]){ currentItems = [[NSMutableArray alloc] initWithCapacity:kNumMaxSelectableItems]; myself = self; } return self; } +(ItemsManager *)getInstance{ if(!myself){ myself = [[ItemsManager alloc] init]; } return myself; } -(void) doSomething{ NSLog(@"hi"); } -(void)dealloc{ [currentItems release]; currentItems = nil; myself = nil; [super dealloc]; } @end </code></pre> <p>And with this design, I suppose I would call it like:</p> <pre><code>void main(){ [[ItemsManager getInstance] doSomething]; } </code></pre>
[]
[ { "body": "<p>This is the the way singletons are usually implemented in apple's code samples.</p>\n\n<pre><code>+ (ItemsManager *)sharedInstance\n{\n static ItemsManager *sharedInstance = nil;\n static dispatch_once_t once;\n\n /* Doing the allocation inside dispatch_once queue ensures the code\n will run only once for the lifetime of the app. */\n\n dispatch_once(&amp;once, ^{\n sharedInstance = [[ItemsManager alloc] init];\n });\n\n return sharedInstance;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-05T22:25:20.383", "Id": "32279", "Score": "1", "body": "I also would like to add a link to a Luke Redpath's post with a good explanation regarding using of this method: http://lukeredpath.co.uk/blog/a-note-on-objective-c-singletons.html" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T00:31:45.823", "Id": "19830", "ParentId": "19829", "Score": "9" } }, { "body": "<blockquote>\n <p>how do i hide the init method so that no one else can alloc/init my class without using \"getInstance\"?</p>\n</blockquote>\n\n<p>there is not a widely accepted pattern how to do so.<br>\nIn fact many (not only Objective-C) developer would argue today, that a <em>classical</em> strict Singleton is not needed and even harmful [<a href=\"http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/\" rel=\"nofollow\">1</a>], [<a href=\"http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx\" rel=\"nofollow\">2</a>], [<a href=\"https://sites.google.com/site/steveyegge2/singleton-considered-stupid\" rel=\"nofollow\">3</a>] — first of all Singletons make code hard to test, as the introduce global states and unit tests might yield different results if their order is changed. </p>\n\n<p>Also Apple changed many real singleton in older Cocoa-Implementations to the softer shared instance pattern, in which actually many objects can be instantiated, but the class offers one shared one — and this is what dallen posted. </p>\n\n<p><strong>conclusion</strong><br>\nDon't waste your time to try to make a bullet-proof singleton. It just don't worth the hassle. Use the approach dallen showed you and when it comes to unit testing be happy, that you can instantiate new objects.</p>\n\n<hr>\n\n<p>that said: in the book <a href=\"http://books.google.de/books?id=rLZcD4hkDy4C&amp;lpg=PA103&amp;ots=lDQFYWnLYk&amp;dq=nsallocateobject%20singleton&amp;pg=PA97#v=onepage&amp;q&amp;f=false\" rel=\"nofollow\">\"Objective-C Design Patterns for iOS\", chapter 7</a>, Carlo Chung shows an implementation of an Singleton, that is even sub-classable. But also in that chapter Chung points out the problems about singleton and advises to use the shared instance concept. <em>Beware</em>: that code predates ARC.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T21:39:14.987", "Id": "41202", "Score": "1", "body": "Note though, that it's not necessary to add a public `init` to production code, just to allow it to be used for unit test." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T01:51:21.240", "Id": "19833", "ParentId": "19829", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T00:18:31.553", "Id": "19829", "Score": "2", "Tags": [ "objective-c", "singleton" ], "Title": "Objective-C singleton implementation" }
19829
<p>I am utilizing CodeIgniter's Pagination class to implement pagination in the project.</p> <p>In this project, there are 3 modules: Event, Business and Parts. Each Module has the same "view" for pagination. I have written pagination code for the event module, which has 3 types of pagination depending on the condition (received from end user).</p> <p><img src="https://i.stack.imgur.com/twM3e.png" alt="enter image description here"></p> <p>Following is the code for the event module:</p> <p>The controller:</p> <pre><code>class Event extends CI_Controller{ public function event_list($sort_by = 'Description', $sort_order = 'asc', $limit = 3,$offset = 0,$search = false,$category = false){ $config = array(); if($category){ $third_term = $this-&gt;uri-&gt;segment(3); if(is_numeric($sort_by)){ if(is_numeric($third_term)){ $sort_by = 'Description'; }else{ $sort_by = 'Price'; } } $config['base_url'] = site_url("event/categories/$sort_by/$sort_order/$limit"); } elseif($search || $_POST){ if($_POST){ $search_data = array( 'search_term' =&gt; '', 'search_category' =&gt; '', ); $this-&gt;session-&gt;unset_userdata($search_data); $search_term = $this-&gt;input-&gt;post('search',TRUE); $search_category = $this-&gt;input-&gt;post('select-search',TRUE); $this-&gt;session-&gt;set_flashdata('search_term',$search_term); $this-&gt;session-&gt;set_flashdata('search_category',$this-&gt;input-&gt;post('select-search',TRUE)); $config['base_url'] = site_url("event/search_list/$sort_by/$sort_order/$limit"); } else{ $this-&gt;session-&gt;keep_flashdata('search_term'); $this-&gt;session-&gt;keep_flashdata('search_category'); $search_term = $this-&gt;session-&gt;flashdata('search_term'); $search_category = $this-&gt;session-&gt;flashdata('search_category'); $config['base_url'] = site_url("event/search_list/$sort_by/$sort_order/$limit"); } }else{ $config['base_url'] = site_url("event/event_list/$sort_by/$sort_order/$limit"); } $data['fields'] = array( 'Description' =&gt; 'Description', 'Price' =&gt; 'Price' ); $config['per_page'] = $limit; $this-&gt;load-&gt;model('event_model'); $results = $this-&gt;event_model-&gt;search($limit, $offset, $sort_by, $sort_order,$search,$category); $data['num_results'] = $results['num_rows']; $data['events'] = $results['rows']; $this-&gt;load-&gt;library('pagination'); $config['total_rows'] = $data['num_results']; $config['uri_segment'] = 6; $this-&gt;config-&gt;load('pagination'); //$this-&gt;pagination-&gt;initialize($config); $data['pagination'] = $this-&gt;pagination-&gt;create_links(); $data['sort_by'] = $sort_by; $data['sort_order'] = $sort_order; $data['page_no'] = ceil($this-&gt;uri-&gt;segment(6)/ $limit) + 1; $total_pages = ceil($config['total_rows'] / $limit); if($total_pages &gt; 1){ $data['total_pages'] = $total_pages; } $config['use_page_numbers'] = TRUE; $data['limit'] = $limit;//echo '&lt;pre/&gt;'.print_r($config);exit(); $this-&gt;load-&gt;view('templates/event/event-list',$data); } public function search_list($sort_by = 'Description', $sort_order = 'asc', $limit = 3,$offset = 0,$search = true,$category = false){ $this-&gt;event_list($sort_by,$sort_order,$limit,$offset,$search); } public function categories($sort_by = 'Description', $sort_order = 'asc', $limit = 3,$offset = 0,$search = false,$category = true){ $search_category = $this-&gt;uri-&gt;segment(3); $in_flash = $this-&gt;session-&gt;flashdata('search_category'); if(($in_flash == $search_category) &amp;&amp; (!is_numeric($search_category))){ $this-&gt;session-&gt;keep_flashdata('search_category'); }else{ $search_data = array( 'search_term' =&gt; '', 'search_category' =&gt; '', ); $this-&gt;session-&gt;unset_userdata($search_data); $this-&gt;session-&gt;set_flashdata('search_category',$search_category); } $this-&gt;event_list($sort_by,$sort_order,$limit,$offset,$search=false,$category = true); } } </code></pre> <p>The Model:</p> <pre><code>class event_model extends CI_Model{ function search($limit, $offset, $sort_by, $sort_order,$search,$category) { $sort_order = ($sort_order == 'desc') ? 'desc' : 'asc'; $sort_columns = array('Description', 'Price'); $sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'Description'; if($search){ $search_term = "'%".$this-&gt;input-&gt;post('search',TRUE)."%'"; $search_category = $this-&gt;input-&gt;post('select-search',TRUE); $query = sprintf('SELECT *,a.id AS eid,(SELECT Url from oc_storage where Object_Id = a.id and Object = "event" and type= "thumb.normal" limit 0,1 ) as thumb FROM oc_event a,oc_event_type b,oc_address c WHERE b.id = %s AND a.Event_Type = b.id AND c.Object_type = "event" AND c.Object_Id = a.id AND a.Description like "%s" ORDER BY a.%s %s LIMIT %s ,%s',$search_category,$search_term,$sort_by, $sort_order,$offset,$limit); $count = "Select Count(*)FROM oc_event a,oc_event_type b,oc_address c WHERE a.Event_Type = b.id AND c.Object_type = 'event' AND c.Object_Id = a.id AND a.Description like $search_term"; } if($category){ $search_category = $this-&gt;session-&gt;flashdata('search_category'); $query = sprintf('SELECT *,a.id AS eid,(SELECT Url from oc_storage where Object_Id = a.id and Object = "event" and type= "thumb.normal" limit 0,1 ) as thumb FROM oc_event a,oc_event_type b,oc_address c WHERE b.id = %s AND c.Object_type = "event" AND c.Object_Id = a.id ORDER BY a.%s %s LIMIT %s ,%s',$search_category,$sort_by, $sort_order,$offset,$limit); $count = "Select Count(*)FROM oc_event a,oc_event_type b,oc_address c WHERE a.Event_Type = $search_category AND c.Object_type = 'event' AND c.Object_Id = a.id"; } else{ $query = sprintf('SELECT *,a.id AS eid,(SELECT Url from oc_storage where Object_Id = a.id and Object = "event" and type= "thumb.normal" limit 0,1 ) as thumb FROM oc_event a,oc_event_type b,oc_address c WHERE a.Event_Type = b.id AND c.Object_type = "event" AND c.Object_Id = a.id ORDER BY a.%s %s LIMIT %s ,%s',$sort_by, $sort_order,$offset,$limit); $count = "Select Count(*)FROM oc_event a,oc_event_type b,oc_address c WHERE a.Event_Type = b.id AND c.Object_type = 'event' AND c.Object_Id = a.id "; } $stmt = $this-&gt;db-&gt;conn_id-&gt;prepare($query); $stmt-&gt;execute(); $ret['rows'] = $stmt-&gt;fetchAll( PDO::FETCH_ASSOC ) ; $ret['num_rows'] = $this-&gt;db-&gt;conn_id-&gt;query($count)-&gt;fetchColumn(); return $ret; } </code></pre> <p>The view : "Including only whats required";</p> <pre><code> &lt;div class="sorting"&gt; &lt;?php foreach($fields as $field_name =&gt; $field_display): ?&gt; &lt;?php if (($sort_by == $field_name)){ (($sort_order == 'asc' &amp;&amp; $sort_by == $field_name) ? 'desc' : 'asc') ?&gt; &lt;a href="&lt;?php $call_by = $this-&gt;uri-&gt;segment(2); echo site_url("event/$$call_by/Description/".(($sort_order == 'asc' &amp;&amp; $sort_by == $field_name) ? 'desc' : 'asc')."/$limit"); ?&gt;"&gt;Desc &lt;?php echo ($sort_order == 'asc' &amp;&amp; $sort_by == "Description") ? '&amp;#9650;' : '&amp;#9660;' ?&gt;&lt;/a&gt;&lt;a href="&lt;?php echo site_url("event/$$call_by/Price/".(($sort_order == 'asc' &amp;&amp; $sort_by == $field_name) ? 'desc' : 'asc')."/$limit"); ?&gt;"&gt;Price &lt;?php echo ($sort_order == 'asc' &amp;&amp; $sort_by == "Price") ? '&amp;#9650;' : '&amp;#9660;'?&gt;&lt;/a&gt; &lt;?php } ?&gt; &lt;?php endforeach; ?&gt; &lt;/div&gt; </code></pre> <p>I am quite sure that I haven't followed all laws of programming.</p> <ol> <li>How can I use the above code for all 3 modules?</li> <li>Where can I improve on these functions?</li> <li>How can I make this code more object-oriented and less scripted?</li> </ol>
[]
[ { "body": "<p>When you have long argument lists, you might consider compacting the arguments into an array. However, sometimes its not an issue of the size of the argument list, its an issue of the size of the method. In this case it is the latter. Your <code>event_list()</code> method is doing entirely too much, which is why your argument list is also so long. If we follow the Single Responsibility Principle, then a function/method should only be responsible for one thing. This method is responsible for at least four different tasks. I would seriously consider breaking this method up into smaller methods. That's the biggest issue I see.</p>\n\n<p>Your variables should be more descriptive, especially when using magic numbers to access unknown values. What is <code>$third_term</code>? Where did \"3\" come from and why is it important?</p>\n\n<p>Why would <code>$sort_by</code> be numeric? It doesn't appear that you ever use it as a numeric value. Instead of trying to manipulate the sort method based on vague inputs, I would create a whitelist of acceptable sort terms and if the one provided does not match one in the whitelist I would default to one of the accepted ones. For instance:</p>\n\n<pre><code>$whitelist = array(\n 'Description',\n 'Price',\n //etc...\n);\n\nif( ! in_array( $sort_by, $whitelist ) ) {\n $sort_by = array_shift( $whitelist );\n}\n</code></pre>\n\n<p>Along with Single Responsibility, you have \"Don't Repeat Yourself\" (DRY). As the name implies, your code should not repeat itself. Your \"base_url\" is very similar throughout this method and seems to be set no matter what. So instead of typing that again and again, I would create a variable to contain the difference and apply it at the end. Another change I would consider making is to use an <code>implode()</code> to accomplish the string. This way you can more easily manipulate it if necessary.</p>\n\n<pre><code>if( $category ) {\n //etc...\n $diff = 'categories';\n}\n//etc...\n\n$sections = array(\n 'event',\n $diff,\n $sort_by,\n $sort_order,\n $limit\n);\n$site_url = implode( '/', $sections );\n$config[ 'base_url' ] = site_url( $site_url );\n</code></pre>\n\n<p>Your elseif statement is redundant. The inner if/else structure mirrors the outer, so you can just shift those inner statements up a level and reverse the order to ensure that the post is processed before the search. This removes a level indentation and saves processing.</p>\n\n<pre><code>elseif( $_POST ){\n //etc...\n} elseif( $search ) {\n //etc...\n} else {\n</code></pre>\n\n<p>Where did <code>$data</code> come from? You just started adding to it without declaring it first. Always declare your arrays before trying to manipulate them, else you could end up accidentally modifying something you didn't mean to or accessing a malicious global. Besides, not declaring issues warnings to your browser. You should have error reporting on high enough to catch these. Also why are you setting all of those values individually? Doing it that way adds a lot of clutter. I would either wait until everything was ready to add into the array all at once, find some way of looping the elements or combining/merging arrays, or compacting variables. The first is probably the method I'd lean to in this situation. The second would be ideal, but because the keys change between arrays it would make this impossible. The third is good if you have already created variables and used them elsewhere. Otherwise you end up creating tons of unused variables just to create an array.</p>\n\n<pre><code>//manually\n$data = array(\n 'num_results' =&gt; $results[ 'num_rows' ],\n 'events' =&gt; $results[ 'rows' ],\n //etc...\n);\n\n//compacting\n$num_results = $results[ 'num_rows' ];\n$events = $results[ 'rows' ];\n//etc...\ncompact(\n 'num_results',\n 'events',\n //etc...\n);\n</code></pre>\n\n<p>Another principle being violated here would be the Separation of Concerns (SoC). I'm not really sure I can adequately explain this one, so I'll just suggest you look into it and see how it applies to things like POST, flashdata, and the inner workings of MVC. Its one of those things I'm aware of and can notice and avoid in my own work, but have issues trying to explain, sorry.</p>\n\n<p>What is the point of <code>search_list()</code>? Its just a slightly reduced wrapper for an already public method. I would remove it and just use <code>event_list</code>.</p>\n\n<p>The <code>printf</code> functions should only be used when applying different variables to the same template (I'll demonstrate this shortly), not when just applying variables to a string. You can do the same thing with concatenation, or better yet, by using double quotes you can have PHP automatically escape variables and entities. Also, MySQL is just as lenient as PHP when it comes to whitespace. I would seriously contemplate making your SQL statements more legible. I would show you an example here, but I'm not that familiar with SQL to accurately format it.</p>\n\n<p>I was getting a headache trying to decipher your HTML so I just edited it. Unless I miss my guess the <code>$call_by</code> shouldn't change on any iteration so it should be defined outside of the loop. This still feels a little too PHP-bulky for a view, but I don't know if anything can be done about that.</p>\n\n<pre><code>&lt;?php $call_by = $this-&gt;uri-&gt;segment( 2 ); ?&gt;\n\n&lt;div class=\"sorting\"&gt;\n &lt;?php foreach($fields as $field_name =&gt; $field_display): ?&gt;\n\n &lt;?php if (($sort_by == $field_name)) : ?&gt;\n\n &lt;?php\n $sort = $sort_order == 'asc' &amp;&amp; $sort_by == $field_name ? 'desc' : 'asc';\n\n $temp = \"event/$$call_by/%s/$sort/$limit\";\n $desc_url = site_url( sprintf( $temp, \"Description\" ) );\n $price_url = site_url( sprintf( $temp, \"Price\" ) );\n\n $desc_ent = $sort_order == 'asc' &amp;&amp; $sort_by == 'Description' ? '&amp;#9650;' : '&amp;#9660;';\n $price_ent = $sort_order == 'asc' &amp;&amp; $sort_by == \"Price\" ? '&amp;#9650;' : '&amp;#9660;';\n ?&gt;\n\n &lt;a href=\"&lt;?php echo $desc_url; ?&gt;\"&gt;Desc &lt;?php echo $desc_entity; ?&gt;&lt;/a&gt;\n &lt;a href=\"&lt;?php echo $price_url; ?&gt;\"&gt;Price &lt;?php echo $price_ent; ?&gt;&lt;/a&gt;\n\n &lt;?php endif; ?&gt;\n\n &lt;?php endforeach; ?&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Hope this helps</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T16:20:03.143", "Id": "31926", "Score": "0", "body": "Thank you very much for taking time to review and pointing out all the errors.I will definitely apply all the suggested programming techniques.(P.S: I cannot vote up due to lack of reputation)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T17:58:27.833", "Id": "19849", "ParentId": "19835", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T04:53:12.960", "Id": "19835", "Score": "3", "Tags": [ "php", "object-oriented", "codeigniter", "pagination" ], "Title": "Implementing pagination with three modules" }
19835
<p>This question is a follow-up to the questions here: <a href="https://codereview.stackexchange.com/questions/19803/illustrating-di-and-ioc-concepts-simple-code-requesting-review">Illustrating DI and IoC concepts : Simple code requesting review</a></p> <p>I have taken the very good review comments got and tweaked the code. These are the classes I define:</p> <ol> <li><code>Dependencies</code>: This <em>namespace</em> holds the interfaces and concrete implementations. </li> <li><code>CoreClassDI</code>: This class is primarily used to illustrate dependency injection.</li> <li><code>IoC</code>: This class defines a simple IoC container following instructions from <a href="http://kenegozi.com/Blog/2008/01/17/its-my-turn-to-build-an-ioc-container-in-15-minutes-and-33-lines" rel="nofollow noreferrer">here</a>. Hence I will not be sharing this code for review.</li> <li><code>Program</code>: This is the console application that illustrates the concepts</li> </ol> <p>Please have a look at my code and feel free to give me your opinion on <em>any</em> aspect of coding. Ofcourse, with an emphasis to the IoC and DI concepts. I have used my own IoC container as opposed to readymade ones since I wanted to understand the working better.</p> <p>Here is the code.</p> <p><strong>Depedencies namespace</strong></p> <pre><code>namespace Dependencies { public interface IPredictingFuture { IWriter Writer { get; set; } string NewYearPrediction(); } public class BadConnections : IPredictingFuture { public BadConnections() { Console.ForegroundColor = ConsoleColor.Red; } public string NewYearPrediction() { return "Take care!! It is a terrible year :-("; } public IWriter Writer { get; set; } } public class EartAndSkyPrediction : IPredictingFuture { public EartAndSkyPrediction() { Console.ForegroundColor = ConsoleColor.DarkGreen; } public string NewYearPrediction() { return "Everything will be just great next year!"; } public IWriter Writer { get; set; } } //This is the template for any class which intends to communicate //the message of the predicting classes to the end user. //The return type of this method is void since it handles the //communication of the message as implemented by the derived classes. public interface IWriter { //Write the message in a format requested by the user. void WriteMessage(string question); } //This class delivers the message by writing it out on the console. public class ConsoleWriter : IWriter { public void WriteMessage(string message) { Console.WriteLine(message); } } } </code></pre> <p><strong>CoreClassDI</strong></p> <pre><code>namespace CoreClassDI { //This class illustrates the dependency injection through the constructor. public class CoreClassDI { //This is a private property which will be initialized by the //constructor private IPredictingFuture FuturePredictions { get; set; } //This is a predict function in which you "inject" the concrete class //in the property. The property injection is achieved through the constructor. //We can also alternatively inject dependencies through the WriteOutPredictions() //function. //Writer is a property of IPredictingFuture. The concrete class for this is //being injected through the constructor here. public CoreClassDI(IPredictingFuture predictionType, IWriter writer) { FuturePredictions = predictionType; predictionType.Writer = writer; } public void WritePredictions() { FuturePredictions.Writer.WriteMessage(FuturePredictions.NewYearPrediction()); } } } </code></pre> <p><strong>ClientCode</strong></p> <pre><code>namespace ClientCode { //This is the main program which controls and illustrates the different types of DI //You need to start debug in one of these programs to understand the concepts //of DI and IoC class Program { static void Main(string[] args) { string choice; string input; Console.WriteLine("Choose the correct option"); Console.WriteLine("1 for dependency injection"); Console.WriteLine("2 for IoC container"); input = Console.ReadKey().KeyChar.ToString(); switch (input) { case "1": Console.WriteLine("Choose the type of predictions you want:"); Console.WriteLine("G or g : Good predictions"); Console.WriteLine("B or b : Bad predictions"); choice = Console.ReadKey().KeyChar.ToString(); IPredictingFuture predictionObj = null; //The dependency is loaded based on run time choice switch (choice) { case "G": case "g": //Setting good predictions predictionObj = new EartAndSkyPrediction(); break; case "B": case "b": //Setting bad predictions on the same object predictionObj = new BadConnections(); break; default: Console.WriteLine("Good going! Who cares anyway?"); break; } var consoleWriter = new ConsoleWriter(); //Injecting the prediction object, writer object and calling the client code with it CoreClassDI.CoreClassDI oracleObj = new CoreClassDI.CoreClassDI(predictionObj, consoleWriter); oracleObj.WritePredictions(); Console.ReadKey(true); break; case "2": Console.WriteLine("Choose the type of predictions you want:"); Console.WriteLine("G or g : Good predictions"); Console.WriteLine("B or b : Bad predictions"); //Registering the concrete implementation for IWriter here IoC.Register&lt;IWriter, ConsoleWriter&gt;(); choice = Console.ReadKey().KeyChar.ToString(); switch (choice) { case "G": case "g": //Registering the good predictions IoC.Register&lt;IPredictingFuture, EartAndSkyPrediction&gt;(); break; case "B": case "b": //Loading the bad predictions IoC.Register&lt;IPredictingFuture, BadConnections&gt;(); break; default: Console.WriteLine("Good going! Who cares anyway?"); Console.ReadKey(true); break; } //Resolving the registered dependencies IPredictingFuture objPredictions = IoC.Resolve&lt;IPredictingFuture&gt;(); objPredictions.Writer = IoC.Resolve&lt;IWriter&gt;(); //Writing the message objPredictions.Writer.WriteMessage(objPredictions.NewYearPrediction()); Console.ReadKey(true); break; default: //Handing the invalid choice Console.WriteLine("Invalid choice"); Console.ReadKey(true); break; } } } } </code></pre>
[]
[ { "body": "<p>There are two issues I would like to emphasize in your question/code:</p>\n\n<ol>\n<li>it looks like you're trying to separate DI and IoC principles. In fact they are just different points of view on a same thing, because Dependency Injection is the software pattern usually used to implement Inversion of Control. So there is no need to make difference between them, quite often these terms are treated as synonyms, and most IoC containers do dependency injection as a part of their function.</li>\n<li><code>CoreClassDI</code> knows too much about <code>FuturePredictions</code>, as it tries to initialize it with <code>writer</code>. This task should be delegated to IoC container (or the code that registers objects in container), and <code>CoreClassDI</code> should only use the pre-configured instance. Also, either <code>IPredictingFuture</code> should expose the method that predicts the future <strong>and</strong> outputs it to writer (so that <code>CoreClassDI</code> just calls this method) or <code>IWriter</code> should be declared on <code>CoreClassDI</code> class (preferably), and then this class acts as a mediator that gets prediction and outputs it to the writer. The line <code>FuturePredictions.Writer.WriteMessage(FuturePredictions.NewYearPrediction())</code> highlights this problem</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T11:59:13.217", "Id": "31794", "Score": "0", "body": "Thanks for your response! What I wanted to show was using a IoC container and DI directly side-by-side. And, then to explore which is more testable. This is why I am insisting on having saparate classes for both. `IoC` class for container. And `CoreClassDI` for direct dependency injection. Basically both these classes should be reflections of each other. They should not share responsibility. For, in the end, only one of them will survive!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T12:09:06.323", "Id": "31795", "Score": "2", "body": "DI and IoC concepts are not competing. IoC is achieved via dependency injection, and IoC container is an implementation pattern that uses DI to wire up and initialize instances." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T12:15:34.610", "Id": "31797", "Score": "0", "body": "As for your second point, you are right. `FuturePredictions.Writer.WriteMessage(FuturePredictions.NewYearPrediction())` is really ugly. I am not sure how I missed this one. Here is what I did - I took IWriter and added it as a property to `CoreClassDI` like you suggested. Then, the same line became `Writer.WriteMessage(FuturePredictions.NewYearPrediction());`. Ofcourse the writer object and the prediction object are both constructor injection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T12:20:35.417", "Id": "31799", "Score": "0", "body": "Posted the earlier comment before yours... I see what you are trying to say. My `CoreClassDI` will eventually be refined into the class `IoC` which I borrowed from [Ken Egozi](http://kenegozi.com/Blog/2008/01/17/its-my-turn-to-build-an-ioc-container-in-15-minutes-and-33-lines). Am I correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T13:17:14.147", "Id": "31803", "Score": "0", "body": "Thank you almaz, for your patience in answering me for both these questions! I value what I learnt in our discussions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T15:33:09.550", "Id": "31807", "Score": "0", "body": "I would suggest to use existing IoC frameworks like `Autofac` or `StructureMap`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T14:08:44.523", "Id": "19841", "ParentId": "19838", "Score": "1" } } ]
{ "AcceptedAnswerId": "19841", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T12:02:07.453", "Id": "19838", "Score": "0", "Tags": [ "c#" ], "Title": "Illustrating DI and IoC concepts" }
19838
<p>I posted this same question on StackOverflow but guys over there told me to post it here.</p> <p>I have programming in PHP since past 2 years and yet haven't found a perfect script for logging the user in. It's very messy when it comes to deciding whether to use Session or Cookies or both. What value to assign to the Session ID? Whether to store that value in MySQL table or not. How to auto-login the user? And so on...</p> <p>I've been using this code for few months. Please tell me whether this is fine.</p> <p>This is the main <code>signin</code> function.</p> <pre><code>&lt;?php //this function is called after sanitizing the user-input //$u is username and $p is password function signin($u,$p) { global $conn, $current_user, $signin_stat, $incorrect; $q_string="SELECT uid FROM users WHERE (emailid='$u' OR uname='$u') AND AES_DECRYPT(pass,CONCAT(uname,'$p'))='$p'"; $q=$conn-&gt;query($q_string); if($q-&gt;num_rows==1) { $c=$q-&gt;fetch_row(); $uid=$c[0]; //getting uid $current_user=new User($uid); //creating $current_user object set_session($uid); //setting session $signin_stat=1; return true; } else { signout(0); $incorrect=1; return false; } } ?&gt; </code></pre> <p>This is the <code>set_session()</code> function :</p> <pre><code>&lt;?php function set_session($uid) { global $conn; $sid=sha1($uid+time()+$_SERVER['REMOTE_ADDR']); $q_string="UPDATE users SET sid='$sid' WHERE uid=$uid"; $q=$conn-&gt;query($q_string); $_SESSION['user_session']=$sid; if($q) return true; else return false; } ?&gt; </code></pre> <p>This is the <code>auto_signin</code> script :</p> <pre><code>&lt;?php if(isset($_SESSION['user_session'])) { $sid=$_SESSION['user_session']; global $conn, $current_user; $q_string="SELECT uid FROM users WHERE sid='$sid'"; $q=$conn-&gt;query($q_string); if($q-&gt;num_rows==1) { $c=$q-&gt;fetch_row(); $uid=$c[0]; $current_user=new User($uid); $signin_stat=1; $current_user-&gt;update_online_stat(); } else { signout(0); } } ?&gt; </code></pre> <p>This is the <code>signout()</code> function</p> <pre><code>&lt;?php function signout($uid) { global $conn, $current_user, $signin_stat; $sid='NULL'; $q_string="UPDATE users SET sid='$sid' WHERE uid=$uid"; $q=$conn-&gt;query($q_string); $signin_stat=0; $current_user=0; $_SESSION['user_session']=''; unset($_SESSION['user_session']); unset($_POST); session_destroy(); } ?&gt; </code></pre> <p><strong>notes</strong> : <code>$conn</code> is the mysqli object</p> <p><code>$current_user</code> is the user object</p> <p><code>sid</code> is the field in mysql users table which holds the current session id of the respective user.</p> <p>Is this script fine or would you suggest some changes?</p> <p>Or is this completely crap and needs to be written again from scratch?</p> <p>Please help me out. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T13:57:25.947", "Id": "31717", "Score": "0", "body": "Try to avoid using globals everywhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T15:46:02.963", "Id": "31725", "Score": "0", "body": "@tsabz Why should I avoid using globals? How do I access the `$conn` variable which is the MySQLi object. Should I declare it again and again in every function? And other objects which are frequently accessed shouldn't also be declared global?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T15:53:57.170", "Id": "31726", "Score": "0", "body": "Gloabls are a security concern. Having your database connection as a global allows any application, malicious or otherwise, to gain access to your database. They are also considered bad because of how difficult it sometimes is to trace while debugging. In a large script a global can appear to be a simple variable and sometimes its not always obvious where it came from. See my answer for alternatives." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-23T13:07:24.770", "Id": "31772", "Score": "0", "body": "Your signin() function contains an SQL injection vulnerability. You're also storing passwords, which is a huge no no. You can read about working with databases and password hashing here: http://www.phptherightway.com/ These are much more important problems than whether to store session data in an encrypted cookie, or in database (both are fine)." } ]
[ { "body": "<p>I'm no security expert, not even close, but I can tell you what I use and have observed. I only use cookies to remember the username. Cookies aren't secure so you want to limit what you save in them. I also use sessions to create persistence by passing the user object on. Is this the right way? I don't know, but it has served me well and does not contradict anything I have read on the subject. As for auto-login, you can do something similar to what SO does. You can create a client side cookie with a unique ID and pair it to an account. If the login computer has that cookie then you can have it automatically login. An added security feature might be to also match IP addresses. Not sure if this is exactly what SO does, but its similar. Again no security expert, so I would gather more opinions and do your research.</p>\n\n<p>If you are going to provide comments about a function then you should use doccomments as they are more useful in that IDEs can recognize them and provide them as auto-complete hints. Additionally, I would not use single letter variables except for incrementals or throwaways. The abstraction can lead to confusion if you are not careful and it makes it more difficult to tell what is going on at a glance.</p>\n\n<pre><code>/** this function is called after sanitizing the user-input\n * \n * @param string $user is username\n * @param string $pass is password\n */\n</code></pre>\n\n<p>As tsabz pointed out, you should never use globals. They are evil and have no place in this world. Help banish these foul demons by forgetting you ever heard of them. Especially don't use globals for something as important as a database connection. It is insecure. If you must use a variable in a function, then inject that variable into the function via the argument list. In this case that would add a very large list, so you might instead want to compact those values into an array and inject the array instead. However, I'll point out in a few that some of these variables are unnecessary, which will decrease the size of said list.</p>\n\n<p>If you are returning from an if statement, then there is no reason to have an else statement, the else is implied. I would remove it to reduce the amount of indentation, however that is really a preference point and entirely up to you.</p>\n\n<pre><code>if( $q-&gt;num_rows == 1 ) {\n //etc...\n return TRUE;\n}\n\n//etc...\nreturn FALSE;\n</code></pre>\n\n<p>There are a couple of different things you can do instead of using <code>$current_user</code> as a global. The easiest way would be to convert it to a session variable so that it can be shared. Another, more practical way would be to return the user object instead of a boolean and then later persist it if necessary. This later method makes sense for a number of reasons. First, it goes along with what the function says it is doing. By signing in I expect either a user object or a failure, not a TRUE/FALSE. Second, it allows you to do away with <code>$signin_stat</code> and <code>$incorrect</code> which were both redundant. You could accomplish the same thing with the boolean return (to illustrate: <code>if( signin() ) { $signin_stat = 1; }</code>). Third, it allows you to change how you persist the user object so you are not reliant on sessions.</p>\n\n<pre><code>$_SESSION[ 'current_user' ] = new User( $uid );\n//or\nif( $q-&gt;num_rows == 1 ) {\n //etc...\n return new User( $uid );\n}\n\n//etc...\nreturn FALSE;\n</code></pre>\n\n<p>Always, always, always use braces. I know it is a feature and you can get away with it, but it can be confusing and can cause issues, especially if you combine two statements on one line like that. Not that an if/else statement is even necessary here. If you want to return a boolean value based on the return of an expression, just return the expression. Here it is a little different because there is no comparison to make this a true expression. Instead you are relying on PHP to automatically convert it to a boolean for the comparison. So you might want to typecast it in the return to get a true boolean.</p>\n\n<pre><code>//braces\nif( $q ) {\n return TRUE;\n} else {\n return FALSE;\n}\n//equivalent to above\nreturn ( bool ) $q;\n</code></pre>\n\n<p>Some of this code is violating the \"Don't Repeat Yourself\" (DRY) Principle. As the name implies, your code should not repeat itself. If you look at your login function and compare it to your auto-login function you should be able to see the similarities. You could create a new function that accomplishes the shared task, but because you are using regular functions this would make bypassing the normal signin function a security concern. I don't really see a way around this, except to convert to using a class, which is something you might want to consider anyways. Many of the issues I pointed out above would be solved much easier in a class. For instance, you could convert those globals to class properties to the same effect. Then there is also the encapsulation that will allow you to hide properties and methods, such as the <code>$conn</code> property and shared login method I was mentioning. I'm not trying to pressure you into using a class, but I am suggesting you give it a look. Hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T01:34:38.410", "Id": "32835", "Score": "0", "body": "all right, i have shifted to `class` but is making mysqli connection object `public` also a security issue?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T15:50:11.927", "Id": "19845", "ParentId": "19839", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T12:16:28.100", "Id": "19839", "Score": "2", "Tags": [ "php", "mysql" ], "Title": "The perfect PHP login script" }
19839
<p>I'm looking to remove all magic quotes at the start of my PHP script (if they are turned on). The code I'm using to do this is rather simple, so I was wondering if I was overlooking anything:</p> <pre><code>if (get_magic_quotes_gpc()) { foreach ($_GET as $key =&gt; $value) $_GET[$key] = stripslashes($value); foreach ($_REQUEST as $key =&gt; $value) $_REQUEST[$key] = stripslashes($value); foreach ($_POST as $key =&gt; $value) $_POST[$key] = stripslashes($value); foreach ($_COOKIE as $key =&gt; $value) $_COOKIE[$key] = stripslashes($value); } </code></pre> <p>Am I missing / overlooking anything? Thanks.</p>
[]
[ { "body": "<p><a href=\"http://php.net/manual/en/security.magicquotes.php\" rel=\"nofollow noreferrer\">Magic Quotes are removed as of PHP 5.4</a>. I would consider something like this only if you don't have control over the php.ini and only if you are on &lt; 5.4.</p>\n\n<p>Your code does not handle multi dimensional arrays nor array keys. <a href=\"https://stackoverflow.com/a/2133211/231774\">See this stackoverflow answer for a better method of disabling magic quotes</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T15:04:09.083", "Id": "19896", "ParentId": "19843", "Score": "1" } }, { "body": "<p>If you are sanitizing your input just for the sake of sanitizing your input, you're wasting time (both yours in coding and the computer in execution). Do you need to sanitize $_COOKIE if you never use it? What about $_SESSION?</p>\n\n<p><strong>Only sanitize what you need, when you need it.</strong> Switching to a PDO system to have it sanitize your database queries would solve that aspect (and the #1 reason to sanitize).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-01T18:40:14.313", "Id": "20078", "ParentId": "19843", "Score": "2" } } ]
{ "AcceptedAnswerId": "19896", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T14:20:29.300", "Id": "19843", "Score": "1", "Tags": [ "php" ], "Title": "Foreach removal of Magic Quotes PHP" }
19843
<p>Here is the class:</p> <pre><code>class Field(object): """Class which contains logic of field-processing """ def __init__(self, routes, callback=None, is_iterable=False,default=None): """ Arguments: - `routes`: sequence of xPath routes to the field, in order of descending priority. - `callback`: callable handler of field - `is_iterable`: if there may be a more then one field with a such route in the xml Document """ self._routes = routes self._callback = callback self._is_iterable = is_iterable self._default = default def _clean_up(self, r): """Cleans up the result of xpath in according to self._is_iterable value and some parameters qualiteies. Sometimes xpath method returns list containing one element, but field is not iterable, so we need not the list, but it's single element Arguments: - `r`: conversable to True result of lxml.etree._Element.xpath method. """ if isinstance(r,list) and self._is_iterable: return map(self._callback,r) if callable(self._callback) else r if isinstance(r,list) and not self._is_iterable: if len(r) == 1: return self._callback(r.pop()) if callable(self._callback) else r.pop() else: raise error.RuntimeError('Many instances of non-iterable field') else: return self._callback(r) if callable(self._callback) else r def get_value(self,xml,nsmap = namespaces): """Returns value of the field in passed document If you passed False value of is_iterable to construct, you get a SINGLE result or error, not a list if you passed True, you get LIST, which may contain one element. if the field was not found, you get None. Anyway. Arguments: - `xml`: lxml.etree._Element instance - `nsmap`: dict with namespaces for xpath. """ if not etree.iselement(xml): raise error.InvalidArgumentError('Passed document is not valid lxml.etree Element'); for route in self._routes: if xml.xpath(route): return self._clean_up(xml.xpath(route,namespaces=nsmap)) else: return self._default </code></pre> <p>And there are its unit tests:</p> <p>Example XML:</p> <pre class="lang-xml prettyprint-override"><code>&lt;xml version="1.0"&gt; &lt;root&gt; &lt;non-iterable&gt;Non-ascii content.Привет.&lt;/non-iterable&gt; &lt;iterable&gt;Раз&lt;/iterable&gt; &lt;iterable&gt;Два&lt;/iterable&gt; &lt;iterable&gt;Три&lt;/iterable&gt; &lt;/root&gt; </code></pre> <p>and test script:</p> <pre><code>document = etree.parse('examples/document_for_common_module_testing.xml').getroot() class TestGetFieldValueMethod(unittest.TestCase): """ """ def test_invalid_argument_exception(self): """An exception must be risen if passed document isn't valid lxml.etree Element """ f = common.Field(['/root/iterable/text()']) try: f.get_value('Not an element...') except error.InvalidArgumentError: return self.fail('There mus be an exception') def test_non_iterable_value(self): """Testing if returned value is correct """ f = common.Field(['/root/non-iterable/text()']) val = f.get_value(document) self.assertEqual(val,u'Non-ascii content.Привет.') #Now a callback is added f = common.Field(['string(/root/non-iterable/text())'], callback=(lambda x:x.upper())) val = f.get_value(document) self.assertEqual(val,u'NON-ASCII CONTENT.ПРИВЕТ.') #Now a default value is added. f = common.Field(['/unexisting'],default='Lol') val = f.get_value(document) self.assertEqual(val,'Lol') def test_non_iterable_exception(self): """The error must be raisen if there are more then one non-iterable element """ f = common.Field(['/root/iterable/text()']) try: f.get_value(document) except error.RuntimeError: return self.fail('There must be a runtime error') def test_iterable_values(self, ): """ """ f = common.Field(['/root/iterable/text()'],is_iterable=True)#callback=(lambda x:x.upper()) val = f.get_value(document) self.assertEqual(val,[u'Раз',u'Два',u'Три']) f = common.Field(['/root/iterable/text()'],is_iterable=True, callback=(lambda x:x.upper())) val = f.get_value(document) self.assertEqual(val,[u'РАЗ',u'ДВА',u'ТРИ']) def test_unexisting_value(self): """ """ f = common.Field(['/unexisting/text()']) self.assertEqual(f.get_value(document),None) f = common.Field(['/unexisting/text()'], callback=(lambda x:x.upper())) self.assertEquals(f.get_value(document),None) </code></pre> <p>It is used for parsing XML documents with lxml library. For example I create </p> <pre><code>f=Field(['string(/root/non-iterable/text())'],callback=(lambda x: x.upper())) </code></pre> <p>then do </p> <pre><code>f.get_value(document) </code></pre> <p>and it returns <code>/root/title/text()</code> value where all chars are uppercase.</p> <ol> <li>What do you think of this class?</li> <li>Is this simple to understand how it works and what it does?</li> <li>Do you think it is a good piece of code?</li> </ol>
[]
[ { "body": "<p>You are only evaluating the first matching route, but the expected behavior for <code>is_iterable=True</code> and multiple matching routes would be to match all routes. If this was not the intention, distinguish between all 4 use cases:</p>\n\n<ol>\n<li>Only use first matching route, only match 1</li>\n<li>Use all routes, only match 1 per route</li>\n<li>Only use first matching route, match all</li>\n<li>Use all routes, match all</li>\n</ol>\n\n<p>When <code>is_iterable=True</code> and a <code>default</code> value is set, your class will either return a list or a single value, but never <code>None</code>. Your comment is deceiving.<br>\nAlso: If <code>default</code> is no list, should it be encapsulated in a list in such case?</p>\n\n<p>With <code>is_iterable=True</code>, I would expect an empty list as default return value.</p>\n\n<p>Ambiguous XPath should match the first occurrence, but not throw if multiple are matched. Validating the XML is not your area of responsibility. Your current implementation will even throw an error when the XML is well formed according to an attached, authoritative XSD.</p>\n\n<p>Unexpected mismatch in behavior between \"multiple routes match once\" and \"single route matches multiple times\". In the first case, you get the first result. In the second case you are throwing a runtime error.</p>\n\n<p>Should the combination of <code>default</code> set and <code>callback</code> set apply the callback to the default value as well or return the plain default value? When the <code>callback</code> is supposed to consume <code>default</code>, and <code>is_iterable=True</code> is set, what is the expected behavior?</p>\n\n<p>Why is the method called <code>_clean_up</code>? It's not cleaning up anything, it's processing the return value of the <code>xpath</code> call. Naming the parameter <code>r</code> isn't optimal either. The rule of choosing descriptive names applies to parameters of internal helper methods as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-26T12:24:04.020", "Id": "153081", "Score": "0", "body": "Inaugurating your entry to the site with a very helpful answer. Welcome fellow CodeReviewer! I hope you enjoy your time here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-26T12:12:09.230", "Id": "85052", "ParentId": "19846", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T15:53:19.120", "Id": "19846", "Score": "4", "Tags": [ "python", "parsing", "xml" ], "Title": "DOMDocument field class" }
19846
<p>I have written the following code, I am quite new to C# and Sockets, so perhaps I have made some big mistakes that only more experienced eyes can detect. This is to be used in a Windows Mobile 6.1 device, so I am trying to avoid using many threads.</p> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.Net; using System.Threading; using System.Diagnostics; namespace SmartDevice_Server { //ClientConnection saves connection information is used to keep context in Async and Event calls public class ClientConnection : EventArgs { public NetworkStream NetworkStream { get; private set; } public byte[] Data { get; private set; } public int byteReadCount { get; set; } public ClientConnection(NetworkStream networkStream, byte[] data) { NetworkStream = networkStream; Data = data; } } //MySocket - Is a server that listens for events and triggers Events upon Request Completion public class MySocketTCP { #region Class Members TcpListener myTcpListener; TcpClient myTcpClient; NetworkStream myNetworkStream; const string localHost = "127.0.0.1"; IPAddress myAddress = IPAddress.Parse(localHost); int myPortNumber = 58889; byte[] myData; int bytesReadCount; const int MIN_REQUEST_STRING_SIZE = 10; int TimeStart; //Event public event socketReadCompleteHandler socketReadCompleteEvent; public EventArgs eventArguments = null; public delegate void socketReadCompleteHandler(MySocketTCP myTcpSocket, ClientConnection eventArguments); #endregion //Constructor public MySocketTCP() { Init(); } //Constructor overloaded to receive IPAdress Host, and Port number public MySocketTCP(IPAddress hostAddress, int portNumber) { myAddress = hostAddress; myPortNumber = portNumber; Init(); } //Initializes the TCPListner public void Init() { try { myTcpListener = new TcpListener(myAddress, myPortNumber); //myNetworkStream = myTcpClient.GetStream(); } catch (Exception ex) { throw ex; } } /*TODO_Listener_Timer: After you accept a connection you wait for data to be Read indefinitely *Possible solution: Use a timeout to close the socket connection. *Check WIKI, TODOS * */ //Listens Asynchronously to Clients, class a recieveMessageHandler to process the read public void ListenAsync() { myTcpListener.Start(); while (true) { //blocks until a client has connected to the server myTcpClient = myTcpListener.AcceptTcpClient(); var client = new ClientConnection(myTcpClient.GetStream(), new byte[myTcpClient.ReceiveBufferSize]); // Capture the specific client and pass it to the receive handler client.NetworkStream.BeginRead(client.Data, 0, client.Data.Length, r =&gt; receiveMessageHandler(r, client), null); } } //Callback is used to Process the request Asynchronously, triggers socketReadCompleteEvent public void receiveMessageHandler(IAsyncResult asyncResult, ClientConnection clientInstance) { bytesReadCount = 0; lock (clientInstance.NetworkStream) { try { bytesReadCount = clientInstance.NetworkStream.EndRead(asyncResult); clientInstance.byteReadCount = bytesReadCount; } catch (Exception exc) { throw exc; } } if (bytesReadCount &lt; MIN_REQUEST_STRING_SIZE) { //Could not read form client. Debug.WriteLine("NO DATA READ"); } else { if (socketReadCompleteEvent != null) { socketReadCompleteEvent(this, clientInstance); } } } //Reads the request, uses the ClientConnection for context public string ReadAsync(ClientConnection connObj) { int bytesReadCount = connObj.byteReadCount; byte[] myData = connObj.Data; string xmlMessage; try { xmlMessage = Encoding.ASCII.GetString(myData, 0, bytesReadCount); } catch (Exception ex) { throw ex; } return xmlMessage; } //Deprecated public string Read() { string xmlMessage; try { xmlMessage = Encoding.ASCII.GetString(myData, 0, bytesReadCount); } catch (Exception ex) { throw ex; } return xmlMessage; } //Deprecated public void Write(byte[] outBytes) { try { myNetworkStream.Write(outBytes, 0, outBytes.Length); } catch (Exception ex) { throw ex; } } //Deprecated public void Write(string outMessage) { byte[] outBytes = Encoding.ASCII.GetBytes(outMessage); try { myNetworkStream.Write(outBytes, 0, outBytes.Length); } catch (Exception ex) { throw ex; } int TimeEnd = Environment.TickCount; int TimeResult = TimeEnd - TimeStart; } //Is used to send the message to the correct socket public void WriteAsync(ClientConnection connObj, string outMessage) { byte[] outBytes = Encoding.ASCII.GetBytes(outMessage); try { connObj.NetworkStream.Write(outBytes, 0, outBytes.Length); } catch (Exception ex) { throw ex; } int TimeEnd = Environment.TickCount; int TimeResult = TimeEnd - TimeStart; } //Closes the client public void Close() { //myNetworkStream.Close(); try { myTcpClient.Close(); } catch (Exception ex) { throw ex; } } } } </code></pre>
[]
[ { "body": "<p>There are a number of naming issues here so it's quite hard to understand the code, I'll start from those:</p>\n\n<ul>\n<li>public properties/events/methods should be named <code>PascalCase</code> (<code>receiveMessageHandler</code> => <code>ReceiveMessageHandler</code>)</li>\n<li>events are named according to the time they occur. If event describes that some fact occurred, it should be named in passive voice without \"Event\" suffix (<code>socketReadCompleteEvent</code> => <code>SocketReadCompleted</code>)</li>\n<li>private fields should be name <code>camelCase</code> (<code>TimeStart</code> => <code>timeStart</code>), I prefer to have underscore prefix</li>\n<li>classes derived from <code>EventArgs</code> should have <code>EventArgs</code> suffix by convention</li>\n<li><code>Async</code> suffix is used to define methods that run asynchronously and return either <code>Task</code> or <code>Task&lt;TResult&gt;</code> objects. In your case <code>ListenAsync</code> just enters infinite loop.</li>\n</ul>\n\n<p>Now let's move to logical issues:</p>\n\n<ul>\n<li>if you catch exceptions you should do something rather than just re-throwing them.</li>\n<li>re-throwing exceptions should be done with <code>throw;</code>, not <code>throw ex;</code>. You loose the stack trace if you do the latter.</li>\n<li>locking should be done on private fields that are not accessible from outside (see <a href=\"http://msdn.microsoft.com/en-us/library/c5kehkcz%28v=vs.110%29.aspx\">remarks section</a>)</li>\n<li>You shouldn't expose internal streams to clients (as you do via <code>ClientConnection.NetworkStream</code>)</li>\n<li>Why do you expose an event that returns raw <code>byte[]</code> and have a separate method that converts this data to string? If you plan to receive strings only just convert array to bytes straight away, otherwise leave the task to others.</li>\n</ul>\n\n<p><strong>Update</strong>\nSince you are creating a <code>server</code>, I would switch from event-based data handling to the structure that mimics IIS request handling via handlers: you can define an <code>IHandler</code> interface that allows customer to handle requests, and register a handler factory that can generate handler instance when you get a new client. That way you will call handler's method with payload and get response as a method result. Then you can serialise result and push it to the stream.</p>\n\n<p><strong>Update 2</strong></p>\n\n<p>Example of how I would tackle this task. First of all we have a number of classes describing our interaction in a typed way:</p>\n\n<pre><code>[XmlRoot(\"request_authenticate\")]\npublic class AuthenticateRequest\n{\n [XmlElement(\"userid\")]\n public int UserId { get; set; }\n\n [XmlElement(\"password\")]\n public string Password { get; set; }\n}\n\n[XmlRoot(\"response_authenticate\")]\npublic class AuthenticateResponse\n{\n [XmlElement(\"status\")]\n public AuthenticateStatus Status { get; set; }\n}\n\npublic enum AuthenticateStatus\n{\n [XmlEnum(\"OK\")]\n Ok,\n [XmlEnum(\"FAILED\")]\n Failed\n}\n</code></pre>\n\n<p>Then we need some base classes to handle these requests:</p>\n\n<pre><code>public interface IHandler\n{\n Type RequestType { get; }\n Type ResponseType { get; }\n\n object Handle(object request);\n}\n\npublic abstract class BaseHandler&lt;TRequest, TResponse&gt; : IHandler\n{\n public Type RequestType { get { return typeof(TRequest); } }\n\n public Type ResponseType { get { return typeof(TResponse); } }\n\n public abstract TResponse Handle(TRequest request);\n\n object IHandler.Handle(object request)\n {\n if (!(request is TRequest))\n throw new ArgumentException(\"request is expected to be of type \", \"request\");\n\n return Handle((TRequest)request);\n }\n}\n\npublic interface IHandlerFactory\n{\n IHandler GetHandler(string elementName);\n}\n\npublic class HandlerFactory : IHandlerFactory\n{\n private readonly Dictionary&lt;string, Func&lt;IHandler&gt;&gt; _mapping = new Dictionary&lt;string, Func&lt;IHandler&gt;&gt;();\n\n public void RegisterHandler(string requestRootName, Func&lt;IHandler&gt; creator)\n {\n if (creator == null)\n throw new ArgumentNullException(\"creator\", \"Factory method should be provided\");\n\n _mapping.Add(requestRootName, creator);\n }\n\n public IHandler GetHandler(string elementName)\n {\n Func&lt;IHandler&gt; creator;\n return _mapping.TryGetValue(elementName, out creator) ? creator() : null;\n }\n}\n</code></pre>\n\n<p>We can define handlers as following:</p>\n\n<pre><code>public class AuthenticationHandler : BaseHandler&lt;AuthenticateRequest, AuthenticateResponse&gt;\n{\n public override AuthenticateResponse Handle(AuthenticateRequest request)\n {\n var authenticateStatus = (request.UserId == 1 &amp;&amp; request.Password == \"123456\")\n ? AuthenticateStatus.Ok\n : AuthenticateStatus.Failed;\n\n return new AuthenticateResponse { Status = authenticateStatus };\n }\n}\n</code></pre>\n\n<p>And finally the \"server\":</p>\n\n<pre><code>public class MySocketTcp : IDisposable\n{\n private const string LocalHost = \"127.0.0.1\";\n\n private readonly IHandlerFactory _handlerFactory;\n\n private readonly IPAddress _myAddress;\n private readonly int _myPortNumber;\n private readonly TcpListener _myTcpListener;\n\n private bool _stopping;\n private readonly ManualResetEvent _stopHandle = new ManualResetEvent(false);\n\n private Thread _mainThread;\n\n public MySocketTcp(IHandlerFactory handlerFactory) : this(handlerFactory, IPAddress.Parse(LocalHost), 58889) { }\n\n public MySocketTcp(IHandlerFactory handlerFactory, IPAddress hostAddress, int portNumber)\n {\n _handlerFactory = handlerFactory;\n _myAddress = hostAddress;\n _myPortNumber = portNumber;\n _myTcpListener = new TcpListener(_myAddress, _myPortNumber);\n }\n\n public void Start()\n {\n if (_stopping)\n return;\n\n _mainThread = new Thread(Listen);\n _mainThread.Start();\n }\n\n private void Listen()\n {\n _myTcpListener.Start();\n\n while (!_stopping)\n {\n var asyncResult = _myTcpListener.BeginAcceptTcpClient(HandleIncomingTcpClient, null);\n //blocks until a client has connected to the server or stopping has been signalled\n WaitHandle.WaitAny(new[] { _stopHandle, asyncResult.AsyncWaitHandle });\n }\n\n _myTcpListener.Stop();\n }\n\n private void HandleIncomingTcpClient(IAsyncResult ar)\n {\n using (TcpClient tcpClient = _myTcpListener.EndAcceptTcpClient(ar))\n using (NetworkStream networkStream = tcpClient.GetStream())\n {\n try\n {\n XElement xml = XElement.Load(networkStream);\n ProcessXmlRequest(networkStream, xml);\n }\n catch (XmlException ex)\n {\n //TODO:log deserialization exception, notify client about error in request etc\n }\n catch (Exception ex)\n {\n //TODO:log exception, notify client about error in request processing\n }\n }\n }\n\n private void ProcessXmlRequest(NetworkStream networkStream, XElement xml)\n {\n var handler = _handlerFactory.GetHandler(xml.Name.LocalName);\n if (handler == null)\n {\n //TODO: notify customer about missing handler, sort of 404 error\n return;\n }\n\n try\n {\n XmlSerializer serializer = new XmlSerializer(handler.RequestType);\n object requestObject = serializer.Deserialize(xml.CreateReader());\n object responseObject = handler.Handle(requestObject);\n serializer = new XmlSerializer(handler.ResponseType);\n serializer.Serialize(networkStream, responseObject);\n }\n catch (InvalidOperationException ex)\n {\n //TODO: add analysis of the error\n }\n }\n\n public void Close()\n {\n _stopping = true;\n _stopHandle.Set();\n _mainThread.Join();\n }\n\n public void Dispose()\n {\n //TODO: dispose all IDisposable properties\n }\n}\n</code></pre>\n\n<p>Usage would look like:</p>\n\n<pre><code>void Main()\n{\n HandlerFactory factory = new HandlerFactory();\n factory.RegisterHandler(\"request_authenticate\", () =&gt; new AuthenticationHandler());\n //TODO: register all other handlers here\n\n MySocketTcp server = new MySocketTcp(factory);\n server.Start();\n}\n</code></pre>\n\n<p>I haven't tested this code and can't guarantee it will work on WinMobile 6.5. The main purpose of it is to demonstrate how serialization/deserialization is abstracted from request handling, and how to decouple different request processing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T19:40:14.437", "Id": "31737", "Score": "0", "body": "Thanks for the comments. I need to do this to call XML functions, afaik... I receive bytes, transform them into XML, process it and then Transform the reply XML into Bytes and send it. Is there an alternative to this?\n\nHow should I make sure that the connection that created the response is the one I send the response back? If I don't expose NetworkStream?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T21:07:14.910", "Id": "31738", "Score": "0", "body": "@AdamSurfari See updated answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T17:16:42.263", "Id": "31758", "Score": "0", "body": "can you provide me some source code that implements what you are explaining? I have 2 weeks experience with C#, and what I am implementing is indeed a server, but a local server to be run on a Windows Mobile 6.1 Pro device with a 624MHz processor and 102MB of Program memory... I will look for more info on Handlers, but if you can provide me with some links or source code that would be a huge help. Thanks again for updating the anwser!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T17:26:34.430", "Id": "31759", "Score": "0", "body": "Ok, will try to sketch the implementation on Monday. In order to make it close to your needs, please describe: what do you need the server on mobile device for? Do you plan to have multiple \"pages\" on your server, or the logic is the same on all incoming requests? Can you provide samples of incoming/outgoing XML?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T17:34:04.987", "Id": "31760", "Score": "0", "body": "Oh wow, that is much appreciated! \nThe XML is along the lines of: \nClientSend:\n<request_authenticate>\n<userid>23<userid>\n<password>7327372</password>\n</request_autenticate>\nServer:Parses, and calls DLL to verify user and pass are valid.\nServer sends:\n<response_authenticate>\n<status>OK</status>\n</response_authenticate>\n\nServer receives the request, usually under 150KB and send responses usually under 300KB\n\nOther request may have many fields, like product information, etc... but they are all along these lines. Client sends request, server parses and responds." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T18:44:31.403", "Id": "31813", "Score": "0", "body": "@AdamSurfari Added handler-oriented basic implementation" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T19:12:31.377", "Id": "19852", "ParentId": "19850", "Score": "11" } } ]
{ "AcceptedAnswerId": "19852", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T18:15:05.110", "Id": "19850", "Score": "6", "Tags": [ "c#", ".net", "networking" ], "Title": "C# Async Socket Server with Events" }
19850
<p>This code is for a spreadsheet that tracks weekly picks for NFL games. Four friends and I pick winners for every NFL game each week. Suppose there are 18 games being played this week; for each game, we all pick a winner, and also a level of confidence in that winner. We rank each game 1 to 18 based on our confidence-- so if a really good team plays a really bad team, we'll pick the good team for 18; if two teams are evenly matched, we'll pick a team for 1. (Each rank may only be used once each week per player.) If our team wins, we get the number of points we put on the game. If our team loses, we get no points.</p> <p>The spreadsheet displays all of the games each week, and we enter our rankings under our column in the row of the corresponding team (see spreadsheet), and on the same side as the team we want to win. Then when a game is over, we just have to enter "w" or "l" in the appropriate column, and all player's scores are automatically calculated. The code also attempts to inform us as soon as a player is eliminated from contention for top score of the week. </p> <p>Here is the currently implemented method of setting an elimination status:</p> <ol> <li>Start by taking the current scores into account.</li> <li>Consider each player vs each other player (aka opponent) one at a time.</li> <li>If there is ever a time when a player cannot beat one or more of his opponents, then he is eliminated.</li> </ol> <p>To check whether he can beat an opponent is tricky, though-- because the best case scenario for a player is not necessarily getting all of his picks right. Suppose they both pick the same team, but the opponent ranks that game higher-- it's actually better for the player (at least against this opponent) for the team he picked to lose.</p> <p>So instead, I calculate a best possible scenario score (again, for each player against each individual opponent). It starts with each player's current score. Then for all unplayed games, if the player and the opponent picked opposite sides, then the player's pick is added to his score (and the opponent gets no points in this scenario.) If they picked the same team, then we have to check who ranked the game higher; if the player ranked the game higher, then we add his points to his score, AND we add the points the opponent put on the game to the opponent's score. If the opponent picked higher, then nothing happens, since the best outcome is that that team loses and no one gets any points.</p> <p>At the end of all of that, if the best possible player score is smaller than the opponent's score in this scenario, then that player is eliminated.</p> <p>It does a few other things as well-- there's a comment section of the spreadsheet that detects the user who entered the comment, colors it appropriately, then shifts all the comments up one cell. </p> <p>Following is the code, and <a href="https://docs.google.com/spreadsheet/ccc?key=0AqSHv8u2wSNJdHRobV9QZDhhcXpWZjFaTktqQkJvQkE#gid=0" rel="nofollow">here is a link</a> to the spreadsheet into which we enter the information.</p> <pre><code>function onEdit(event){ var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var sh = event.source.getActiveSheet(); var r = event.source.getActiveRange(); var user = Session.getUser(); var lastCellModified = r.getA1Notation(); //only update the elimiantions/must win/lose scenarios if the w/l column is updated: if (lastCellModified == "A10" || lastCellModified == "A11" || lastCellModified == "A12" || lastCellModified == "A13" || lastCellModified == "A14" || lastCellModified == "A15" || lastCellModified == "A16" || lastCellModified == "A17" || lastCellModified == "A18" || lastCellModified == "A19" || lastCellModified == "A20" || lastCellModified == "A21" || lastCellModified == "A22" || lastCellModified == "A23" || lastCellModified == "A24" || lastCellModified == "A25"){ ss.getRange("D2:D7").clearContent(); //clear "elimination" status, so it doesn't have to be done manually if a wrong game outcome is entered. var sheetArray = []; sheetArray = ss.getRange("A1:N25").getValues() //A1: [0][0] //A2: [1][0] //B1: [0][1] // IN OTHER WORDS: [Y][X] AND REMEMBER Y IS THE NUMBER, X IS THE LETTER //BECUASE I AM DUMB HERE IS A HANDY ALPHANUMERIC CONVERSION CHART: //A B C D E F G H I J K L M N O P Q R S T U V W X Y Z //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 //ALSO BECAUSE IT IS FUNNY TO ME HERE IS A HANDY NUMERONUMERIC CONVERSION CHART: //COLUMN DESIRED : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 //ARRAY NUMBER TO ENTER:[0][1][2][3]4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 [21][22][23][24][25][26] //player values: Steve=1, Chris=2, Tyler=3, Billy=4, Drew=5 //go through each player one at a time for (var player=1; player&lt;6; player++){ if(player==1){var pScore=sheetArray[1][1];var leftPCol=2; var rightPCol=11; var elimRow=1} if(player==2){var pScore=sheetArray[2][1];var leftPCol=3; var rightPCol=10; var elimRow=2} if(player==3){var pScore=sheetArray[3][1];var leftPCol=4; var rightPCol=9; var elimRow=3} if(player==4){var pScore=sheetArray[4][1];var leftPCol=5; var rightPCol=8; var elimRow=4} if(player==5){var pScore=sheetArray[5][1];var leftPCol=1; var rightPCol=12; var elimRow=5} //Now we take select opponents one at a time for the current player for(var opponent=1; opponent&lt;6; opponent++){ if(player==opponent){break} if(opponent==1){var oScore=sheetArray[1][1]; var leftOCol=2; var rightOCol=11} if(opponent==2){var oScore=sheetArray[2][1]; var leftOCol=3; var rightOCol=10} if(opponent==3){var oScore=sheetArray[3][1]; var leftOCol=4; var rightOCol=9} if(opponent==4){var oScore=sheetArray[4][1]; var leftOCol=5; var rightOCol=8} if(opponent==5){var oScore=sheetArray[5][1]; var leftOCol=1; var rightOCol=12} //Set best possible scenario score initially to the player's current score, and opponent's to opponent's current score var bPScore=pScore; //toastMessage = toastMessage + "bPScore for player "+player+" is "+bPScore+", "; var bOScore=oScore; //toastMessage = toastMessage + "bOScore for opponent "+opponent+" is "+bOScore+", " for(var row=9; row&lt;24; row++){ //Iterate through game rows. if(sheetArray[row][0]==""){ //But only if the game has not been played yet //determine which team player and opponent picked and if they picked the same team. If their left column ISN'T empty, they picked the team on the left; //if it IS empty, they picked the team on the right. if(sheetArray[row][leftPCol]!=""){var pPick="left"} else{var pPick="right"} if(sheetArray[row][leftOCol]!=""){var oPick="left"} else{var oPick="right"} if(pPick==oPick){var sameTeam=true} else {var sameTeam=false} //get values of each pick if(pPick=="left"){var pV=sheetArray[row][leftPCol]} if(pPick=="right"){var pV=sheetArray[row][rightPCol]} if(oPick=="left"){var oV=sheetArray[row][leftOCol]} if(oPick=="right"){var oV=sheetArray[row][rightOCol]} //if both players picked the same team, add the picks to the scenario score if player picked higher than opponent if(sameTeam==true){ if(pV&gt;oV){bPScore=bPScore+pV;bOScore=bOScore+oV}//if player picked for more points, add each players' picks to their score }//if opponent picked for more points, don't do anything. //if both players picked opposite teams, add player's pick value to his total score if(sameTeam==false){bPScore=bPScore+pV} //don't change opponent's bp scenario score }//end of cycling through opponent } //After checking each unplayed game by the current player against a given opponent and assigning points based on a best case scenario, check if player is eliminated if (bPScore&lt;bOScore){sheetArray[elimRow][3]="ELIMINATED"}; } } // sheet.getRange("O26").setValue(toastMessage); //var elimArray = [[sheetArray[1][3]],[sheetArray[2][3]],[sheetArray[3][3]],[sheetArray[4][3]],[sheetArray[5][3]]]; //sheet.getRange("A26").setValue(sheetArray); //for debugging sheet.getRange("D2").setValue(sheetArray[1][3]); sheet.getRange("D3").setValue(sheetArray[2][3]); sheet.getRange("D4").setValue(sheetArray[3][3]); sheet.getRange("D5").setValue(sheetArray[4][3]); sheet.getRange("D6").setValue(sheetArray[5][3]); //end of ELIMINATIONS part of script } //This is for the moving comment box. It formats a cell with the colors of the commenter's favorite team, //and then moves all the comments up, just like in a chat room, leaving the bottom cell open. if (lastCellModified == "G8"){ var user = Session.getEffectiveUser().getEmail() switch (user){ case "fakeemail1@gmail.com":r.setBackgroundColor("MidnightBlue").setFontColor("LimeGreen");break; case "fakeemail2@gmail.com":r.setBackgroundColor("MidnightBlue").setFontColor("Orange");break; case "fakeemail3t@gmail.com":r.setBackgroundColor("Gray").setFontColor("DarkBlue");break; case "fakeemail4@gmail.com":r.setBackgroundColor("Orange").setFontColor("DarkBlue");break; case "fakeemail5@gmail.com":r.setBackgroundColor("Gray").setFontColor("DarkBlue");break; case "fakeemail6@gmail.com":r.setBackgroundColor("Green").setFontColor("Yellow");break; } ss.getRange("G2").copyFormatToRange(sheet, 7, 15, 1, 1);//sheet, column, columnEnd, row, rowEnd ss.getRange("G2").copyValuesToRange(sheet, 7, 15, 1, 1); ss.getRange("G3").copyFormatToRange(sheet, 7, 15, 2, 2); ss.getRange("G3").copyValuesToRange(sheet, 7, 15, 2, 2); ss.getRange("G4").copyFormatToRange(sheet, 7, 15, 3, 3); ss.getRange("G4").copyValuesToRange(sheet, 7, 15, 3, 3); ss.getRange("G5").copyFormatToRange(sheet, 7, 15, 4, 4); ss.getRange("G5").copyValuesToRange(sheet, 7, 15, 4, 4); ss.getRange("G6").copyFormatToRange(sheet, 7, 15, 5, 5); ss.getRange("G6").copyValuesToRange(sheet, 7, 15, 5, 5); ss.getRange("G7").copyFormatToRange(sheet, 7, 15, 6, 6); ss.getRange("G7").copyValuesToRange(sheet, 7, 15, 6, 6); ss.getRange("G8").copyFormatToRange(sheet, 7, 15, 7, 7); ss.getRange("G8").copyValuesToRange(sheet, 7, 15, 7, 7); ss.getRange("G8").clearContent().clearFormat; } } </code></pre> <p>Some specific things I'm interested in:</p> <ol> <li><p>Am I doing things efficiently? I don't care how fast the code runs (within reason) but I do want to know if I'm wasting a lot of my own time typing needless repetitions of code.</p></li> <li><p>It would really have helped me to take some of these little sections out of the main function, creating new functions and inserting calls to them. That would have helped me keep parentheses straight, and likely would have sped up the process of bug-fixing quite a bit. However, I kept having problems when I tried.</p></li> </ol> <p>You may have noticed that there is a problem with the way I am calculating eliminations-- it assumes that if a player could beat all other players in a one-on-one contest, given that everything goes exactly right, then the player is still alive. In fact, though, it is often impossible for a player to have something happen that is the best possible outcome against multiple opponents at once.</p> <p>(Example: Player has 5 points, Opponent1 has 3 points, Opponent2 has 5 points. One game remains, A vs B. Player picks A for 1 point. Opponent1 picks A for 4 points; Opponent2 picks B for 1 point. Individually, Player can beat Opponent1 if A loses, since he will finish with 5 and Opponent1 will finish with 3. And he can beat Opponent2 if A wins, because he will finish with 6 and Opponent2 will finish with 5. However, if A loses, then Opponent2 will actually get 1 point and win; if A wins, Opponent1 will get 4 points while Player will only get 1 point, finishing with 6 vs Opponent1's 7 points. So in reality, Player is already eliminated.)</p> <p>That's the problem I'm working on right now. And I wanted to kill 2 birds with 1 stone, so while checking for these scenarios where a player can't take on both opponents at once, I figured it would also be fun to highlight (in green) all games that a player MUST WIN to remain alive, as well as games that he MUST LOSE to remain alive (red), and of course games that he has to simultaneously win and lose, which cause him to be eliminated (highlighted in black).</p> <p>This is also <a href="https://docs.google.com/spreadsheet/ccc?key=0AqSHv8u2wSNJdGdibTdTT2pPdG1qVHhUX20zWl9CUmc#gid=0" rel="nofollow">on this spreadsheet</a>. You just need to go to "tools->script editor."</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T03:32:55.460", "Id": "31750", "Score": "0", "body": "Are you sure this code works correctly? Looking at your player/opponent comparison loops, the `if(player==opponent){break}` line means that (e.g.) \"player\" 3 will be compared to \"opponent\" 1 and 2, but player 1 will never be compared to any opponent, and cannot be eliminated, because `if (bPScore<bOScore){sheetArray[elimRow][3]=\"ELIMINATED\"};` will only eliminate the \"player\" in any cycle of the loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T15:12:41.390", "Id": "31752", "Score": "0", "body": "Actually, now that you mention it, Stuart...\n\nIt used to work perfectly, but in my effort to cut down on parentheses, I recently changed that part. It used to say \"if player != opponent {\" and then a close bracket way down at the end. And I recently did experience a problem with it breaking and not calculating eliminations properly for some players against some opponents, but it seemed like the problem cleared up again after that.\n\nThat may explain part of why the new function isn't working, too. Thanks for your comment." } ]
[ { "body": "<p>You can get rid of repetition in several places.</p>\n\n<p>The long if statement could be replaced with this:</p>\n\n<pre><code>if (lastCellModified.indexOf(['A10', 'A11', 'A12', 'A13', 'A14', 'A15', 'A16', \n 'A17', 'A18', 'A19', 'A20', 'A21', 'A22', 'A23', 'A25']) &gt; -1) {\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>if (lastCellModified.length == 3 &amp;&amp; lastCellModified &gt;= \"A10\" &amp;&amp; lastCellModified &lt;= \"A25\")\n</code></pre>\n\n<p>Setting variables for players and opponents can be reduced to:</p>\n\n<pre><code>var pScore = sheetArray[player][1];\nvar leftPCol = player % 5 + 1;\nvar rightPCol = 13 - leftPCol;\nvar pElimRow = player;\n</code></pre>\n\n<p>The list of <code>sheet.getRange('D2')</code> etc. could be replaced with a loop:</p>\n\n<pre><code>for (var i = 1; i &lt; 6; i++) {\n sheet.getRange(\"D\" + (i + 1)).setValue(sheetArray[i][3]);\n}\n</code></pre>\n\n<p>and similarly for the <code>ss.getRange...</code> list:</p>\n\n<pre><code>for (var i = 1; i &lt; 8; i++) {\n var range = ss.getRange('G' + (i + 1));\n range.copyFormatToRange(sheet, 7, 15, i, 1);\n range.copyValuesToRange(sheet, 7, 15, i, 1);\n}\n</code></pre>\n\n<p>See the full code with a few other changes <a href=\"http://jsfiddle.net/pnqax/1/\" rel=\"nofollow\">here</a></p>\n\n<p><strong>EDIT</strong>: I looked at this in a bit more detail. Ultimately what I think you need is to go through every possible combination of outcomes for the remaining games, and check who is the winner under each scenario, and eliminate the players who are not winners under any scenarios. (There might be some shortcut method, but as you have already noted, your solution of comparing pairs of players does not quite do it.) This does involve looking at 2 to the power of N scenarios where N is the number of remaining games. That should be manageable for, say, 16 games, although it may get a little slow. I've altered the script to do this <a href=\"http://jsfiddle.net/pnqax/8/\" rel=\"nofollow\">here</a> but couldn't figure out how to test it.</p>\n\n<p>Whether you use this or not, I recommend using the first part of that code, which reads the players' current scores, their picks, and their bets, into arrays with meaningful names at the beginning. This simplifies the rest of the code a lot as you can deal with those arrays instead of having to keep thinking about what reference you need in the spreadsheet.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T15:20:22.447", "Id": "31753", "Score": "0", "body": "Wow, it looks like there is a lot of great stuff in there that I can learn from. It'll probably take me a couple weeks to completely understand some of the things you've done, but believe me, I will keep at it.\n\nIn addition, I was really surprised by how you calculated eliminations. I had tried asking around previously but didn't get an answer-- the idea of calculating all possible remaining scenarios was appealing to me, of course, but it seemed like it would be really slow. I know very little of computer science, but I'm excited to know that this is doable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T15:46:13.690", "Id": "31754", "Score": "0", "body": "Usually javascript is slow when inputting/outputting (e.g. to a webpage or in this case a spreadsheet) but fast when just comparing numbers in arrays. Going through a few hundred thousand values should take less than a second generally. But obviously the number of possible outcomes increases exponentially with the number of games. Anyway try to test it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T15:56:08.857", "Id": "31755", "Score": "0", "body": "I have to run to work, but after a brief test, I do come across a few problems. However, I lost connection to the Google Server at one point (even while other sites were working), and maybe the problems are not in the code but somewhere else. Anyway, after trying the updated code, the commenting section stopped working, and the eliminations updated regardless of what cell I edited. Eliminations worked sporadically, which I am chalking up to the connection issue. I'll re-try it tonight, assuming I get off work at a reasonable hour. Thanks again for your help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T16:59:54.503", "Id": "31757", "Score": "0", "body": "there was a bug - the if statement towards the top should read `if (r.getColumn() == 1 && r.getRow() >= 10 && r.getRow() <= 25)` (remove the !)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-23T07:12:32.853", "Id": "31770", "Score": "0", "body": "Made another fix: towards the end `range.copyFormatToRange(sheet, 7, 15, i, 1);` should be `range.copyFormatToRange(sheet, 7, 15, i, i);`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T03:45:00.120", "Id": "19865", "ParentId": "19856", "Score": "3" } }, { "body": "<p>Few general notes on the code</p>\n\n<ol>\n<li><p>The method <code>onEdit</code> is doing too many things which is making the code difficult to read. I would prefer to break the entire function and distribute responsibilities. The structure would look something like this (this is just an example) -</p>\n\n<pre><code>var Game = {};\n\nGame.setStatus = {\n validateInput: function () {\n },\n isLastCallModified: function() {\n },\n update: function() {\n },\n moveBox: function() {\n }\n};\n</code></pre></li>\n<li><p>you have check for boolean values in this way <code>if (sameTeam == true)</code> and <code>if (sameTeam == false)</code> which is not the right way. It should be <code>if (sameTeam)</code> and <code>if (!sameTeam)</code></p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T13:45:26.580", "Id": "19870", "ParentId": "19856", "Score": "1" } }, { "body": "<p>for readability replace</p>\n\n<pre><code>var ss = ... ;\nvar sheet = ... ;\nvar sh = ... ;\nvar r = ... ;\nvar user = ... ;\nvar lastCellModified = ... ;\n</code></pre>\n\n<p>with </p>\n\n<pre><code>var ss = ... ,\n sheet = ... ,\n sh = ... ,\n r = ... ,\n user = ... ,\n lastCellModified = ... ,\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T12:34:39.777", "Id": "20119", "ParentId": "19856", "Score": "1" } } ]
{ "AcceptedAnswerId": "19870", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T22:08:19.510", "Id": "19856", "Score": "4", "Tags": [ "javascript" ], "Title": "Tracking weekly picks for NFL games" }
19856
<p>I'm currently using a scientific information management system that employs a RESTful API. I've never used this API with PHP, and I had a hard time finding best practice examples online. After some reading and experimenting, I came up with the following proof-of-concept procedure to retrieve data from the API and then upload the XML object, slightly modified, in order to change information in the system.</p> <p>I'm most concerned with PHP best practices here: is my PHP efficient, robust, and secure? Is there any code I can remove or make more efficient? I'm using PHP v5.3.8</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;?php $uriPrefix = 'http://[user:pass]@[path_to_web_app:port]/api/v2/'; //Open up a connection to the API //for the container: $containerSuffix = 'containers/27-95'; $containerUri = $uriPrefix . $containerSuffix; $containerCurl = curl_init($containerUri); //for the sample: $sampleSuffix = 'samples/DOR6A12'; $sampleUri = $uriPrefix . $sampleSuffix; $sampleCurl = curl_init($sampleUri); //API-specific settings curl_setopt($containerCurl, CURLOPT_RETURNTRANSFER, true); curl_setopt($sampleCurl, CURLOPT_RETURNTRANSFER, true); //get the yummy data $containerResult = curl_exec($containerCurl); $containerXml = new SimpleXMLElement($containerResult); $sampleResult = curl_exec($sampleCurl); $sampleXml = new SimpleXMLElement($sampleResult); //close the API connection curl_close($containerCurl); curl_close($sampleCurl); echo '&lt;h2&gt;Some XML for a LIMS Container:&lt;/h2&gt;'; echo htmlentities($containerXml-&gt;asXML()); echo '&lt;h2&gt;Some XML for a LIMS Sample:&lt;/h2&gt;'; echo htmlentities($sampleXml-&gt;asXML()); //Now let's infer the project ID for the sample from the XML result $limsId = $sampleXml-&gt;project['limsid']; echo "&lt;p&gt;The project ID for the sample is $limsId&lt;/p&gt;"; //Now let's change the sample name $newName = 'New Sample Name'; $oldName = (string)$sampleXml-&gt;name; $sampleXml-&gt;name = $newName; $changeSampleCurl = curl_init($sampleUri); curl_setopt($changeSampleCurl, CURLOPT_RETURNTRANSFER, true); curl_setopt($changeSampleCurl, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($changeSampleCurl, CURLOPT_POSTFIELDS,$sampleXml-&gt;asXML()); $changeSampleResult = curl_exec($changeSampleCurl); echo '&lt;h2&gt;The submitted XML&lt;/h2&gt;'; echo htmlentities($changeSampleResult); curl_close($changeSampleCurl); echo "&lt;p&gt;The old sample name was $oldName&lt;/p&gt;"; echo "&lt;p&gt;It should now be $newName&lt;/p&gt;"; ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T15:17:14.420", "Id": "31805", "Score": "0", "body": "There's not really much that I've noticed. Though I should warn I'm unfamiliar with REST and cURL. You might consider creating a config file for your suffixes and prefixes, and you might want to escape your HTML rather than echo it; but beyond that, there isn't much here. This is a relatively simple application." } ]
[ { "body": "<p>The most obvious omission is error handling. You don't handle curl errors or xml parsing errors.</p>\n\n<p>A REST api is like any other external service you might use in your application (such as a database). You might consider creating a client library for it (first check to see if one does not already exist for the service in question). Example usage with the implementation details neatly tucked away:</p>\n\n<pre><code>&lt;?php\n//read these values from your configuration and set here\n$connection = array(\n 'user' =&gt; '',\n 'pass' =&gt; '',\n 'baseUrl' =&gt; '',\n 'version' =&gt; ''\n);\ntry {\n $client = new FooClient($connection);\n $container = $client-&gt;getContainer('27-95');\n if ($container) {\n //do something with the fetched container\n }\n\n $sample = $client-&gt;getSample('DOR6A12');\n if ($sample) {\n $sample-&gt;setName('new name');\n $client-&gt;saveSample($sample);\n }\n} catch (FooClientException $e) {\n //handle accordingly\n}\n</code></pre>\n\n<p>I'm assuming that the client will return mapped objects for the getContainer and getSample methods. These mapped objects would be instances of php classes which are part of this client library. The xml responses returned by the service would be mapped to to these returned objects. That way, you are not directly dealing with the xml here, rather those details are dealt with in your client library (errors are handled there too with an appropriate exception being thrown if need be).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-07T02:45:49.837", "Id": "32328", "Score": "0", "body": "Thanks, the feedback and examples were extremely helpful! That's a lot of useful info in a small space." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T15:51:35.710", "Id": "19899", "ParentId": "19859", "Score": "1" } } ]
{ "AcceptedAnswerId": "19899", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T23:02:54.477", "Id": "19859", "Score": "1", "Tags": [ "php", "api" ], "Title": "Accessing a REST API with PHP" }
19859
<p>I am looking to submit the following code (adapted to fit into <code>java.util</code> obviously) which <a href="https://gist.github.com/4356621">significantly improves performance</a> and reduces useless allocations of <code>java.util.UUID</code>. Help me find the bugs and stupidity before I submit myself to the judgment of the JDK maintainers! :-)</p> <pre><code> benchmark instances Bytes ns linear runtime JdkUuidFromString 51.00 1544.0 608.2 ============================== NessUuidFromString 2.00 72.0 179.1 ======== JdkUuidToString 31.00 1720.0 321.4 =============== NessUuidToString 3.00 200.0 51.5 == </code></pre> <p>FromString gets a 3x speedup and 1/25th the object allocations. ToString gets a 6x speedup and 1/10th of the object allocations.</p> <p>And here's the code:</p> <pre><code>/** * A class that provides an alternate implementation of {@link * UUID#fromString(String)} and {@link UUID#toString()}. * * &lt;p&gt; The version in the JDK uses {@link String#split(String)} * which does not compile the regular expression that is used for splitting * the UUID string and results in the allocation of multiple strings in a * string array. We decided to write {@link NessUUID} when we ran into * performance issues with the garbage produced by the JDK class. * */ public class NessUUID { private NessUUID() {} private static final int NUM_ALPHA_DIFF = 'A' - '9' - 1; private static final int LOWER_UPPER_DIFF = 'a' - 'A'; // FROM STRING public static UUID fromString(String str) { int dashCount = 4; int [] dashPos = new int [6]; dashPos[0] = -1; dashPos[5] = str.length(); for (int i = str.length()-1; i &gt;= 0; i--) { if (str.charAt(i) == '-') { if (dashCount == 0) { throw new IllegalArgumentException("Invalid UUID string: " + str); } dashPos[dashCount--] = i; } } if (dashCount &gt; 0) { throw new IllegalArgumentException("Invalid UUID string: " + str); } long mostSigBits = decode(str, dashPos, 0) &amp; 0xffffffffL; mostSigBits &lt;&lt;= 16; mostSigBits |= (decode(str, dashPos, 1) &amp; 0xffffL); mostSigBits &lt;&lt;= 16; mostSigBits |= (decode(str, dashPos, 2) &amp; 0xffffL); long leastSigBits = (decode(str, dashPos, 3) &amp; 0xffffL); leastSigBits &lt;&lt;= 48; leastSigBits |= (decode(str, dashPos, 4) &amp; 0xffffffffffffL); return new UUID(mostSigBits, leastSigBits); } private static long decode(final String str, final int [] dashPos, final int field) { int start = dashPos[field]+1; int end = dashPos[field+1]; if (start &gt;= end) { throw new IllegalArgumentException("Invalid UUID string: " + str); } long curr = 0; for (int i = start; i &lt; end; i++) { int x = getNibbleFromChar(str.charAt(i)); curr &lt;&lt;= 4; if (curr &lt; 0) { throw new NumberFormatException("long overflow"); } curr |= x; } return curr; } static int getNibbleFromChar(final char c) { int x = c - '0'; if (x &gt; 9) { x -= NUM_ALPHA_DIFF; // difference between '9' and 'A' if (x &gt; 15) { x -= LOWER_UPPER_DIFF; // difference between 'a' and 'A' } if (x &lt; 10) { throw new IllegalArgumentException(c + " is not a valid character for an UUID string"); } } if (x &lt; 0 || x &gt; 15) { throw new IllegalArgumentException(c + " is not a valid character for an UUID string"); } return x; } // TO STRING public static String toString(UUID uuid) { return toString(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits()); } /** Roughly patterned (read: stolen) from java.util.UUID and java.lang.Long. */ public static String toString(long msb, long lsb) { char[] uuidChars = new char[36]; digits(uuidChars, 0, 8, msb &gt;&gt; 32); uuidChars[8] = '-'; digits(uuidChars, 9, 4, msb &gt;&gt; 16); uuidChars[13] = '-'; digits(uuidChars, 14, 4, msb); uuidChars[18] = '-'; digits(uuidChars, 19, 4, lsb &gt;&gt; 48); uuidChars[23] = '-'; digits(uuidChars, 24, 12, lsb); return new String(uuidChars); } private static void digits(char[] dest, int offset, int digits, long val) { long hi = 1L &lt;&lt; (digits * 4); toUnsignedString(dest, offset, digits, hi | (val &amp; (hi - 1)), 4); } private final static char[] DIGITS = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' }; private static void toUnsignedString(char[] dest, int offset, int len, long i, int shift) { int charPos = len; int radix = 1 &lt;&lt; shift; long mask = radix - 1; do { dest[offset + --charPos] = DIGITS[(int)(i &amp; mask)]; i &gt;&gt;&gt;= shift; } while (i != 0 &amp;&amp; charPos &gt; 0); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T16:52:43.837", "Id": "35950", "Score": "2", "body": "In Java 7 [`String.split()`](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/String.java#String.split%28java.lang.String%2Cint%29) has a \"fastpath\" improvement for single character patterns that don't include meta chars. In this case, splitting on '-' will take the fastpath. This fastpath avoids using the regex engine and improves performance in trivial spilts. Still, good to see these improvements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T08:05:17.730", "Id": "48034", "Score": "0", "body": "`toString(long msb, long lsb)` should be private." } ]
[ { "body": "<p>I could not get Caliper running, but hacked my own test:</p>\n\n<p>My initial results were:</p>\n\n<pre><code>warmup\nJdkFrom: 1787.38 JdkTo: 635.12 NessFrom: 460.15 NessTo: 183.67 [-4552303853801426784, 69220000, -4552303853801426784, 69220000]\nReal Run\nJdkFrom: 1415.68 JdkTo: 553.28 NessFrom: 426.29 NessTo: 94.69 [-4552303853801426784, 69220000, -4552303853801426784, 69220000]\nJdkFrom: 1394.24 JdkTo: 387.14 NessFrom: 340.78 NessTo: 59.33 [-4552303853801426784, 69220000, -4552303853801426784, 69220000]\nJdkFrom: 1378.38 JdkTo: 339.20 NessFrom: 325.73 NessTo: 59.20 [-4552303853801426784, 69220000, -4552303853801426784, 69220000]\nJdkFrom: 1381.61 JdkTo: 334.28 NessFrom: 389.30 NessTo: 59.09 [-4552303853801426784, 69220000, -4552303853801426784, 69220000]\n</code></pre>\n\n<p>So, at face value, yes, your algorithm is nicely faster.</p>\n\n<p>As for the code review, I have some comments:</p>\n\n<h1>fromString()</h1>\n\n<ol>\n<li>I don't like that you ignore the required format for UUID's, essentially you say if it has 4 dashes it's cool, but, really, the number of digites between dashes is significant, and you ignore that.</li>\n<li>I feel that you should be calculating the long bits at the same time as you are validating and counting the dashes. Repeating the loops afterwards seems redundant.</li>\n<li>If you are looking for raw performance, a trick I have found out is that lookup tables make a big difference... I will show an example in a bit.</li>\n</ol>\n\n<h1>toString()</h1>\n\n<ol>\n<li>I don't like the public <code>toString(long,long)</code> method. This is not 'symmetrical'. Only the toString(UUID) should be public.</li>\n<li>The <code>DIGITS</code> code appears to be designed to satisfy many different radices (radixes, what's the plural?). This makes it a little bulky for this special case.</li>\n<li>There are too many levels of method calls. It can be much shallower.</li>\n</ol>\n\n<hr>\n\n<h1>Consider:</h1>\n\n<p>I had a hack at this and decided I could do better.... consider the following results:</p>\n\n<pre><code>warmup\nJdkFrom: 1929.14 JdkTo: 542.10 NessFrom: 270.43 NessTo: 175.71 [2254274162472357232, 70459000, 2254274162472357232, 70459000]\nReal Run\nJdkFrom: 1569.85 JdkTo: 404.93 NessFrom: 249.37 NessTo: 45.94 [2254274162472357232, 70459000, 2254274162472357232, 70459000]\nJdkFrom: 1528.79 JdkTo: 279.55 NessFrom: 114.74 NessTo: 44.71 [2254274162472357232, 70459000, 2254274162472357232, 70459000]\nJdkFrom: 1657.85 JdkTo: 271.24 NessFrom: 118.20 NessTo: 44.43 [2254274162472357232, 70459000, 2254274162472357232, 70459000]\nJdkFrom: 1563.52 JdkTo: 273.69 NessFrom: 140.96 NessTo: 46.46 [2254274162472357232, 70459000, 2254274162472357232, 70459000]\n</code></pre>\n\n<p>This is almost three times faster than <strong>your</strong> version for the fromString, and another 0.2-times faster than <strong>your</strong> toString.</p>\n\n<p>Here is the code that is (in my experience) about as fast as you can get with Java:</p>\n\n<pre><code>package uuid;\n\nimport java.util.Arrays;\nimport java.util.UUID;\n\n/**\n * A class that provides an alternate implementation of {@link\n * UUID#fromString(String)} and {@link UUID#toString()}.\n *\n * &lt;p&gt; The version in the JDK uses {@link String#split(String)}\n * which does not compile the regular expression that is used for splitting\n * the UUID string and results in the allocation of multiple strings in a\n * string array. We decided to write {@link NessUUID} when we ran into\n * performance issues with the garbage produced by the JDK class.\n *\n */\npublic class NessUUID {\n private NessUUID() {}\n\n // lookup is an array indexed by the **char**, and it has\n // valid values set with the decimal value of the hex char.\n private static final long[] lookup = buildLookup();\n private static final int DASH = -1;\n private static final int ERROR = -2;\n private static final long[] buildLookup() {\n long [] lu = new long[128];\n Arrays.fill(lu, ERROR);\n lu['0'] = 0;\n lu['1'] = 1;\n lu['2'] = 2;\n lu['3'] = 3;\n lu['4'] = 4;\n lu['5'] = 5;\n lu['6'] = 6;\n lu['7'] = 7;\n lu['8'] = 8;\n lu['9'] = 9;\n lu['a'] = 10;\n lu['b'] = 11;\n lu['c'] = 12;\n lu['d'] = 13;\n lu['e'] = 14;\n lu['f'] = 15;\n lu['A'] = 10;\n lu['B'] = 11;\n lu['C'] = 12;\n lu['D'] = 13;\n lu['E'] = 14;\n lu['F'] = 15;\n lu['-'] = DASH;\n return lu;\n }\n\n // FROM STRING\n\n public static UUID fromString(final String str) {\n final int len = str.length();\n if (len != 36) {\n throw new IllegalArgumentException(\"Invalid UUID string (expected to be 36 characters long)\");\n }\n final long[] vals = new long[2];\n int shift = 60;\n int index = 0;\n for (int i = 0; i &lt; len; i++) {\n final int c = str.charAt(i);\n if (c &gt;= lookup.length || lookup[c] == ERROR) {\n throw new IllegalArgumentException(\"Invalid UUID string (unexpected '\" + str.charAt(i) + \"' at position \" + i + \" -&gt; \" + str + \" )\");\n }\n\n if (lookup[c] == DASH) {\n if ((i - 8) % 5 != 0) {\n throw new IllegalArgumentException(\"Invalid UUID string (unexpected '-' at position \" + i + \" -&gt; \" + str + \" )\");\n }\n continue;\n }\n vals[index] |= lookup[c] &lt;&lt; shift;\n shift -= 4;\n if (shift &lt; 0) {\n shift = 60;\n index++;\n }\n }\n return new UUID(vals[0], vals[1]);\n }\n\n // TO STRING\n\n // recode is 2-byte arrays representing the hex representation of every byte value (all 256)\n private static final char[][] recode = buildByteBlocks();\n private static char[][] buildByteBlocks() {\n final char[][] ret = new char[256][];\n for (int i = 0; i &lt; ret.length; i++) {\n ret[i] = String.format(\"%02x\", i).toCharArray();\n }\n return ret;\n }\n\n public static final String toString(final UUID uuid) {\n long msb = uuid.getMostSignificantBits();\n long lsb = uuid.getLeastSignificantBits();\n char[] uuidChars = new char[36];\n int cursor = uuidChars.length;\n while (cursor &gt; 24 ) {\n cursor -= 2;\n System.arraycopy(recode[(int)(lsb &amp; 0xff)], 0, uuidChars, cursor, 2);\n lsb &gt;&gt;&gt;= 8;\n }\n uuidChars[--cursor] = '-';\n while (cursor &gt; 19) {\n cursor -= 2;\n System.arraycopy(recode[(int)(lsb &amp; 0xff)], 0, uuidChars, cursor, 2);\n lsb &gt;&gt;&gt;= 8;\n }\n uuidChars[--cursor] = '-';\n while (cursor &gt; 14) {\n cursor -= 2;\n System.arraycopy(recode[(int)(msb &amp; 0xff)], 0, uuidChars, cursor, 2);\n msb &gt;&gt;&gt;= 8;\n }\n uuidChars[--cursor] = '-';\n while (cursor &gt; 9) {\n cursor -= 2;\n System.arraycopy(recode[(int)(msb &amp; 0xff)], 0, uuidChars, cursor, 2);\n msb &gt;&gt;&gt;= 8;\n }\n uuidChars[--cursor] = '-';\n while (cursor &gt; 0) {\n cursor -= 2;\n System.arraycopy(recode[(int)(msb &amp; 0xff)], 0, uuidChars, cursor, 2);\n msb &gt;&gt;&gt;= 8;\n }\n return new String(uuidChars);\n }\n\n}\n</code></pre>\n\n<p>For your amusement, here's my test class (no Caliper, I know):</p>\n\n<pre><code>package uuid;\n\nimport java.util.Arrays;\nimport java.util.UUID;\n\n\npublic class PerformanceComparison \n{\n\n private final int N_UUIDS = 1000;\n private final UUID[] testUuids = new UUID[N_UUIDS];\n private final String[] testStrings = new String[N_UUIDS];\n\n public void setup () {\n for (int i = 0; i &lt; N_UUIDS; i++)\n {\n testUuids[i] = UUID.randomUUID();\n testStrings[i] = testUuids[i].toString();\n }\n }\n\n public static void main(String[] args) {\n PerformanceComparison pc = new PerformanceComparison();\n\n final UUID uuidj = UUID.randomUUID();\n String valj = uuidj.toString();\n String valn = NessUUID.toString(uuidj);\n UUID uuidn = NessUUID.fromString(valn);\n if (!valj.equals(valn)) {\n throw new IllegalStateException(\"Illegal conversion\");\n }\n if (!uuidj.equals(uuidn)) {\n throw new IllegalStateException(\"Illegal conversion\");\n }\n\n pc.setup();\n final int reps = 1000000;\n\n System.out.println(\" warmup\");\n pc.runAll(reps);\n System.out.println(\" Real Run\");\n pc.runAll(reps);\n pc.runAll(reps);\n pc.runAll(reps);\n pc.runAll(reps);\n\n }\n\n private final void runAll(final int reps) {\n long[] accum = new long[4];\n System.out.printf(\" JdkFrom: %6.2f JdkTo: %6.2f NessFrom: %6.2f NessTo: %6.2f %s\\n\", \n timeJdkUuidFromString(reps, accum, 0) / 1000000.0,\n timeJdkUuidToString(reps, accum, 1) / 1000000.0,\n timeNessUuidFromString(reps, accum, 2) / 1000000.0,\n timeNessUuidToString(reps, accum, 3) / 1000000.0,\n Arrays.toString(accum));\n }\n\n public long timeJdkUuidFromString(int reps, long[] accum2, int j)\n {\n long accum = 0;\n long start = System.nanoTime();\n for (int i = 0; i &lt; reps; i++)\n {\n accum += UUID.fromString(testStrings[i % N_UUIDS]).getMostSignificantBits();\n }\n accum2[j] = accum;\n return System.nanoTime() - start;\n }\n\n public long timeJdkUuidToString(int reps, long[] accum2, int j)\n {\n long accum = 0;\n long start = System.nanoTime();\n for (int i = 0; i &lt; reps; i++)\n {\n accum += testUuids[i % N_UUIDS].toString().charAt(0);\n }\n accum2[j] = accum;\n return System.nanoTime() - start;\n }\n\n public long timeNessUuidFromString(int reps, long[] accum2, int j)\n {\n long accum = 0;\n long start = System.nanoTime();\n for (int i = 0; i &lt; reps; i++)\n {\n accum += NessUUID.fromString(testStrings[i % N_UUIDS]).getMostSignificantBits();\n }\n accum2[j] = accum;\n return System.nanoTime() - start;\n }\n\n public long timeNessUuidToString(int reps, long[] accum2, int j)\n {\n\n long accum = 0;\n long start = System.nanoTime();\n for (int i = 0; i &lt; reps; i++)\n {\n accum += NessUUID.toString(testUuids[i % N_UUIDS]).charAt(0);\n }\n accum2[j] = accum;\n return System.nanoTime() - start;\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-19T15:34:31.210", "Id": "512339", "Score": "0", "body": "See my answer below for something even faster. Your logic in iterating through the string characters results in a lot of extra operations that impede performance. Also, use of the modulus operator hurts performance. It is a lot quicker to just hardcode all the indexes used in the UUID string." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T05:39:01.370", "Id": "35899", "ParentId": "19860", "Score": "13" } }, { "body": "<p>Improvements to the JDK have made the JDK's <code>UUID.toString()</code> much more performant. It now (JDK 11) significantly outperforms any of these homegrown methods.\nUnforntunately, the built-in <code>UUID.fromString()</code> still performs pretty poorly. The OP and @rolfl's solutions are faster than the JDK's, but there is still room for improvement. Switching to a two char lookup table (1 byte) significantly improves performance (at the cost of some more memory). Two characters appears to be the sweet spot. In my tests, attempting to use a table for more than two hex characters at a time did not improve performance any further.</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.Arrays;\nimport java.util.UUID;\n\n/**\n * Unfortunately, the built-in java UUID.fromString(name) is not very efficient.\n * This method is approximately 80% faster. The only cost is the static lookup\n * table, which consumes around 52K of memory. Useful for very high throughput\n * applications.\n */\npublic class UUIDUtils {\n\n // Lookup table of all possible byte values. \n // Type of array needs to be short in order to be able to use -1 for invalid values.\n // We can also use a byte array of nibble values (single hex character), but that\n // is about 30% slower - although it does consume significantly less memory.\n private static final short[] HEX_LOOKUP = new short[indexVal('f', 'f') + 1];\n static {\n Arrays.fill(HEX_LOOKUP, (short) -1);\n char[] chars = {\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', \n 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f' };\n for (char c : chars) {\n for (char c1 : chars) {\n int i = indexVal(c, c1);\n HEX_LOOKUP[i] = (short) (Character.digit(c, 16) &lt;&lt; 4 | Character.digit(c1, 16));\n }\n }\n }\n\n public static UUID fromStringFast(String string) {\n if (string.length() != 36) {\n throw new IllegalArgumentException(&quot;Invalid length for UUID string: &quot; + string + &quot; :&quot; + string.length());\n }\n long msb = toByte(string.charAt(0), string.charAt(1));\n msb = msb &lt;&lt; 8 | toByte(string.charAt(2), string.charAt(3));\n msb = msb &lt;&lt; 8 | toByte(string.charAt(4), string.charAt(5));\n msb = msb &lt;&lt; 8 | toByte(string.charAt(6), string.charAt(7));\n checkDash(string.charAt(8));\n msb = msb &lt;&lt; 8 | toByte(string.charAt(9), string.charAt(10));\n msb = msb &lt;&lt; 8 | toByte(string.charAt(11), string.charAt(12));\n checkDash(string.charAt(13));\n msb = msb &lt;&lt; 8 | toByte(string.charAt(14), string.charAt(15));\n msb = msb &lt;&lt; 8 | toByte(string.charAt(16), string.charAt(17));\n checkDash(string.charAt(18));\n long lsb = toByte(string.charAt(19), string.charAt(20));\n lsb = lsb &lt;&lt; 8 | toByte(string.charAt(21), string.charAt(22));\n checkDash(string.charAt(23));\n lsb = lsb &lt;&lt; 8 | toByte(string.charAt(24), string.charAt(25));\n lsb = lsb &lt;&lt; 8 | toByte(string.charAt(26), string.charAt(27));\n lsb = lsb &lt;&lt; 8 | toByte(string.charAt(28), string.charAt(29));\n lsb = lsb &lt;&lt; 8 | toByte(string.charAt(30), string.charAt(31));\n lsb = lsb &lt;&lt; 8 | toByte(string.charAt(32), string.charAt(33));\n lsb = lsb &lt;&lt; 8 | toByte(string.charAt(34), string.charAt(35));\n\n return new UUID(msb, lsb);\n }\n\n private static final int toByte(char hi, char low) {\n try {\n short b = HEX_LOOKUP[indexVal(hi, low)];\n if (b == -1) {\n throw new IllegalArgumentException(&quot;Invalid hex chars: &quot; + hi + low);\n }\n return b;\n } catch (IndexOutOfBoundsException e) {\n throw new IllegalArgumentException(&quot;Invalid hex chars: &quot; + hi + low);\n }\n }\n\n private static final int indexVal(char hi, char low) {\n return hi &lt;&lt; 8 | low;\n }\n \n private static void checkDash(char c) {\n if(c != '-') {\n throw new IllegalArgumentException(&quot;Expected '-', but found '&quot; + c + &quot;'&quot;);\n }\n }\n}\n</code></pre>\n<p>Even more performance can be squeezed out by removing all error checking. (Removing all error checking would also allow <code>byte[]</code> to be used for the lookup table instead of <code>short[]</code>, which also saves memory). This would increase throughput by about 25%. However, that is not advisable unless you can guarantee the validity of your input via some other means.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-19T15:30:44.567", "Id": "259727", "ParentId": "19860", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T23:51:11.950", "Id": "19860", "Score": "31", "Tags": [ "java", "performance" ], "Title": "Improving the Java UUID class performance" }
19860
<p>I've put together this simple fetcher for text data (which I just copy and pasted from a flight info website) - it takes in text data, and spits out an array of objects containing values for each property of each flight it finds. I thought it would be a good accompaniment exercise to "Eloquent Javascript: Chapter 3, Data Structures: Objects and Arrays."</p> <ul> <li>I'm looking for ways in which I should condense the functions, or possibly merge their tasks. I don't think there's a whole lot that can be shared amongst each fetch function, however.</li> <li>I think there may be a more simple way of noting the index of each item (found from the specific fetcher function), and then passing that on to the next fetcher function, but I'm not sure if that applies for each property of the flight, and I'm not sure what pattern I would use for that.</li> <li>General code critique or advice?</li> </ul> <p>*<strong><em>Note: I held off on adding fetchers for timeSched, status, and onSched until I get some feedback here, thanks! *</em></strong> </p> <pre><code>var flightObject = { /* We assume our text value comes in this form: airlineCode airlineName destAbbrev dest timeSched status onSched */ text: "9E 3801 Pinnacle Airlines (MSP) Minneapolis 3:38 PM Landed On-time\nDL 3801 Delta Air Lines (MSP) Minneapolis 3:38 PM Landed On-time\n1I 131 Netjets Aviation (MEM) Memphis 3:06 PM Scheduled On-time\n1I 880 Netjets Aviation (HPN) Westchester County 3:06 PM En Route On-time\nRAX 308 Royal Air Freight, Inc. (FDY) Findlay 3:06 PM Landed On-time\nWN 627 Southwest Airlines (FLL) Fort Lauderdale 3:16 PM En Route On-time\nWN 2541 Southwest Airlines (SAT) San Antonio 3:35 PM En Route Delayed\nWN 1939 Southwest Airlines (LAS) Las Vegas 3:35 PM En Route On-time\nFIV 540 Citationshares (PWK) Chicago 3:10 PM Scheduled On-time", /* Here is our function that grabs the Flight Number (airlineCode), Airline (airlineName), Destination Abbreviation (destAbbrev), and Destination Long Title (dest), Scheduled Time (timeSched), Status of Flight (stat), and whether flight is on time (onSched) */ extractFlight: function() { /* Split paragraphs into lines */ var paragraphs = this.text.split("\n"); /* Get index for parenthesis which will help in finding destAbbrev note: start at i = 3 because we know it can't occur earlier due to data's nature. */ function getParenthIndex(){ for( var i = 3 ; i &lt; words.length ; i++ ) { var word = words[i]; if (word.charAt(0) === "(") { return i; } } } function getAirlineName(){ var parenthIndex = getParenthIndex(); var airlineName = ""; /* note: we start for loop at i = 2 because we know it can't occur earlier due to data's nature. */ for( var i = 2; i &lt; parenthIndex; i++ ) { var word = words[i]; if (i === parenthIndex - 1) { return airlineName += word; } else { airlineName += word + " "; } } } /* Grab destination abbreviation using index of word that starts with parenthesis as guide */ function getDestAbbrev(){ var parenthIndex = getParenthIndex(); return words[parenthIndex]; } /* Grab destination using index of word that starts with parenthesis as guide, while searching for number to know when to stop. */ function getDest(){ var parenthIndex = getParenthIndex(); var dest = ""; for( var i = parenthIndex + 1 ; i &lt; words.length ; i++ ) { var word = words[i]; var re = /\d/; if (!re.test(word)){ if (i === parenthIndex + 1) { dest+= word; } else { dest += " " + word; } } else { return dest; } } } /* Take array and add flight objects by looping through each paragraph and grabbing each property value we're interested in. */ var flights = []; for( var i = 0 ; i &lt; paragraphs.length ; i++ ) { var paragraph = paragraphs[i]; var words = paragraph.split(" "); /* Now we find the flight number which is the 1st and 2nd word */ var flightCode = words[0] + " " + words[1]; var flightCodeConden = words[0] + words[1]; var airlineName = getAirlineName(); var destAbbrev = getDestAbbrev(); var dest = getDest(); flights[flightCodeConden] = { "flightCode" : flightCode, "airlineName" : airlineName, "destAbbrev" : destAbbrev, "dest" : dest }; } console.log(flights); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T02:19:14.917", "Id": "31747", "Score": "0", "body": "maybe you're doing it like this for a particular reason? You could simplify a lot using `slice` and `join` methods on `words`." } ]
[ { "body": "<p>The individual flights here are good candidates for being individual objects, along the following lines. I take a slightly different approach of first identifying the index of the flight code and the index of the date, and then using that to parse all the other information using <code>words.slice</code>. That simplifies things so much you don't have to worry about passing indices around between different functions (though if you did need to do that as your parser gets more complicated, you could do so by making the relevant indices properties of the Flight object).</p>\n\n<pre><code>function Flight(text) {\n var ch, i, words = text.split(' '), parenthIndex, dateIndex;\n for (i = 3; i &lt; words.length; i++) {\n ch = words[i].charAt(0);\n if (ch === \"(\") {\n parenthIndex = i;\n }\n else if (ch &gt;= '0' &amp;&amp; ch &lt;= '9') {\n dateIndex = i;\n break;\n }\n }\n this.airlineName = words.slice(2, parenthIndex).join(' ');\n this.destAbbrev = words[parenthIndex];\n this.dest = words.slice(parenthIndex + 1, dateIndex).join(' ');\n this.code = words[0] + ' ' + words[1];\n this.id = words[0] + words[1];\n}\n</code></pre>\n\n<p>Then in your <code>extractFlights</code> function you only need the following, to break the text down into individual lines and send them to new Flight objects to be parsed.</p>\n\n<pre><code>extractFlights: function() {\n var paragraphs = this.text.split(\"\\n\"), flights = {}, f, p;\n while (p = paragraphs.pop()) {\n f = new Flight(p);\n flights[f.id] = f;\n }\n console.log(flights);\n}\n</code></pre>\n\n<p>(<a href=\"http://jsfiddle.net/nNsK4/5/\" rel=\"nofollow\">fiddle</a>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T00:03:41.917", "Id": "31907", "Score": "0", "body": "Can you explain your while loop in extractFlights? Did you mean to check for equality instead of assigning p to paragraphs.pop()?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T00:05:58.097", "Id": "31908", "Score": "0", "body": "I just ended up using a for loop: \n\n`for (var i = 0; i < paragraphs.length; i++) {\n p = paragraphs.pop();\n f = new Flight(p);\n flights.push(f);\n}`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T00:14:15.970", "Id": "31909", "Score": "0", "body": "Your for loop is a more transparent way of doing the same thing. The while statement assigns the last value in paragraphs to p and removes it from paragraphs; when paragraphs is empty it returns `undefined` and so the loop stops. It's just a nice way of looping though all the values of an array when you don't care if the array gets destroyed in the process." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T02:36:57.660", "Id": "19863", "ParentId": "19862", "Score": "1" } } ]
{ "AcceptedAnswerId": "19863", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T01:20:50.707", "Id": "19862", "Score": "2", "Tags": [ "javascript" ], "Title": "Simplifying and improving (namely DRY) for flight info fetcher" }
19862
<p>This is my first attempt at trying to write a "monitor" class to determine if a UNC path is available. I need the monitor to not block the main thread and to also event when the UNC is toggled UP/DOWN so that I can respond to that event. </p> <p>I'm looking for:</p> <ol> <li>Best practice suggestions</li> <li>Am I doing this properly? Is there a more efficient way?</li> <li>Will there be threads left alive? will I eat into the pool until it starves? </li> <li>Other comments suggestions related to this code or programming context </li> </ol> <p></p> <pre><code>public class NetworkPathMonitor { public event EventHandler&lt;PathAvailabilityChangedArgs&gt; PathAvailabilityChanged; public event EventHandler Started; public event EventHandler Stopping; public event EventHandler Stopped; public event EventHandler CheckingStatus; protected virtual void OnStopping(object sender, EventArgs e) { EventHandler handler = Stopping; if (handler != null) handler(sender, e); } protected virtual void OnCheckingStatus(object sender, EventArgs e) { EventHandler handler = CheckingStatus; if (handler != null) handler(sender, e); } protected virtual void OnStopped(object sender, EventArgs e) { EventHandler handler = Stopped; if (handler != null) handler(sender, e); } protected virtual void OnStarted(object sender, EventArgs e) { EventHandler handler = Started; if (handler != null) handler(sender, e); } protected virtual void OnPathAvailabilityChanged(object sender, PathAvailabilityChangedArgs e) { EventHandler&lt;PathAvailabilityChangedArgs&gt; handler = PathAvailabilityChanged; if (handler != null) handler(sender, e); } private PathState CurrentState { get; set; } private CancellationTokenSource TokenSource { get; set; } private AutoResetEvent IsStopping { get; set; } public string PathToMonitor { get; set; } public int Interval { get; set; } public NetworkPathMonitor(string pathToMonitor, int interval, PathState expectedState = PathState.Up) { this.CurrentState = expectedState; this.Interval = interval; this.PathToMonitor = pathToMonitor; } public void Stop() { OnStopping(this, EventArgs.Empty); TokenSource.Cancel(); } public void Start() { IsStopping = new AutoResetEvent(false); TokenSource = new CancellationTokenSource(); var t = Task.Factory.StartNew(() =&gt; { OnStarted(this, EventArgs.Empty); TimeSpan waitInterval = TimeSpan.FromMilliseconds(Interval); while (!IsStopping.WaitOne(waitInterval)) { if (this.TokenSource.IsCancellationRequested) { //Is this how to properly stop the signal? IsStopping.Set(); IsStopping.Dispose(); OnStopped(this, EventArgs.Empty); break; } OnCheckingStatus(this, EventArgs.Empty); CheckPathStatus(); } }, TokenSource.Token); } private void CheckPathStatus() { //this is synchronous. We just have to wait for it to timeout. var currentState = Directory.Exists(PathToMonitor) ? PathState.Up : PathState.Down; var shouldEvent = currentState != CurrentState; CurrentState = currentState; if (shouldEvent) { OnPathAvailabilityChanged(this, new PathAvailabilityChangedArgs() { Path = PathToMonitor, PathState = CurrentState }); } } } public enum PathState { Up, Down } public class PathAvailabilityChangedArgs : EventArgs { public string Path { get; set; } public PathState PathState { get; set; } public PathAvailabilityChangedArgs() { } public PathAvailabilityChangedArgs(string path) { Path = path; } } </code></pre>
[]
[ { "body": "<p>The implementation you have will forever consume one thread from the ThreadPool. That's not the end of the world, but not ideal either. An easy solution would be to use an overload of <code>Task.Factory.StartNew</code> that accepts a <code>TaskCreationOptions</code> argument, and specify <code>TaskCreationOptions.LongRunning</code>. That will let the system handle it appropriately. Another option would be starting a new thread yourself. </p>\n\n<p>In the task delegate (the code inside <code>StartNew()</code>) I would put a global try/catch block. Any exceptions that might be thrown in there will cause your process to be killed. At the very least you'd want to log those somewhere just so you have some idea what's going on. </p>\n\n<p>I think you're going to <code>Dispose()</code> the <code>IsStopping</code> event on the first time through the loop, then try to use it on the second time through, which will probably cause an exception. I would just remove the <code>AutoResetEvent</code> entirely and use <code>CancellationTokenSource</code> instead. You can use <code>TokenSource.Token.WaitHandle.WaitOne()</code> to wait on instead of the <code>AutoResetEvent</code>. This also has the benefit that when <code>Stop()</code> is called, any pending wait will end immediately. </p>\n\n<p>I would make the <code>Interval</code> property a <code>TimeSpan</code> instead of an <code>int</code>. It's just more clear to users what it means - they don't have to wonder whether it's seconds, milliseconds, or what. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T16:47:16.860", "Id": "31756", "Score": "0", "body": "Very good feeback. It's actually not as bad as I thought it would be. All of your suggestions are valid. I will attempt to make these changes and post a revision when complete. Additionally, if there is no more feedback afterwards, I will mark this as the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T17:37:12.900", "Id": "31761", "Score": "0", "body": "Just a note about the disposing of the AutoEvent: That only happened upon cancellation (token.Cancel()). When the call to cancel was made, the loop would only then check the cancellation status and dispose. The code as entered in my OP didn't throw any errors during testing, however, that's not to say that it is absolute. I just can't say for sure due to lack of confidence." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T20:27:29.117", "Id": "31763", "Score": "0", "body": "I have updated the code per the suggestions. However, I am uncertain how to handle exceptions from within the Task thread. I read http://www.albahari.com/threading/part5.aspx#_Working_with_AggregateException and _thought_ I had applied it properly, but it doesn't appear to bubble up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-23T16:46:57.367", "Id": "31776", "Score": "0", "body": "Since this is a simple case I would probably throw a try/catch block inside the thread method, rather than using continuations. But the way you've done it looks OK to me. Have you tried intentionally causing an exception and following it in the debugger?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-23T18:22:28.923", "Id": "31777", "Score": "0", "body": "I have done an intentional throw and it never popped in the debugger. Everything looks and runs as expected. Thank you for your time, effort and expertise. I've marked your reply as the answer." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T16:21:21.227", "Id": "19871", "ParentId": "19868", "Score": "3" } }, { "body": "<p>Just to add to <code>breishl</code>'s answer:</p>\n\n<ul>\n<li>don't use private properties, just use fields instead (<code>private CancellationTokenSource TokenSource { get; set; }</code> => <code>private CancellationTokenSource _tokenSource;</code>)</li>\n<li><code>AutoResetEvent</code> is not needed as already noted, but even now it's used incorrectly, you should have used <code>ManualResetEvent</code> instead (again, not needed here)</li>\n<li>you can also wait (await) with cancellationToken using <code>Task.Delay(TimeSpan, CancellationToken)</code> method.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T19:53:41.147", "Id": "31762", "Score": "0", "body": "I updated my comment to include a formerly missing requirement of .NET 4.0. I have taken note of the incorrect usage of AutoResetEvent and will research more for my own knowledge; however, it seems it's somewhat obsolete now with the existence of Tasks? Can you confirm that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T21:49:52.630", "Id": "31764", "Score": "1", "body": "I wouldn't say that `ManualResetEvent` and `AutoResetEvent` are already obsolete. That's true that most of day-to-day work is covered with new async API (Tasks in .NET 4.0 and async compiler support in .NET 4.5), but there are cases when you need to synchronise work done in different threads. It's like the main use case of `Monitor` class is covered with `lock` keyword, but there may be cases when you need features like `Monitor.Wait` and `Monitor.Pulse`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T18:06:46.213", "Id": "19873", "ParentId": "19868", "Score": "2" } } ]
{ "AcceptedAnswerId": "19871", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T10:06:08.453", "Id": "19868", "Score": "4", "Tags": [ "c#", ".net", "multithreading", "task-parallel-library" ], "Title": "UNC path exists monitor" }
19868
<p>Listening to <a href="https://codereview.stackexchange.com/a/19826/11197">mseancole's advice in my previous post</a>, I have rewritten the code. </p> <pre><code>function fihHomeIndex() { global $conf, $DBH; if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST') { $prelim_check_errors = array(); if (@$_POST['ss'] != $_SESSION['shared_secret']) { array_push($prelim_check_errors, 'Possible hacking attempt. Upload aborted.'); } if (empty($_POST['adult'])) { array_push($prelim_check_errors, 'Please choose whether this image contains ADULT content or is family safe!'); } elseif ($_POST['adult'] != 'yes' &amp;&amp; $_POST['adult'] != 'no') { array_push($prelim_check_errors, 'Possible hacking attempt. Upload aborted.'); } if (isSpamIP($_SERVER['REMOTE_ADDR']) !== FALSE) { array_push($prelim_check_errors, 'Sorry, your IP is listed in one of the spammer lists we use, which aren\'t controlled by us. More information is available at &lt;a href="http://www.dnsbl.info/dnsbl-database-check.php?IP=' . $_SERVER['REMOTE_ADDR'] . '"&gt;http://www.dnsbl.info/dnsbl-database-check.php?IP=' . $_SERVER['REMOTE_ADDR'] . '&lt;/a&gt;.'); } if (count($prelim_check_errors) &gt;= 1) { fihRenderErrors($prelim_check_errors); } else { $upload_errors = array(); $names = $_FILES['fihImageUpload']['name']; foreach ($names as $index =&gt; $name) { if ($_FILES['fihImageUpload']['error'][$index] == UPLOAD_ERR_NO_FILE) { unset($names[$index]); continue; } if (filesize($_FILES['fihImageUpload']['tmp_name'][$index]) &gt; $conf['upload']['max_file_size']) { array_push($upload_errors, htmlspecialchars(strip_tags(utf8_decode($name))) . ' exceeds filesize limit.'); unset($names[$index]); continue; } if (FALSE !== ($fileInfo = getimagesize($_FILES['fihImageUpload']['tmp_name'][$index]))) { if (strrchr($name, '.') == FALSE) { array_push($upload_errors, htmlspecialchars(strip_tags(utf8_decode($name))) . ' is missing a file extension.'); unset($names[$index]); continue; } elseif (! in_array(substr(strrchr($name, '.'), 1), $conf['upload']['file_types']) || ! in_array($fileInfo['mime'], $conf['upload']['mime_types'])) { array_push($upload_errors, htmlspecialchars(strip_tags(utf8_decode($name))) . ' is not an image.'); unset($names[$index]); continue; } } else { array_push($upload_errors, htmlspecialchars(strip_tags(utf8_decode($name))) . ' is not an image.'); unset($names[$index]); continue; } } if (empty($names) || count($upload_errors) &gt;= 1) { $error_m = empty($upload_errors) ? 'Please choose aleast file to upload!' : $upload_errors; fihRenderErrors($error_m); } else { foreach ($names as $index =&gt; $name) { $org_name = sanitize(explode('.', $name)[0]) . '.' . explode('.', $name)[1]; $new_name = sanitize(explode('.', $name)[0], true) . '_' . time() . '.' . explode('.', $name)[1]; if (move_uploaded_file($_FILES['fihImageUpload']['tmp_name'][$index], $conf['storage']['folder'] . 'full/' . $new_name)) { $image_info = getimagesize($conf['storage']['folder'] . 'full/' . $new_name); if (! $DBH-&gt;query("INSERT INTO `{$conf['db']['table_prefix']}images` (`image_id`, `image_orig_filename`, `image_filename`, `image_adult`) VALUES " . "(NULL, '{$org_name}', '{$new_name}', '{$_POST['adult']}');")) { die('Database error'); } $image_last_id = $DBH-&gt;insert_id; $image_dimensions = $image_info[0] . 'x' . $image_info[1]; $image_filesize = filesize($conf['storage']['folder'] . 'full/' . $new_name); createThumbnail($new_name, $conf['storage']['folder'] . 'thumb/', $conf['thumbnail']['width'], $conf['thumbnail']['height'], $image_last_id); if (! $DBH-&gt;query("INSERT INTO `{$conf['db']['table_prefix']}images_meta` (`meta_id`, `image_id`, `image_ext`, `image_size`) VALUES " . "(NULL, '{$image_last_id}', '{$image_dimensions}', '{$image_filesize}');")) { die('Database error'); } $template_info[$index] = array('id' =&gt; $image_last_id); header('Location: ' . $conf['base_url'] . 'upload-success/' . base64_encode(serialize($template_info))); } else { die('Possible hacking attempt. Upload aborted.'); } } } } } else { # Display the header fihDisplayHead(); # Display the first column, which contains a login form and social networking tools fihDisplayFirstColumn(); # Display the upload section fihDisplayUpload(); # Footer fihDisplayFoot(); } } </code></pre> <p>Now please tell me anywhere where I can further improve this code. Thanks</p>
[]
[ { "body": "<p>You ignored mseancole's first bit of advice about not using globals. Note that the globals are not only $conf and $DBH but also $_POST, $_SESSION, and $_FILES. All of these globals should be passed to your functions. And your code is still very difficult to read mostly due to heavy indentation. You have heavy indentation because the function is doing too much. It is concerned with ip addresses, input validation, input filtering, db access, view presentation, and probably more. Yes, all those things need to be dealt with. But, dealing with them all in one place makes one huge piece of non-reusable, non-testable, hard to maintain piece of code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T15:25:51.890", "Id": "19897", "ParentId": "19872", "Score": "1" } }, { "body": "<p>Ummmm... what happened? I see you've changed and added a few things, but very little is anything I recommended.</p>\n\n<p>I mentioned the globals in my last answer, so I wont go over these again. I'll just remind you that they are bad.</p>\n\n<p>There is no need to use <code>strtoupper()</code> on the request method. It should work just fine how you had it, especially if you are using the loose comparison <code>==</code> instead of the absolute one <code>===</code>. The only thing I may have mentioned is that you might want to reverse the logic for it to get that else out of the way first. That way you could return early and avoid the heavy indentation.</p>\n\n<pre><code>if( $_SERVER[ 'REQUEST_METHOD' ] != 'POST' ) {\n fihDisplayHead();\n fihDisplayFirstColumn();\n fihDisplayUpload();\n fihDisplayFoot();\n return;//this return will make an else unnecessary\n}\n//now the rest of the code can be unindented by one level\n</code></pre>\n\n<p>Honestly, this function shouldn't even be concerned with this anyways. Do that check outside of the function to determine if you should run the script for uploading an image or displaying the page. Those should be separate concerns. Remember the Single Responsibility Principle I mentioned in my last answer. A function should be responsible for one task and that task should be readily identifiable by the function's name.</p>\n\n<pre><code>if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) {\n fihHomeIndex();\n} else {\n fihDisplayHead();\n fihDisplayFirstColumn();\n fihDisplayUpload();\n fihDisplayFoot();\n}\n</code></pre>\n\n<p>You should avoid the error suppressor <code>@</code> at all costs. Manually perform the checks necessary to avoid the errors. This avoids confusion later and ensures your code runs as expected. Besides, as your skills progress and you add things such as error logs and the like, you will find these check statements will make the task of debugging much simpler if you consistently check for things like this.</p>\n\n<pre><code>if( ! isset( $_POST[ 'ss' ] ) || $_POST[ 'ss' ] != $_SESSION[ 'shared_secret' ] ) {\n</code></pre>\n\n<p>Another possibility is to use <code>filter_input()</code> to automatically check and sanitize the input for you. If it doesn't exist you will get a FALSE return. Sanitizing is always a big part of using user input and should be done regularly.</p>\n\n<pre><code>$secret = filter_input( INPUT_POST, 'ss', FILTER_SANITIZE_STRING );\nif( $secret != $_SESSION[ 'shared_secret' ] ) {\n</code></pre>\n\n<p>Why have all of your array appending been redone to use <code>array_push()</code>? There is no reason for you to use this function unless you are adding a bunch of elements to an array at once. Use the method you were before. Calling a function is actually slower and less legible. Though the speed is negligible and the legibility is more important here.</p>\n\n<pre><code>$prelim_check_errors[] = 'one element';\narray_push( $prelim_check_errors,\n 'multiple',\n 'elements',\n 'makes',\n 'this method',\n 'cleaner'\n);\n</code></pre>\n\n<p>Your function is still doing entirely too much. If statements, especially large ones, are usually pretty good indications for the need for separation. I'm not saying every if statement, mind, just the major ones. For instance, the request method if statement mentioned previously. It was a determining if statement that took the code in one of two completely different directions. Notice how I was able to separate that statement from the function? It didn't create a new function, but it did demonstrate how it could be separated.</p>\n\n<p>Take a look at your code and determine what tasks you need to do, make a very detailed list, and create a separate function for each task, especially if that task is being repeated. If the task is already a function, one of your own or PHP's, then you shouldn't need to create another, but make sure you keep the Single Responsibility Principle in mind as well. A challenge you may face while doing this will be the sharing of resources; Remember my advice from my previous answer about injecting those resources and you should be fine. Typically an application such as this would immensely benefit from an OOP structure, but I would be more concerned with getting those principles down pat first. Doing so should naturally lead into a more OOP approach. Let me help get you started with that list:</p>\n\n<ul>\n<li>Determine if image has been uploaded (Demonstrated with request method above).</li>\n<li>Verify user (IP address and shared secret, etc...)</li>\n<li>Verify content (Adult, size, etc...).</li>\n<li>Render Errors (Already a function).</li>\n<li>Upload Image.</li>\n<li>etc...</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T16:45:41.310", "Id": "19901", "ParentId": "19872", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T16:58:26.830", "Id": "19872", "Score": "1", "Tags": [ "php", "php5" ], "Title": "Image upload script" }
19872
<p>I'm currently attempting to learn OCaml, and I'm working thought the Project Euler problems to do so. Here's some code I knocked together for problem 10.</p> <p>I am looking for idiomatic feedback rather than algorithmic</p> <pre><code>(* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. MODIFYING CODE FROM PROBLEM 7 *) (* first thing we are going to do is write a bit of code that checks to see if a number is prime *) let rec isPrimeRec number start = if (start*start)&gt;number then 1 else if number mod start = 0 then -1 else isPrimeRec number (start+1);; let i = ref 2;; let sum = ref 0 in while !i &lt;2000000 do if (isPrimeRec !i 2) = 1 then begin sum:= !sum + !i; i:= !i + 1; Printf.printf "%d is prime, it is prime number %d\n" !i !sum; end else i:= !i + 1 done;; let temp = ref 0;; temp:= isPrimeRec 19 3; Printf.printf "The value is %d\n" !temp </code></pre> <p>Now - I almost purposely didn't write this to be efficient algorithmically (for example I am aware that prime numbers can't be even) and there are a few other things that I would change for efficiency - but I'm interested in style feedback - so I'd like the code critiqued much more on the level of "In OCaml, one would normally bracket expression X for readability" or "OCaml let's you use this, clearly syntax instead" - rather than "it's a property of prime numbers that" </p>
[]
[ { "body": "<p>Here are some comments and an example rewrite of your code.</p>\n\n<p>Indentation and line breaks are not idiomatic to OCaml, it's good practice in any language.</p>\n\n<p>A more intuitive type for <code>is_prime</code> would be to have only one argument, so let's encapsulate <code>is_prime_rec</code>:</p>\n\n<pre><code>let is_prime =\n let rec is_prime_rec number start =\n if start * start &gt; number then true (* OCaml provides a type `bool`, distinct from `int`, so it's better to return `true` instead of `1`. *)\n else if number mod start = 0 then false\n else is_prime_rec number (start+1) in\n fun n -&gt; is_prime_rec n 2;;\n</code></pre>\n\n<p>which yields <code>val is_prime : int -&gt; bool = &lt;fun&gt;</code>.</p>\n\n<p>You know the number of iterations in the loop, so better use <code>for</code> rather than <code>while</code>.\nThis also avoid manually incrementing <code>i</code>.</p>\n\n<pre><code>let sum = ref 0 in\nfor i = 2 to 2_000_000 do (* detail: OCaml parses `2_000_000` as `2000000`, which is more readable. *)\n if is_prime i then (* no need for parentheses around the if clause *)\n begin\n sum:= !sum + i;\n Printf.printf \"%d is prime, it is prime number %d\\n\" i !sum;\n end\ndone;;\n</code></pre>\n\n<p>I can't help but add an algorithmic remark: consider using a sieve.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-23T08:52:14.747", "Id": "19876", "ParentId": "19874", "Score": "3" } }, { "body": "<p>Hello from Haskell world ;)\nConsider using some kind of memoization. For example with help of infinte cached sequence through <code>Seq.cache</code> in F#:\n</p>\n\n<pre><code>let rec is_prime x =\n primes\n |&gt; Seq.takeWhile (fun p -&gt; p*p &lt;= x)\n |&gt; Seq.exists (fun p -&gt; x % p = 0)\n |&gt; not\nand primes = \n seq {\n yield 2;\n yield 3;\n yield!\n Seq.initInfinite (fun i -&gt; i) \n |&gt; Seq.skipWhile (fun i -&gt; i &lt;= 3)\n |&gt; Seq.filter is_prime\n }\n |&gt; Seq.cache\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T13:03:13.417", "Id": "19893", "ParentId": "19874", "Score": "0" } }, { "body": "<p>To complement these very good answers, I would suggest to avoid using <code>ref</code>s. The cool thing about functional programming is that it encourages you not to change the states of the variables. In your case, there is no penalty (in terms of performance or readability) not to use <code>ref</code>s.</p>\n\n<p>So you could replace the summation loop with a recursive function :</p>\n\n<pre><code>let sumPrimes i =\n let rec aux i sum =\n if (i=1) then sum\n else begin \n if (isPrimeRec i 2 = 1) then aux (i-1) (sum+i) else aux (i-1) sum\n end\n in aux i 0;;\n</code></pre>\n\n<p>Which is slightly shorter than :</p>\n\n<pre><code>let i = ref 2;;\nlet sum = ref 0 in \nwhile !i &lt;2000000 do \nif (isPrimeRec !i 2) = 1 then \nbegin \nsum:= !sum + !i; i:= !i + 1; \nPrintf.printf \"%d is prime, it is prime number %d\\n\" !i !sum; \nend \nelse \ni:= !i + 1\ndone;;\n</code></pre>\n\n<p>And you can finish the problem with a simple :</p>\n\n<pre><code>print_int (sumPrimes 2000000) ;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-06T10:38:21.460", "Id": "122050", "ParentId": "19874", "Score": "0" } } ]
{ "AcceptedAnswerId": "19876", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T21:42:28.160", "Id": "19874", "Score": "3", "Tags": [ "programming-challenge", "primes", "ocaml" ], "Title": "Project Euler 10 - Summation of primes" }
19874
<p>I have a textView which is displaying a string. I also have an array which keeps track of where every line begins, it stores the "start index" or NSRange.location for every line.</p> <p>However, when text is inserted on one line, the start indexes of every line afterwards change. So I'm doing this:</p> <pre><code> //i = the linenumber of the modified row // self.lineStartIndexes = NSMutableArray for (int j = i+1; j &lt; self.lineStartIndexes.count; j++) { _lineStartIndexes[j] = @([(NSNumber *)[self.lineStartIndexes objectAtIndex:j] intValue]+text.length); } </code></pre> <p>This takes 12ms on a large text file, and it feels like it could go a lot faster without all <code>NSNumber</code>-conversions. I have thought about using C arrays, but I don't know the size of the array and everything became very complicated to me. What should I do to optimize this?</p>
[]
[ { "body": "<p>You could consider creating a class that holds the indices for a larger amount of text (for example a paragraph or a section or a subsection in the text). That class would have the absolute index for where in the file it begins and relative indices within the paragraph/section each line begins. </p>\n\n<p>Whenever a new line is added or removed only the lines within that paragraph/section would have to be updated and the absolute start index of all the following sections as well. </p>\n\n<p>(I don't know what text you write or what you use the line starts for). </p>\n\n<p>You could still find a specific line very easily (and probably very fast) by enumerating the absolute indices of the paragraphs/sections and when you find the right section enumerate it's lines. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T21:02:10.697", "Id": "30277", "ParentId": "19880", "Score": "2" } }, { "body": "<ol>\n<li><p>You don't need <code>(NSNumber *)</code>. <code>-[NSArray objectAtIndex:]</code> return <code>id</code> type and you can call any method on it.</p></li>\n<li><p>You can save and reuse the result of <code>text.length</code> so you don't need to call a method every time in the loop. Similarly for <code>self.lineStartIndexes.count</code>.</p></li>\n<li><p><code>[self.lineStartIndexes objectAtIndex:j]</code> can be replaced with <code>self.lineStartIndexes[j]</code></p></li>\n<li><p>Try use <code>self.propertyName</code> to access property. For performance reason you may want to use <code>_propertyName</code> directly but be consistent.</p></li>\n</ol>\n\n<p>As result:</p>\n\n<pre><code>NSUInteger length = text.length;\nNSUInteger count = self.lineStartIndexes.count;\n\nfor (int j = i+1; j &lt; count; ++j) {\n self.lineStartIndexes[j] = @([self.lineStartIndexes[j] intValue]+length);\n}\n</code></pre>\n\n<hr>\n\n<p>For performance improvement, using <code>NSArray</code> with <code>NSNumber</code> is very expansive. You should consider use C array (<code>NSUInteger[]</code>/<code>NSUInteger *</code>) if possible although you have to management the dynamic memory yourself with <code>malloc</code> and <code>free</code>.</p>\n\n<p>For example:</p>\n\n<pre><code>@property NSUInteger * lineStartIndexes;\n\n- (void)createLineStartIndexesWithSize:(NSUInteger)size\n{\n free(lineStartIndexes);\n lineStartIndexes = calloc(size, sizeof(NSUInteger));\n}\n\n- (void)dealloc\n{\n // other dealloc code\n free(lineStartIndexes);\n}\n</code></pre>\n\n<p>then you can do </p>\n\n<pre><code>NSUInteger length = text.length;\nNSUInteger count = self.lineStartIndexes.count;\n\nfor (int j = i+1; j &lt; count; ++j) {\n self.lineStartIndexes[j] += length;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T07:36:54.090", "Id": "36040", "ParentId": "19880", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-23T18:45:01.387", "Id": "19880", "Score": "2", "Tags": [ "array", "objective-c", "ios", "integer", "casting" ], "Title": "NSArray and NSNumber-int conversions" }
19880
<p>I wrote this code about finding the end of file (EOF). Please review this.</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;conio.h&gt; void main (void) { int x,y,m; for(x=0;x&gt;=0;x++){ m=scanf("%d %d",&amp;x,&amp;y); if (m!=2 || m==EOF){ break; } else printf("/%d/%d/\n",x,y); } if (feof ( stdin )){ printf("End of input\n"); } else if(m!=2){ printf("There was an error\n"); } getch(); } </code></pre>
[]
[ { "body": "<p>Let me look at this...first you include the headers, good.</p>\n\n<pre><code>void main (void)\n{\n /* snip */\n}\n</code></pre>\n\n<p>Well, for C it's standard to call <code>int main(int argc, char** argv)</code> to facilitate <a href=\"http://publications.gbdirect.co.uk/c_book/chapter10/arguments_to_main.html\" rel=\"nofollow noreferrer\">arguments</a>, or if there are no arguments just <code>int main()</code>. </p>\n\n<p>This is minor style compaint, not a major problem.</p>\n\n<p>Examining your main function's contents:</p>\n\n<pre><code> int x,y,m;\n for(x=0;x&gt;=0;x++){\n m=scanf(\"%d %d\",&amp;x,&amp;y); /* NOTE THIS LINE!!! */\n if (m!=2 || m==EOF){\n break;\n }\n else printf(\"/%d/%d/\\n\",x,y);\n }\n</code></pre>\n\n<p><strong>1.</strong> This <code>scanf</code> uses <code>STDIN</code> for input, i.e., the user will enter stuff from the command line. Is this what you desire? </p>\n\n<p>I don't think <code>EOF</code> would be entered by the user...</p>\n\n<p>Perhaps you meant <code>fscanf</code> to scan a file for input?</p>\n\n<p><strong>2.</strong> So if I enter <code>-9 3</code> I should expect this for-loop to terminate. Is this the desired behaviour?</p>\n\n<p>On the <code>/* NOTE THIS LINE!!!</code> bit of code, I am suspicious about using <code>sanf(...,&amp;x,...)</code>. Again, perhaps this is desired, I don't know.</p>\n\n<p><strong>3.</strong> You should also be consistent with the use of brackets for single lines, writing <code>if (...) break;</code> instead. Or change the <code>else</code> to include brackets. But don't include brackets for one, then forget them for the other.</p>\n\n<pre><code> if (feof ( stdin )){\n printf(\"End of input\\n\");\n }\n else if(m!=2){\n printf(\"There was an error\\n\");\n }\n getch();\n}\n</code></pre>\n\n<p><strong>4.</strong> These lines could be tucked into the <code>for</code>-loop. </p>\n\n<p><strong>5.</strong> Avoid using <code>getch()</code> since it's <a href=\"https://stackoverflow.com/questions/814975/getch-is-deprecated\">deprecated</a>. If you're just waiting for the user to hit some key to continue, use <code>getchar()</code>.</p>\n\n<p>You could have condensed the main function to be:</p>\n\n<pre><code>int main() {\n int m,x,y;\n for(x=0; x&gt;=0; x++) {\n m=scanf(\"%d %d\",&amp;x,&amp;y);\n if (m!=2) { /* note multiple lines always trapped between brackets */\n printf(\"There was an error!\\nHit any key to continue...\\n\");\n getchar();\n return EXIT_FAILURE;\n } else if (m==EOF) {\n printf(\"End of input\\n\");\n break();\n }\n else printf(\"/%d/%d/\\n\",x,y); /* single lines don't have brackets */\n }\n printf(\"Hit any key to continue...\\n\");\n getchar();\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>The beauty of returning an <code>int</code> is you can have multiple different exit failures, e.g., <code>-1</code> for bad input, <code>-2</code> for some other problem, etc.</p>\n\n<h2>Addendum</h2>\n\n<p>After sleeping on it, I realized some additional style points for C.</p>\n\n<p><strong>A1.</strong> You should <em>always</em> initialize your variables! So instead of just writing <code>int m,x,y;</code> we should instead write:</p>\n\n<pre><code> int m,x,y;\n x=0;\n y=0;\n m=0;\n</code></pre>\n\n<p>It's something people overlook in C programming.</p>\n\n<p><strong>A2.</strong> You could have written a <code>while</code>-loop instead of a <code>for</code>-loop, which may have been more elegant. For example:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;conio.h&gt;\n\nint main() {\n int m,x,y;\n m = 0; \n x = 0; \n y = 0;\n while (x++ &gt;= 0) {\n m=scanf(\"%d %d\",&amp;x,&amp;y);\n if (m!=2) { /* note multiple lines always trapped between brackets */\n printf(\"There was an error!\\nHit any key to continue...\\n\");\n getchar();\n exit(EXIT_FAILURE);\n } else if (m==EOF) break();\n else printf(\"/%d/%d/\\n\",x,y); /* single lines don't have brackets */\n }\n if (feof(stdin)) printf(\"End of input\\n\");\n printf(\"Hit any key to continue...\\n\");\n getchar();\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>Note that we immediately terminate when there's an error, as is noted in the <em>C Book</em> in <a href=\"http://publications.gbdirect.co.uk/c_book/chapter1/description_of_example.html#section-10\" rel=\"nofollow noreferrer\">Chapter 1</a> and <a href=\"http://publications.gbdirect.co.uk/c_book/chapter10/interpreting_program_arguments.html\" rel=\"nofollow noreferrer\">Chapter 10</a>.</p>\n\n<p><strong>A3.</strong> Observe the only way to leave the <code>while</code>-loop is through (a) scanning an <code>EOF</code>, (b) scanning a \"negative enough\" number, or (c) through bad data. So we can notify the user of an error immediately, and exit (which is good form).</p>\n\n<p>And the only remaining way to leave the loop is through (a) or (b). But it appears in the OP either case is acceptable, but only for (a) should we notify the user there's the end of input.</p>\n\n<p><strong>A4.</strong> Note upon exiting when encountering an error, it's good form to use <code>exit(&lt;error code&gt;)</code>. You need <code>stdlib.h</code> to use <code>exit(...)</code> though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T00:16:17.017", "Id": "31781", "Score": "1", "body": "The user can enter EOF for the input stream. On Unix it is done with <ctrl>-D On Windows <ctrl>-Z. See http://stackoverflow.com/a/10505004/14065" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T03:13:29.013", "Id": "31786", "Score": "0", "body": "`These lines could be tucked into the for-loop.` No they should obviously not be inside the for loop. They are a test to see if the data supplied in the file is correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T01:56:31.927", "Id": "31828", "Score": "0", "body": "@LokiAstari: thanks, although I contend for the exit failure case...you should stick them into the `for`-loop. At least, that's what I've read in the C books. However, I may be in error, and if that's the case, by all means correct me :) I'd be interested in any further remarks on my addendum." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-23T20:41:13.710", "Id": "19883", "ParentId": "19882", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-23T19:21:41.667", "Id": "19882", "Score": "4", "Tags": [ "beginner", "c", "file", "error-handling" ], "Title": "Finding the end of file (EOF)" }
19882
<p>I have view and it works correct, but very slow</p> <pre><code>class Reading(models.Model): meter = models.ForeignKey(Meter, verbose_name=_('meter')) reading = models.FloatField(verbose_name=_('reading')) code = models.ForeignKey(ReadingCode, verbose_name=_('code')) date = models.DateTimeField(verbose_name=_('date')) class Meta: get_latest_by = 'date' ordering = ['-date', ] def __unicode__(self): return u'%s' % (self.date,) @property def consumption(self): try: end = self.get_next_by_date(code=self.code, meter=self.meter) return (end.reading - self.reading) / (end.date - self.date).days except: return 0.0 @property def middle_consumption(self): data = [] current_year = self.date.year for year in range(current_year - 3, current_year): date = datetime.date(year, self.date.month, self.date.day) try: data.append(Reading.objects.get( date = date, meter = self.meter, code = self.code ).consumption) except: data.append(0.0) for i in data: if not i: data.pop(0) return sum(data) / len(data) class DataForDayChart(TemplateView): def get(self, request, *args, **kwargs): output = [] meter = Meter.objects.get(slug=kwargs['slug']) # TODO: Make it faster for reading in meter.readings_for_period().order_by('date'): output.append({ "label": reading.date.strftime("%d.%m.%Y"), "reading": reading.reading, "value": reading.consumption / 1000, "middle": reading.middle_consumption / 1000 }) return HttpResponse(output, mimetype='application/json') </code></pre> <p>What should I change to make it faster?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T08:18:32.167", "Id": "31790", "Score": "0", "body": "How slow it is? How many records the view returns?\nLooks like you have a loots of SQL Queries there, try to reduce amount of queries." } ]
[ { "body": "<p>There's nothing intrinsically time-consuming here code-wise - I think the best approach is to make sure that your database tables are set up correctly with the required indices. Perhaps create a view on the db to push some work onto that rather than select in code?</p>\n\n<p>I am a little puzzled however by your middle_consumption function. The inner loop contents do something like:</p>\n\n<pre><code>get a date, x years ago from present day\nget a reading on that date, or 0 on failure\nadd that reading to the results\ngo through the results\n if the current item is 0, delete the **first** item\n</code></pre>\n\n<p>This seems wrong.</p>\n\n<ol>\n<li>What happens on February 29th? It would be better to add 365 days if that's appropriate for your application.</li>\n<li><p>Why add a value only to (presumably want to) delete it again? Would something like this be better?</p>\n\n<pre><code>try:\n current_value = Reading.objects.get(\n date = date_of_reading,\n meter = self.meter,\n code = self.code\n ).consumption\nexcept Reading.DoesNotExist: # or suitable exception\n current_value = 0\nif current_value &gt; 0:\n anniversary_values.append( current_value )\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T08:57:33.763", "Id": "19887", "ParentId": "19886", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T06:24:10.340", "Id": "19886", "Score": "2", "Tags": [ "python", "django" ], "Title": "Django how to make this view faster?" }
19886
<p>I'm wondering if perhaps I am doing this all wrong:</p> <p>Questions:</p> <ol> <li>How is my OOP?</li> <li>Is it running multiple methods on a value {i.e.: is <code>strip_tags($copy-&gt;truncateString($articles[$i]['body'], 250, " "))</code>} a terrible way to manage resources?</li> <li><p>Should I create separate methods to use for the following line: </p> <pre><code>echo '&lt;div class="summary"&gt;&lt;a href="/' . BreadCrumbs::getCrumb(1) . '/'. BreadCrumbs::getCrumb(2) . '/article/' . $articles[$i]['id'] . '"&gt;&lt;h5&gt;' . $articles[$i]['title'] . '&lt;/h5&gt;&lt;/a&gt; (' . $articles[$i]['date'] . ')&lt;p&gt;' . strip_tags($copy-&gt;truncateString($articles[$i]['body'], 250, " ")) . '&lt;/p&gt;&lt;p&gt;&lt;a href="/' . BreadCrumbs::getCrumb(1) . '/'. BreadCrumbs::getCrumb(2) . '/article/' . $articles[$i]['id'] . '"&gt; Read more&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;'; </code></pre></li> </ol> <p>Notes:</p> <ul> <li><code>pageTemplate</code> is a class which will contain all HTML templates for this particular site</li> <li>Two static classes take care of site wide configuration variables (not seen here) and tracking the URL (<code>BreadCrumbs::</code>).</li> <li>Calling <code>BreadCrumbs::getCrumb(x)</code> retrieves the 'value' at the x position of the url (ie: domain.com/"pos 1"/"pos 2"/"pos 3"). The values are managed at the top of the page and are checked if empty and replaced with a default value if they are.</li> <li><code>GetCopy</code> is a class which has a number of functions designed to run a query (based on various parameters) and retrieves an array (or mulch-dimensional array). The function used below retrieves a mulch-dimensional array with each second level array containing a whole article.</li> <li><code>GetCopy</code> has a parent. It extends a class called <code>CopyMan</code> which contains various functions such as adding paragraphs to a block of text, truncating, converting date forms, and pagination tools, called through the <code>GetCopy</code> object.</li> </ul> <p></p> <pre><code>/** * homePage :: () * PUBLIC method * = lay out the home page content * */ public static function homePage() { // initialize GetCopy class $copy = new GetCopy(); // special feature container echo '&lt;div id="special_box"&gt;&lt;div class="special_header"&gt;&lt;img src="/images/layout/special_header.png"&gt;&lt;/div&gt;&lt;div class="special_container"&gt;'; $articles = $copy-&gt;getRows('articles', 'date', 0, 2); //print_r($articles); for ($i = 0; $i &lt; count($articles); $i++) { echo '&lt;div class="special_summary"&gt;&lt;a href="/' . BreadCrumbs::getCrumb(1) . '/'. BreadCrumbs::getCrumb(2) . '/article/' . $articles[$i]['id'] . '"&gt;&lt;h5&gt;' . $articles[$i]['title'] . '&lt;/h5&gt;&lt;/a&gt; (' . $articles[$i]['date'] . ')&lt;p&gt;' . strip_tags($copy-&gt;truncateString($articles[$i]['body'], 250, " ")) . '&lt;/p&gt;&lt;p&gt;&lt;a href="/' . BreadCrumbs::getCrumb(1) . '/'. BreadCrumbs::getCrumb(2) . '/article/' . $articles[$i]['id'] . '"&gt; Read more&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;'; } echo '&lt;/div&gt;&lt;/div&gt;'; } </code></pre> <p>Further Information to help provide insight:</p> <pre class="lang-none prettyprint-override"><code>-[Folder] Lib -[Folder] bespoke --&gt; [Class] DisplayEngine private static $instance; public static function getInstance() + Methods for laying out divs. --&gt; [Class] PageTemplate public function homePage() -[Folder] copy --&gt; [Class] CopyMan public function truncateString($string, $limit, $break='.', $pad='...') public function convertToPara($string) public function convertToLongDate($date) protected function paginateList($table, $current_page, $list_length) protected function setLimits($table, $page, $numArticles, $featured) --&gt; [Class] GetCopy extends CopyMan require_once(Config::getAbsPath() . '/lib/omc_frmwrk/copy/CopyMan.php'); public function getFieldContents($table, $where_field, $where_match, $column) public function getRow($table, $field_array, $where_field, $where_match) public function getRows($table, $order_by, $limit_start, $limit_end) public function getRowsWhere($table, $order_by, $where_field, $where_match, $limit_start, $limit_end) -[Folder] database --&gt; [Class] DbMan private static $db_host = Config::db_host; private static $db_user = Config::db_user; private static $db_pass = Config::db_pass; private static $db_name = Config::db_name; private $mysql_connection; private $mysql_db; private $query; private $query_result; private function dbConnect() protected function executeQuery($query) --&gt; [Class] DbQuery extends DbMan private $query; public function prepareQuery($query_request) -[Folder] helpers --&gt; [Class] ArrayHelp public function recValueCheck($needle, $haystack) public function recValueReturn($needle, $haystack) -[Folder] layout --&gt; [Class] LogoMan private static $site_logo; public static function setSiteLogo($x) { self::$site_logo = $x; } public function printLogo() -[Folder] navigation --&gt; [Class] BreadCrumbs private static $bread_crumbs; private static $instance; public static function getCrumbs() { return self::$bread_crumbs; } public static function getCrumb($x) { return self::$bread_crumbs[$x]; } public static function setCrumbs($x) { self::$bread_crumbs = explode("/", $x); } public static function getInstance() { if (!self::$instance) { self::$instance = new self(); } return self::$instance; } public static function setEmptyCrumb($crumb, $fallback) --&gt; [Class] NavMan private static $links; private static $nav_id; public static function setLinks($x) { self::$links = $x; } public static function setNavId($x) { self::$nav_id = $x; } public function printNav($pre_link = "", $post_link = "") --&gt; [Class] Config const db_host = const db_user = const db_pass = const db_name = private static $abs_path; private static $include_css = array () private static $include_classes = array () private static $include_js = array () private static $site_logo = array () private static $nav_primary = array () private static $nav_secondary = array () + Getters and Setters for all above --&gt; [Class] initialize private static $include_css; private static $include_classes; private static $include_js; public function __construct() //*sets session, runs include methods below *// private function loadStylesheets() private function loadRequiredClasses() public function loadJavascript() </code></pre>
[]
[ { "body": "<p>I have a few good suggestions for you.</p>\n<h2>Max Line Length</h2>\n<p>Try to cut down on the length of your lines, at my current resolution(running from a cheap laptop on the train) stackexchange displays 90 characters per code line, your longest lines are far above 300, for sharing code try to keep it manageable.</p>\n<h2>Foreach</h2>\n<p>You're using a for loop for an array, which is fine, but the foreach function is more efficient if you're iterating all objects, and makes things a little cleaner.</p>\n<h2>Abstraction</h2>\n<p>In this instance I think you should abstract your display, maybe make a class to handle that stuff?</p>\n<h2>Put logic where it belongs</h2>\n<p>Put simply put the act of displaying the article in your display class, and leave the logic where it is.</p>\n<h2>Demo of what I think it should look like</h2>\n<pre><code>public static function homePage() {\n\n $copy = new GetCopy();\n\n $display = DisplayEngine::GetInstance();\n\n $display-&gt;printSpecialHeader();\n\n $display-&gt;openSpecialContainer();\n\n $articles = $copy-&gt;getRows('articles', 'date', 0, 2);\n\n foreach( $articles AS $article ){\n\n $display-&gt;printArticleLink($article);\n\n }\n\n $display-&gt;closeSpecialContainer();\n\n}\n\n...\n\nclass DisplayEngine {\n\n public function printArticleLink($article){\n\n echo '&lt;div class=&quot;special_summary&quot;&gt;&lt;a href=&quot;/'\n\n . BreadCrumbs::getCrumb(1)\n\n . '/'\n\n . BreadCrumbs::getCrumb(2)\n\n . '/article/'\n\n . $article['id']\n\n . '&quot;&gt;&lt;h5&gt;'\n\n . htmlspecialchars($article['title'])\n\n . '&lt;/h5&gt;&lt;/a&gt; ('\n\n . $article['date']\n\n . ')&lt;p&gt;'\n\n . $copy-&gt;truncateString(\n strip_tags($article['body']),\n 250,\n &quot; &quot;\n )\n\n . '&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;/'\n\n . BreadCrumbs::getCrumb(1)\n\n . '/'. BreadCrumbs::getCrumb(2)\n\n . '/article/'\n\n . $article['id']\n\n . '&quot;&gt; Read more&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;';\n\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T12:09:27.437", "Id": "31796", "Score": "0", "body": "That's beautiful man. Thank you! It was that long echo statement that really bugged me. I will do as you suggest and use a separate class for it. Should I keep the function static? Hows the OOP path I'm on?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T12:15:57.237", "Id": "31798", "Score": "0", "body": "Also, DisplayEngine::GetInstance(); is the singlton pattern, correct? Isn't that the same as using a static class? .. a quick google later and I think this looks like a better way of handling my Config and BreadCrumbs classes (currently just static classes)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T12:22:09.880", "Id": "31800", "Score": "0", "body": "or maybe not.. http://moisadoru.wordpress.com/2010/03/02/static-call-versus-singleton-call-in-php/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T13:08:26.910", "Id": "31802", "Score": "0", "body": "@obmon Yes it's a singleton, and they are slower, however it's commonly accepted that you use singletons over static classes for things that can hold config data, since this was a display class I imagined it having some sort of options specifying a stylesheet for the page, maybe a language or similar. If speed is essential use a static class, otherwise I suggest the speed difference is likely negligible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T13:30:16.237", "Id": "31804", "Score": "0", "body": "@obmon as for your style of oop, it's not bad, I'd suggest using a class for the articles so you can use type hinting and maybe move your truncating of the string onto the article. In fact you could probably have an ArticleManager class to overlook this stuff for you if it implements the Iterator interface you could make it work exactly the same but call it as `$articles = new ArticleManager(); $articles->getArticles( 0, 2, 'date' ); foreach( $articles AS $article ){ echo $article->previewText; }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T09:24:03.050", "Id": "31839", "Score": "0", "body": "I do have an article management class with functions to prepare and modify strings.. I will use singletons for some things like the DisplayEngine and the Bread crumbs (already done), but static for other things such as the Config file. Thanks for your help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T10:17:59.540", "Id": "31844", "Score": "0", "body": "The article management class is the parent of the class i use to retrieve row or rows from the DB (this way i can use the same object to perform manipulations).. I haven't started using interfaces yet, still don't really understand the need for them unless you are sharing code in a team (I'm not, and don't intend to).. and type hinting is on the to do list!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T11:43:20.247", "Id": "19889", "ParentId": "19888", "Score": "2" } }, { "body": "<p><strong>Does my OOP suck?</strong></p>\n\n<p>I don't know, I'm not seeing much OOP. I am seeing a bunch of static calls, which are completely contrary to the whole OOP concept. As far as the singleton suggested by scragar, you should avoid those as well. They are usually considered bad practice. See this <a href=\"https://stackoverflow.com/a/8776814/1015656\">answer on SO</a> for more details. For the purposes you are employing, I would suggest that a simple helper function should suffice. No need for a full class if all you are doing is parsing the URL.</p>\n\n<p><strong>is running multiple methods on a value a terrible way to manage resources?</strong></p>\n\n<p>Let's take a look.</p>\n\n<pre><code>strip_tags($copy-&gt;truncateString($articles[$i]['body'], 250, \" \"));\n\n//compared to...\n$maxLength = 250;//should be a config constant\n$body = $article[ 'body' ];\n$truncated = $copy-&gt;truncateString( $body, $maxLength, ' ' );\n$synopse = strip_tags( $truncated );\n</code></pre>\n\n<p>It's a little more verbose, but much easier to read and understand what is going on. You have labeled your magic number, you have labeled your text to be modified, and you have separated the modifications (allowing for further steps to be added/removed if/as necessary). This goes along with that \"Max Line Length\" scragar mentioned in his answer. Usually you will want to limit your lines of code to 80 characters, including indentation. Why 80? Well, its commonly accepted that most displays will display at least 80 characters and older machines/tools used to limit the display to just 80. Asides from this, the main reason for this rule of thumb is to avoid complex, difficult to read, code. Usually this is easiest to see with long lines of code, but can just as easily be seen with the smaller, such as this.</p>\n\n<p>Something you may want to consider is creating a method to accomplish this for you. You can probably create these synopsis when you create the <code>$articles</code> array and append it to that allowing for much easier access during rendering. (<code>$article[ 'synopse' ];</code> ).</p>\n\n<p><strong>Should I create separate methods to use for the following line:</strong></p>\n\n<p>I'd suggest separating the logic from the display. These are two entirely separate concerns, and as such violate the Separation of Concerns (SoC) Principle. The rule of thumb here is that you should avoid having PHP render your HTML in case something happens and it stops working, otherwise you could just end up with a blank page. Your pages should always, minimally, work without PHP. Usually you would use HTML with only minor, absolutely necessary, PHP to render your view and default text should something happen. This also helps with legibility and allows for features such as tag matching/highlighting and proper auto-complete to work in your IDE.</p>\n\n<pre><code>&lt;?php foreach( $articles AS $article ) : ?&gt;\n\n&lt;div class=\"summary\"&gt;\n &lt;a href=\"&lt;?php echo $breadcrumbs . $article[ 'id' ]; ?&gt;\"&gt;\n &lt;h5&gt;$article[ 'title' ]&lt;/h5&gt;\n &lt;/a&gt;\n (&lt;?php echo $article[ 'date' ]; ?&gt;)\n &lt;p&gt;\n &lt;?php\n //enter code from above here\n ?&gt;\n &lt;/p&gt;\n &lt;p&gt;\n &lt;a href=\"&lt;?php echo $breadcrumbs . $article[ 'id' ]; ?&gt;\"&gt;\n Read more\n &lt;/a&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n\n&lt;?php endforeach; ?&gt;\n</code></pre>\n\n<p><strong>Edit for clarity on includes</strong></p>\n\n<p>article.inc</p>\n\n<pre><code>&lt;div class=\"summary\"&gt;\n &lt;a href=\"&lt;?php echo $breadcrumbs . $article[ 'id' ]; ?&gt;\"&gt;\n &lt;h5&gt;$article[ 'title' ]&lt;/h5&gt;\n &lt;/a&gt;\n (&lt;?php echo $article[ 'date' ]; ?&gt;)\n &lt;p&gt;\n &lt;?php\n //enter code from above here\n ?&gt;\n &lt;/p&gt;\n &lt;p&gt;\n &lt;a href=\"&lt;?php echo $breadcrumbs . $article[ 'id' ]; ?&gt;\"&gt;\n Read more\n &lt;/a&gt;\n &lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>page where include is used</p>\n\n<pre><code>&lt;?php foreach( $articles AS $article ) :\n include article.php;\nendforeach; ?&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T09:35:58.753", "Id": "31840", "Score": "0", "body": "Thanks for taking the time mseancole. **::1::** What do you mean you only see static calls? Have I not understood the object model enough? I figured I was passing data and other objects to objects that react to what has passed onto them? Not OOP?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T09:36:22.340", "Id": "31841", "Score": "0", "body": "**::2::** I see how the more verbose code is easier to expand, I'm a little wary of having too many lines of code.. but I guess that i should stick to the \"readability is better than efficiency\" adage. I am creating a separate class with the method to handle this though, as per scrager (and your) suggestion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T09:38:48.880", "Id": "31842", "Score": "0", "body": "**::3::** The problem with separating the HTML is that i will be repeating myself a lot. On a page with a list of articles, each article is a divs within divs.. I understand the possibility of ending up with blank pages, but how else do I achieve DRY? Is DRY only for the PHP? and not for the HTML? Thanks for your suggestions and the link. I will read more on it, and hopefully reach a better technique." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T09:50:42.200", "Id": "31843", "Score": "0", "body": "Also, doing some reading, it seems singletons are \"bad practice\" because it has hard-coded object references inside the class. But I don't actually do that.. I use getters and setters and pass variables along. With every method, my primary goal is decoupling. Every function I have either uses an unchangeable static variable (using a getter) from the Config class, or has the data to manipulate passed to it..... **If, as popularly claimed, the learning curve for OOP is 2 years long, then I reckon I am at about the 8 month mark. So thanks for any advice!**" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T10:29:40.797", "Id": "31845", "Score": "0", "body": "Also, just wanted to add.. I am using URL Rewriting and the breadcrumbs class to manage site content. Everything is being handled by the index.php page. thought that might be important info to know." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T22:59:00.180", "Id": "31863", "Score": "0", "body": "1: Static contradicts OOP. The main thing here is the lack of flexibility. OOP should allow for classes to share information and change it, else you are stuck with a codebase that has to be duplicated each time you need to make a change. Static has its place, but rarely ever does it come up. 2: There's no such thing as too many lines of code; There's always just enough. It is not even a matter of efficiency, the two should be equally efficient, or close enough to it to make no difference. Legibility should always be first. 3: The solution is to create an include and include it as necessary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T07:29:24.947", "Id": "31868", "Score": "0", "body": "1: Classes sharing information involves lots of coupling, this makes no sense to me. I thought the idea was decoupling. Which I am doing. 2: Ok. 3: An Include doesn't change the fact that I have to write out each block of div tags for each article on a list page. why? when I can put it all in a loop and then write it just once. What if I decide to change or add a css class to the divs.. i have to do it 10 times in the included template? whats the point? Forgive me.. but i really don't get it. this sounds counterproductive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T07:34:41.680", "Id": "31869", "Score": "0", "body": "I wish there were classes i could take in my part of the world.. It seems I need to go back to square 1 and rethink OOP again.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T14:26:36.410", "Id": "31878", "Score": "0", "body": "@obmon: 1: I meant share as in polymorphism. The ability for a class to be extended easily by sharing its properties and methods with a child class. That's a little harder to do with static properties/methods. Even if you aren't doing it now, having the ability to easily allow for it is the main purpose of OOP. 3: I don't think we are on the same page here. Give me a few and I'll edit the bottom section of my answer to demonstrate for you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T18:48:35.973", "Id": "31885", "Score": "0", "body": "Thanks. Let me edit my original post and add the structure of the code \"library\" that I'm building to give you a better idea.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T19:29:50.080", "Id": "31889", "Score": "0", "body": "Ah.. now I see what you mean.. this makes me want to ask, is this a greater resource hog? best practice to use lots of includes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T19:38:53.997", "Id": "31890", "Score": "0", "body": "Nevermind.. my question has been answered here: http://stackoverflow.com/questions/3589117/using-too-many-php-includes-a-bad-idea" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T20:01:47.113", "Id": "31892", "Score": "1", "body": "The only way that would ever be a resource hog is if you were to use the `*_once()` versions numerous times. And I mean quite a few times, hundreds maybe even thousands. I don't know the exact limit, I've never reached it. But that's only because PHP has to ensure that the included page hasn't already been included. That's why the `*_once()` versions should be avoided unless absolutely necessary." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T15:02:41.303", "Id": "19895", "ParentId": "19888", "Score": "2" } } ]
{ "AcceptedAnswerId": "19895", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T11:12:42.720", "Id": "19888", "Score": "4", "Tags": [ "php", "object-oriented" ], "Title": "Rendering articles with breadcrumb navigation" }
19888
<p>There is no doubt that Knockout.js is a very useful tool, which will save you from a lot of JavaScript (jQuery) binding hassle, which will reduce your team's bug ratio concerning this part.</p> <p>But unfortunately, its JavaScript part gets ugly sooner than you can imagine. The resulting unreadable code is killing me and my team.</p> <p><a href="http://knockoutjs.com/examples/twitter.html" rel="nofollow">Here</a> you can find a simple example from the official website.</p> <p>This is an official example:</p> <pre><code>var savedLists = [ { name: "Celebrities", userNames: ['JohnCleese', 'MCHammer', 'StephenFry', 'algore', 'StevenSanderson']}, { name: "Microsoft people", userNames: ['BillGates', 'shanselman', 'ScottGu']}, { name: "Tech pundits", userNames: ['Scobleizer', 'LeoLaporte', 'techcrunch', 'BoingBoing', 'timoreilly', 'codinghorror']} ]; var TwitterListModel = function(lists, selectedList) { this.savedLists = ko.observableArray(lists); this.editingList = { name: ko.observable(selectedList), userNames: ko.observableArray() }; this.userNameToAdd = ko.observable(""); this.currentTweets = ko.observableArray([]) this.findSavedList = function(name) { var lists = this.savedLists(); return ko.utils.arrayFirst(lists, function(list) { return list.name === name; }); }; this.addUser = function() { if (this.userNameToAdd() &amp;&amp; this.userNameToAddIsValid()) { this.editingList.userNames.push(this.userNameToAdd()); this.userNameToAdd(""); } }; this.removeUser = function(userName) { this.editingList.userNames.remove(userName) }.bind(this); this.saveChanges = function() { var saveAs = prompt("Save as", this.editingList.name()); if (saveAs) { var dataToSave = this.editingList.userNames().slice(0); var existingSavedList = this.findSavedList(saveAs); if (existingSavedList) existingSavedList.userNames = dataToSave; // Overwrite existing list else this.savedLists.push({ name: saveAs, userNames: dataToSave }); // Add new list this.editingList.name(saveAs); } }; this.deleteList = function() { var nameToDelete = this.editingList.name(); var savedListsExceptOneToDelete = $.grep(this.savedLists(), function(list) { return list.name != nameToDelete }); this.editingList.name(savedListsExceptOneToDelete.length == 0 ? null : savedListsExceptOneToDelete[0].name); this.savedLists(savedListsExceptOneToDelete); }; ko.computed(function() { // Observe viewModel.editingList.name(), so when it changes (i.e., user selects a different list) we know to copy the saved list into the editing list var savedList = this.findSavedList(this.editingList.name()); if (savedList) { var userNamesCopy = savedList.userNames.slice(0); this.editingList.userNames(userNamesCopy); } else { this.editingList.userNames([]); } }, this); this.hasUnsavedChanges = ko.computed(function() { if (!this.editingList.name()) { return this.editingList.userNames().length &gt; 0; } var savedData = this.findSavedList(this.editingList.name()).userNames; var editingData = this.editingList.userNames(); return savedData.join("|") != editingData.join("|"); }, this); this.userNameToAddIsValid = ko.computed(function() { return (this.userNameToAdd() == "") || (this.userNameToAdd().match(/^\s*[a-zA-Z0-9_]{1,15}\s*$/) != null); }, this); this.canAddUserName = ko.computed(function() { return this.userNameToAddIsValid() &amp;&amp; this.userNameToAdd() != ""; }, this); // The active user tweets are (asynchronously) computed from editingList.userNames ko.computed(function() { twitterApi.getTweetsForUsers(this.editingList.userNames(), this.currentTweets); }, this); }; ko.applyBindings(new TwitterListModel(savedLists, "Tech pundits")); // Using jQuery for Ajax loading indicator - nothing to do with Knockout $(".loadingIndicator").ajaxStart(function() { $(this).fadeIn(); }).ajaxComplete(function() { $(this).fadeOut(); }); </code></pre> <p>And of course, we have in our code base a lot more worse examples than that. Really bad ones, especially with a more complicated business.</p> <p>So, do anyone know how to make Knockout.js's code more elegant and readable?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T16:54:12.847", "Id": "31809", "Score": "2", "body": "This site is for reviewing code. While your statement may be true, a working illustration with actual code would help and follows the [FAQ](http://codereview.stackexchange.com/faq#questions). If you have some code to add to demonstrate your point, then you should do so, otherwise this will get closed as being off topic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T17:03:04.223", "Id": "31810", "Score": "0", "body": "@mseancole sorry, I was talking about the normal way knockout.js is handling his code, and how we can use his ViewModel & Model in a cleaner way, anyway I included a code demonstrating how knockout.js can make code worse" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T17:52:57.393", "Id": "31811", "Score": "1", "body": "@AbdelHadyMu Post an excerpt of your own code. It's easier to discuss a specific, real example than to talk about knockout in the abstract." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T20:28:08.613", "Id": "31816", "Score": "0", "body": "@mcknz I do understand your point, but I really mean that Knockout.js do have a readability problem from defining `this.foo = function(){}` (and all in one viewModel where you can't reach the viewModel parameters easily) to defining ViewModel with its Models in the same file, for example I have tried to separate the inline functions, but then knockout didn't work, and so on" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T20:38:49.740", "Id": "31817", "Score": "0", "body": "@AbdelHadyMu that's what I mean -- perhaps you could post the examples where you tried to separate the inline functions. Without seeing the code, we don't know if it's an issue with Knockout, or with your implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T15:55:40.613", "Id": "31850", "Score": "1", "body": "this is not ugly code , this is proper MVVM implementation , can you please tell us which part of code is ugly or you want to refactor" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-14T07:13:10.437", "Id": "52244", "Score": "0", "body": "The whole code is in the `constructor` function. That's what is ugly. Make use of `TwitterListModel.prototype`." } ]
[ { "body": "<p>The sample code from knockout probably just wants to show what can be done, not how it ought to be done. ( You messed up indenting btw ).</p>\n\n<p>If this were my code, I would have 3 or 4 models/objects: </p>\n\n<ul>\n<li>Groups<br>\n<ul>\n<li>get ( aka findSavedList ) </li>\n<li>save ( aka saveChanges )</li>\n<li>remove ( aka deleteList )</li>\n<li>isDirty ( aka hasUnsavedChanges ) -> You might consider a Group model?</li>\n</ul></li>\n<li>UserList \n<ul>\n<li>add ( aka addUser )</li>\n<li>remove ( aka removeUser )</li>\n<li>isDirty ( to be called from Group(s) )</li>\n</ul></li>\n<li>User\n<ul>\n<li>isNameValid( userNameToAddIsValid )</li>\n</ul></li>\n</ul>\n\n<p>Furthermore,</p>\n\n<p><code>ko.computed()</code> seems funny, I feel this really belongs to the C in MVC, the controller should create the model and pass that model to the <code>ko.computed</code>s.</p>\n\n<p><code>userNameToAddIsValid</code> and <code>canAddUserName</code> seem a mess, they can be merged.</p>\n\n<p>So, in essence, this model is doing too much. Maybe your ugly models are doing too much as well. As mcknz mentioned, please post your awful code ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T15:45:16.423", "Id": "37141", "ParentId": "19900", "Score": "3" } }, { "body": "<p>Quick solution, and not specific to knockout: I'd declare a variable up high in your constructor:</p>\n\n<pre><code>var instance = this;\n</code></pre>\n\n<p>and replace \"this\" with \"instance\" later in the class. You can use a variable name of your choosing, of course, but please bear with me. </p>\n\n<p>My rationale is this thing I experience, as a senior developer, called \"code fatigue\". Simply stated, it's which \"this\" is \"this\"? I do much more c#, where (a) in-scope properties of the current class don't have to be prefixed with \"this\" and (b) best practice is one class per file -- which can be done in JS, but has to be planned out because of dependency issues. </p>\n\n<p>So, my train of thought is that one of your devs is tasked to do a quick fix on something buggy. Let's He (she) is directed to look at a single function somewhere in a monster Javascript file. Let's say it's a junior developer, to add to the foray. And those \"this\" references are everywhere. It's INSTANTLY confusing to trace back up to the origin of \"this\", most especially if the code isn't formatted for viewing. But if you abstract the scope-level \"this\" into a neat, uniquely NAMED variable, it's a cleaner point of reference and takes the guesswork out.</p>\n\n<p>Just a thought.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T19:48:23.947", "Id": "68392", "Score": "0", "body": "**this** is really a good idea, I have heard **this** from other JavaScript programmers as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T19:49:54.283", "Id": "68393", "Score": "0", "body": "You'll get an up-vote from me as soon as I get my votes back!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T20:04:47.597", "Id": "68396", "Score": "0", "body": "If it is clear that we want to refer to the current object instance, then `self` instead of `this` may be a good solution, as that's the default convention in many languages (Smalltalk, Python, Perl, …)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T00:17:19.633", "Id": "68418", "Score": "1", "body": "My point for this was to de-genericize \"this\". \"self\" is usable also but I think the use of both of them can be quickly confusing in any situation where the code is written such that contexts are nested. I don't like to have to guess. Here's an example: http://jsfiddle.net/sZ4W8/" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T17:58:35.397", "Id": "39016", "ParentId": "19900", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T16:30:46.160", "Id": "19900", "Score": "5", "Tags": [ "javascript", "knockout.js" ], "Title": "How to enhance the readability of JavaScript part?" }
19900
<p>My solution to this feels 'icky' and I've got calendar math falling out of my ears after working on similar problems for a week so I can't think straight about this.</p> <p>Is there a better way to code this?</p> <pre><code>import datetime from dateutil.relativedelta import relativedelta def date_count(start, end, day_of_month=1): """ Return a list of datetime.date objects that lie in-between start and end. The first element of the returned list will always be start and the last element in the returned list will always be: datetime.date(end.year, end.month, day_of_month) If start.day is equal to day_of_month the second element will be: start + 1 month If start.day is after day_of_month then the second element will be: the day_of_month in the next month If start.day is before day_of_month then the second element will be: datetime.date(start.year, start.month, day_of_month) &gt;&gt;&gt; start = datetime.date(2012, 1, 15) &gt;&gt;&gt; end = datetime.date(2012, 4, 1) &gt;&gt;&gt; date_count(start, end, day_of_month=1) #doctest: +NORMALIZE_WHITESPACE [datetime.date(2012, 1, 15), datetime.date(2012, 2, 1), datetime.date(2012, 3, 1), datetime.date(2012, 4, 1)] Notice that it's not a full month between the first two elements in the list. If you have a start day before day_of_month: &gt;&gt;&gt; start = datetime.date(2012, 1, 10) &gt;&gt;&gt; end = datetime.date(2012, 4, 1) &gt;&gt;&gt; date_count(start, end, day_of_month=15) #doctest: +NORMALIZE_WHITESPACE [datetime.date(2012, 1, 10), datetime.date(2012, 1, 15), datetime.date(2012, 2, 15), datetime.date(2012, 3, 15), datetime.date(2012, 4, 15)] Notice that it's not a full month between the first two elements in the list and that the last day is rounded to datetime.date(end.year, end.month, day_of_month) """ last_element = datetime.date(end.year, end.month, day_of_month) if start.day == day_of_month: second_element = start + relativedelta(start, months=+1) elif start.day &gt; day_of_month: _ = datetime.date(start.year, start.month, day_of_month) second_element = _ + relativedelta(_, months=+1) else: second_element = datetime.date(start.year, start.month, day_of_month) dates = [start, second_element] if last_element &lt;= second_element: return dates while dates[-1] &lt; last_element: next_date = dates[-1] + relativedelta(dates[-1], months=+1) next_date = datetime.date(next_date.year, next_date.month, day_of_month) dates.append(next_date) dates.pop() dates.append(last_element) return dates </code></pre>
[]
[ { "body": "<p>How about...</p>\n\n<pre><code>def date_count(start, end, day_of_month=1):\n dates = [start]\n next_date = start.replace(day=day_of_month)\n if day_of_month &gt; start.day:\n dates.append(next_date)\n while next_date &lt; end.replace(day=day_of_month):\n next_date += relativedelta(next_date, months=+1)\n dates.append(next_date)\n return dates\n</code></pre>\n\n<p>And by the way it seems like a nice opportunity to use yield, if you wanted to.</p>\n\n<pre><code>def date_count2(start, end, day_of_month=1):\n yield start\n next_date = start.replace(day=day_of_month)\n if day_of_month &gt; start.day:\n yield next_date\n while next_date &lt; end.replace(day=day_of_month):\n next_date += relativedelta(next_date, months=+1)\n yield next_date\n</code></pre>\n\n<p>Another possibility - discard the first value if it is earlier than the start date:</p>\n\n<pre><code>def date_count(start, end, day_of_month=1):\n dates = [start.replace(day=day_of_month)]\n while dates[-1] &lt; end.replace(day=day_of_month):\n dates.append(dates[-1] + relativedelta(dates[-1], months=+1))\n if dates[0] &gt; start:\n return [start] + dates\n else:\n return [start] + dates[1:]\n</code></pre>\n\n<p>Or use a list comprehension to iterate over the number of months between start and end.</p>\n\n<pre><code>def date_count(start, end, day_of_month=1):\n round_start = start.replace(day=day_of_month)\n gap = end.year * 12 + end.month - start.year * 12 - start.month + 1\n return [start] + [round_start + relativedelta(round_start, months=i) \n for i in range(day_of_month &lt;= start.day, gap)]\n</code></pre>\n\n<p>Finally, I don't know dateutil but <a href=\"http://labix.org/python-dateutil#head-470fa22b2db72000d7abe698a5783a46b0731b57\" rel=\"nofollow\">it seems you can use <code>rrule</code></a>:</p>\n\n<pre><code>from dateutil import rrule\ndef date_count(start, end, day_of_month=1):\n yield start\n for date in rrule(MONTHLY, \n dtstart=start.replace(day=day_of_month),\n until=end.replace(day=day_of_month)):\n if date &gt; start:\n yield date\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T22:38:05.560", "Id": "31862", "Score": "0", "body": "Excellent answer. Not sure which solution I will use, but thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T22:52:39.313", "Id": "19907", "ParentId": "19903", "Score": "3" } } ]
{ "AcceptedAnswerId": "19907", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T19:49:00.440", "Id": "19903", "Score": "6", "Tags": [ "python", "datetime" ], "Title": "Building a list of dates between two dates" }
19903
<p>I always seem to struggle refactoring my code. I can look at any other code and know exactly what is going on, but when it comes to cleaning up my code, I get writers block. </p> <p>The following code works, but I know if can be done much nicer, and with few lines of code. I just wanted to wrap a memcache client to use one server for testing and another for dev/prod or just fetch the value if it cannot connect to the server.</p> <p>Any tips on refactoring, etc. are much appreciated. </p> <pre><code>require 'dalli' class Cache def self.fetch(key, ttl, &amp;block) if memcache memcache.fetch(key, ttl, &amp;block) else block.call end end def self.memcache begin if(ENV['RACK_ENV'] == :production or ENV['RACK_ENV'] == :development) @memcache ||= Dalli::Client.new('cache.amazonaws.com:11211') else @memcache ||= Dalli::Client.new('localhost:11211') end rescue Exception =&gt; e false end end end </code></pre>
[]
[ { "body": "<p>This DRY's the code in <code>self.memcache</code> and simply uses a ternary operator for <code>self.fetch</code>.</p>\n\n<pre><code>require 'dalli'\nclass Cache\n def self.fetch(key, ttl, &amp;block)\n memcache ? memcache.fetch(key, ttl, &amp;block) : block.call\n end\n\n def self.memcache\n @memcache ||= Dalli::Client.new((ENV['RACK_ENV'] == :production or ENV['RACK_ENV'] == :development) ?\n 'cache.amazonaws.com:11211' :\n 'localhost:11211')\n rescue Exception\n false\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T23:35:29.467", "Id": "31824", "Score": "0", "body": "The begin and end keywords you get for free inside the block that is a method definition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T19:56:38.303", "Id": "31891", "Score": "1", "body": "I'd change some indentation and blank lines, but basically this is it. One important thing though: dont' write `rescue Exception`, always `rescue StandardError`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T22:04:50.603", "Id": "31901", "Score": "1", "body": "Generally true, tokland, but Exception was what was given in the original question, so rather than assume they are rescuing the wrong thing, I stuck with it. It was not clear what they intended to rescue, though that is likely overreaching. I am sure it wasn't a comment to me, though, I am just saying. The indentation is only there to show a new user what the important part of the above line is, which is to indicate the two options below would be resulting in that parenthesis level. I tried to not affect behavior, only what they asked for. @gp, you want to answer about Exception choice?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T23:20:18.613", "Id": "19908", "ParentId": "19904", "Score": "3" } }, { "body": "<p>I'd write it like this, if I really want to have <code>fetch</code> as a class method. If that is not mandatory, I would make <code>fetch</code> the only public instance method, and the rest private instance methods.</p>\n\n<pre><code> require 'dalli'\n\n class Cache\n def self.fetch(key, ttl, &amp;block)\n memcache ? memcache.fetch(key, ttl, &amp;block) : block.call\n end\n\n def self.memcache\n @memcache ||= new_client\n end\n\n def self.new_client\n begin\n Dalli::Client.new(memcache_host)\n rescue StandardError\n false\n end\n end\n\n def self.memcache_host\n (production? || development?) ? 'cache.amazonaws.com:11211' : 'localhost:11211' \n end\n\n def self.production?\n environment == :production\n end\n\n def self.development?\n environment == :development\n end\n\n def self.environment\n ENV['RACK_ENV']\n end\n end\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-30T08:26:36.613", "Id": "32008", "Score": "0", "body": "I like it. Still the begin and end are implicit by virtue of being in a block, this block being the method definition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-30T13:26:20.857", "Id": "32019", "Score": "0", "body": "I just don't like the un-indented `rescue`. Same as the indented or un-indented `private` statement, some like it one way, others like the other :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T03:53:02.980", "Id": "20013", "ParentId": "19904", "Score": "2" } }, { "body": "<p>I would do it like the following:</p>\n\n<pre><code>require 'dalli'\nclass Cache\n def self.fetch(key, ttl, &amp;block)\n memcache and\n memcache.fetch(key, ttl, &amp;block) or\n block.call\n end\n\n def self.host\n @host ||= (ENV['RACK_ENV'] == :production || ENV['RACK_ENV'] == :development) ?\n 'cache.amazonaws.com:11211' :\n 'localhost:11211'\n end\n\n def self.memcache \n @memcache ||= Dalli::Client.new(host)\n rescue StandardError\n nil\n end\nend\n</code></pre>\n\n<p>I prefer returning <code>nil</code> instead of <code>false</code> on methods that would otherwise return an object on success. If it returns <code>false</code> on failure, then it should return <code>true</code> on success, but that would then change the method's name to <code>memcache</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-22T23:24:23.257", "Id": "141966", "Score": "0", "body": "I've downvoted this answer. `Cache::fetch` and `Cache::host` are confusing. The the ternary disguised as and `and`/`or` is ambiguous (`(a and b) or c` or `a and (b or c)`). The ternary in `Cache::host`, like the one in `Cache::fetch` is so long, it's split it into multiple lines. They would both be clearer as regular `if` statements. `Cache::memcache` silently swallows *every* exception inheriting from `StandardError`, making debugging hard. Introducing `Cache::host` is a good decision, it makes `Cache::memcache` clear and concise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-23T03:03:24.630", "Id": "141976", "Score": "0", "body": "If you know Ruby, you should know that the `and` and `or` operators behave similarly to bash's `&&` and `||`. So order of operation should be a non-issue. It's like saying `(5 * 3) + 2`. Redundant. Long ternary operations are non-issue. If we look at David's answer, where he split the env check into their own functions, it can be a good idea if the rest of the system also could take advantage of the env check. But from the question alone, we don't know if that's even needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-23T09:06:52.673", "Id": "142004", "Score": "0", "body": "The precedence rules for `and`/`or` are unintuitive (and, more importantly, different from the more popular `&&`/`||`!). I have to look them up all the time. I had to look quite a bit longer at the `and`/`or` construction in `Cache::fetch` to recognize it as a simple if statement. An if statement would have made it crystal clear that it is an if statement. Fun example: `a = nil or \"foo\"` (`a` is now `nil`, but the return value is `\"foo\"`)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-22T22:21:50.280", "Id": "78369", "ParentId": "19904", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T20:35:35.003", "Id": "19904", "Score": "5", "Tags": [ "ruby", "cache" ], "Title": "Using Dalli to connect to memcached" }
19904
<p>Is this code (also available at <a href="https://github.com/andrewcooke/simple-crypt/blob/master/src/simplecrypt/__init__.py" rel="nofollow">github</a> with <a href="https://github.com/andrewcooke/simple-crypt/blob/master/src/simplecrypt/tests.py" rel="nofollow">tests</a>, <a href="https://github.com/andrewcooke/simple-crypt/blob/master/src/simplecrypt/example.py" rel="nofollow">example</a>, and <a href="https://github.com/andrewcooke/simple-crypt#algorithms" rel="nofollow">description of algorithms</a>) correct and secure? It follows the recommendations <a href="http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html" rel="nofollow">here</a> as far as I can tell.</p> <pre><code>from Crypto.Cipher import AES from Crypto.Hash import SHA256, HMAC from Crypto.Protocol.KDF import PBKDF2 from Crypto.Random.random import getrandbits from Crypto.Util import Counter EXPANSION_COUNT = 10000 AES_KEY_LEN = 256 SALT_LEN = 128 HASH = SHA256 HEADER = b'sc\x00\x00' # lengths here are in bits, but pcrypto uses block size in bytes HALF_BLOCK = AES.block_size*8//2 assert HALF_BLOCK &lt;= SALT_LEN # we use a subset of the salt as nonce def encrypt(password, data): ''' Encrypt some data. Input can be bytes or a string (which will be encoded using UTF-8). @param password: The secret value used as the basis for a key. This should be as long as varied as possible. Try to avoid common words. @param data: The data to be encrypted. @return: The encrypted data, as bytes. ''' data = _str_to_bytes(data) _assert_encrypt_length(data) salt = _random_bytes(SALT_LEN//8) hmac_key, cipher_key = _expand_keys(password, salt) counter = Counter.new(HALF_BLOCK, prefix=salt[:HALF_BLOCK//8]) cipher = AES.new(cipher_key, AES.MODE_CTR, counter=counter) encrypted = cipher.encrypt(data) hmac = _hmac(hmac_key, HEADER + salt + encrypted) return HEADER + salt + encrypted + hmac def decrypt(password, data): ''' Decrypt some data. Input must be bytes. @param password: The secret value used as the basis for a key. This should be as long as varied as possible. Try to avoid common words. @param data: The data to be decrypted, typically as bytes. @return: The decrypted data, as bytes. If the original message was a string you can re-create that using `result.decode('utf8')`. ''' _assert_not_string(data) _assert_header_sc(data) _assert_header_version(data) _assert_decrypt_length(data) raw = data[len(HEADER):] salt = raw[:SALT_LEN//8] hmac_key, cipher_key = _expand_keys(password, salt) hmac = raw[-HASH.digest_size:] hmac2 = _hmac(hmac_key, data[:-HASH.digest_size]) _assert_hmac(hmac_key, hmac, hmac2) counter = Counter.new(HALF_BLOCK, prefix=salt[:HALF_BLOCK//8]) cipher = AES.new(cipher_key, AES.MODE_CTR, counter=counter) return cipher.decrypt(raw[SALT_LEN//8:-HASH.digest_size]) class DecryptionException(Exception): pass class EncryptionException(Exception): pass def _assert_not_string(data): # warn confused users if isinstance(data, str): raise DecryptionException('Data to decrypt must be bytes; ' + 'you cannot use a string because no string encoding will accept all possible characters.') def _assert_encrypt_length(data): # for AES this is never going to fail if len(data) &gt; 2**HALF_BLOCK: raise EncryptionException('Message too long.') def _assert_decrypt_length(data): if len(data) &amp;lt; len(HEADER) + SALT_LEN//8 + HASH.digest_size: raise DecryptionException('Missing data.') def _assert_header_sc(data): if len(data) &amp;lt; 2 or data[:2] != HEADER[:2]: raise DecryptionException('Data passed to decrypt were not generated by simple-crypt (bad header).') def _assert_header_version(data): if len(data) &amp;lt; len(HEADER) or data[:len(HEADER)] != HEADER: raise DecryptionException('The data appear to be encrypted with a more recent version of simple-crypt (bad header). ' + 'Please update the library and try again.') def _assert_hmac(key ,hmac, hmac2): # https://www.isecpartners.com/news-events/news/2011/february/double-hmac-verification.aspx if _hmac(key, hmac) != _hmac(key, hmac2): raise DecryptionException('Bad password or corrupt / modified data.') def _expand_keys(password, salt): if not salt: raise ValueError('Missing salt.') if not password: raise ValueError('Missing password.') key_len = AES_KEY_LEN // 8 # the form of the prf below is taken from the code for PBKDF2 keys = PBKDF2(_str_to_bytes(password), salt, dkLen=2*key_len, count=EXPANSION_COUNT, prf=lambda p,s: HMAC.new(p,s,HASH).digest()) return keys[:key_len], keys[key_len:] def _random_bytes(n): return bytes(getrandbits(8) for _ in range(n)) def _hmac(key, data): return HMAC.new(key, data, HASH).digest() def _str_to_bytes(data): try: return data.encode('utf8') except AttributeError: return data </code></pre> <p>Finally, see also <a href="http://news.ycombinator.com/item?id=4962983" rel="nofollow">this HN thread</a> which identified many issues in an earlier version of the code.</p>
[]
[ { "body": "<p>I'm not a crypto expert, but I see that at least your decryption code is vulnerable to verification timing attacks (see e.g. here: <a href=\"http://rdist.root.org/2009/05/28/timing-attack-in-google-keyczar-library/\">http://rdist.root.org/2009/05/28/timing-attack-in-google-keyczar-library/</a>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T19:03:46.647", "Id": "31960", "Score": "0", "body": "you're right, thanks, although it has been fixed since i posted here (i now compare the hash of the hmacs). i will update the code in the question (for the record i had `if hmac != hmac2`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T21:01:14.557", "Id": "31966", "Score": "0", "body": "@andrewcooke, comparing hashes of hmacs is still a verification timing vulnarability, only of a different kind. You have to switch to a constant-time comparison method which executes in exactly the same time regardless of the string possible inequality location, the referenced page contains one such algorithm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T22:13:02.127", "Id": "31971", "Score": "0", "body": "it's the solution described here https://www.isecpartners.com/news-events/news/2011/february/double-hmac-verification.aspx - can you explain why that's wrong? is it a different problem? they argue (afaict) that it's equivalent to a constant time comparison (that link is in the code next to the comparison)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T23:12:10.207", "Id": "31974", "Score": "0", "body": "@andrewcooke, double hashing makes this vulnerability much harder to exploit, but if you approach this from the cryptographer's point of view (in terms of a game played by an adversary against your crypto implementation), then this \"new\" approach still does disclose *some* information about the ciphertext, while a proper algorithm must disclose no information. It is not easily exploitable under current knowledge, but as usual this is just a matter of time and theory. I don't understand why not simply use a constant time implementation which is proven to be resistant to this attack." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T23:21:36.430", "Id": "31975", "Score": "0", "body": "i want code that follows clear guidelines from standard authorities. as far as i can see that reference is clear and authoritative. you started by saying you were not an expert. now you are arguing against an article by someone who, as far as i can tell, is. in my (unexpert) opinion, either is fine. edit: hmm, although it looks like i may have screwed up my implementation. i will fix that later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T23:41:28.287", "Id": "31977", "Score": "0", "body": "fixed. and thanks again (particularly since there was an error there). this isn't personal. i understand your argument, but my main goal in writing this code is that it is documented behaviour from standard sources (and that i think it makes sense)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T16:33:10.873", "Id": "19997", "ParentId": "19910", "Score": "5" } } ]
{ "AcceptedAnswerId": "19997", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T23:57:37.130", "Id": "19910", "Score": "3", "Tags": [ "python", "security", "cryptography" ], "Title": "Simple crypto library in Python" }
19910
<p>I'm working on a game in JavaScript and I'm trying to generate rooms in a map. For this example, the map is 32 by 24 (each tile is 32 by 32 pixels).</p> <p>A room is made up of a collection of tiles. A room is always in a square or rectangle shape. For example, 16,16,8,8 would make a room that draws from the top left corner at 16 by 16 and the bottom right corner at 24 by 24.</p> <p>How the algorithm works:</p> <ol> <li>pick a random x,y, width and height for the room</li> <li>check if these points collide with another room </li> <li>if it fails repeat points 1 and 2 (it will only repeat problems 1 and 2 1000 times before finally giving up and deciding it can't fit any more rooms in)</li> </ol> <p>This is done by this code here:</p> <pre><code> //make sure a room doesn't clash here while (maxTrys &gt; 0) { var x = randomValue(2, tileX - MAXROOMSIZE); //starting top left corner tile's x position var y = randomValue(2, tileY - MAXROOMSIZE);//starting top left corner tile's y position var width = randomValue(MINROOMSIZE, MAXROOMSIZE); //width of room in tiles sqaures e.g 3 = 96 pixels var height = randomValue(MINROOMSIZE, MAXROOMSIZE);//height of room in tiles e.g 3 = 96 pixels if (locationIsFine(x, y, width, height) == true) { //if we've found a location we're happy with roomStore.push(createRoom(i, x, y, width, height)); break; } maxTrys--; } </code></pre> <p>How it checks if a point collides with another room:</p> <ol> <li>generate a room with the randomly created x,y,width and height cordinates</li> <li>check if any point in this "temp room" collides with any point of any other room</li> <li>if it does we know there is a collision</li> </ol> <p>The code for this is the following:</p> <pre><code>var locationIsFine = function(x, y, width, height) { //turn the cordinates into a fake room var tempTiles = new Array(); for (var i = 0; i &lt; width; i++) { for (var j = 0; j &lt; height; j++) { tempTiles.push(new tile(tileset,x+ j,y + i,0,null,ScreenManager)); } } //make sure room wont hit any other rooms, we do this by checking if edges of a room collide with an exisiting room for (var i = 0; i &lt; roomStore.length; i++) { for (var j = 0; j &lt; tempTiles.length; j++) { if (roomStore[i].intersects(tempTiles[j].getX(), tempTiles[j].getY()) == true) { return false; } } } return true; } </code></pre> <p>The intersects method looks like this:</p> <pre><code>this.intersects = function (x,y) { /* find the biggest and smallest points in the room*/ for (var i = 0; i &lt; tiles.length; i++) { if (tiles[i].getX() == x &amp;&amp; tiles[i].getY() == y) { return true; } } return false; } </code></pre> <p>My problem with this is that it is really really slow. After running it a few times, it can take 5-8 seconds to generate the rooms and normally it gives up after the 5th room. I am 100% sure the bottleneck is coming from this code as if I set <code>maxTrys</code> to a smaller number, the program runs quicker.</p>
[]
[ { "body": "<p>In your locationIsFine it seems you check for each room in your roomStore if any of its tiles intersect with a tile inside your new/fake room.</p>\n\n<p>It would probably be worth wile to add some basic checks which (the larger your roomStore will grow, the more it) will reduce the number of checks needed.</p>\n\n<p>This is actually a rectangle intersection problem.\nBetween rectangles, if one isn't completly to the left, right, above or below the other, they will intersect; so checking on that is the fastest way and will save you the check on each and every tile against each and every tile of the other room. This will save you from creating the tilesets for the fake room.</p>\n\n<p>So a start to enhance the algorithm would be this.</p>\n\n<pre><code>var locationIsFine = function(x, y, width, height) {\n //make sure room wont hit any other rooms, we do this by checking if edges of a room collide with an exisiting room\n for (var i = 0; i &lt; roomStore.length; i++) {\n // roomStore[i] completly left or completly right of new room\n if(roomStore[i].X &gt; x+width || roomStore[i].x+roomStore[i].Width &lt; x) continue;\n // roomStore[i] completly above or completly below new room\n if(roomStore[i].Y &gt; y+height || roomStore[i].Y+roomStore[i].Height &lt; y) continue;\n\n //if a room is neither completely to the right nor completely to the left as well as\n //not completly above nor completely below, it will intersect\n return false;\n }\n return true;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T01:27:21.807", "Id": "19912", "ParentId": "19911", "Score": "2" } }, { "body": "<p><strong>1. style</strong> </p>\n\n<p>replace </p>\n\n<pre><code>var x = ...\nvar y = ...\nvar width = ...\nvar height = ...\n</code></pre>\n\n<p>with </p>\n\n<pre><code>var x = ... ,\n y = ... ,\n width = ... ,\n height = ... ,\n</code></pre>\n\n<p>to make it more readable, less verbose, and easier to maintain.</p>\n\n<p><strong>2. performance</strong></p>\n\n<p>replace</p>\n\n<pre><code> for (var i = 0; i &lt; roomStore.length; i++) {\n</code></pre>\n\n<p>with </p>\n\n<pre><code> for (var i = 0, len=roomStore.length; i &lt; len; i++) {\n</code></pre>\n\n<p>to prevent getting the roomStore length on each loop</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T12:23:44.640", "Id": "20118", "ParentId": "19911", "Score": "0" } }, { "body": "<p>Instead of checking a proposed room against all other rooms, try a different algorithm. Let's trade time for space:</p>\n\n<ul>\n<li><p>Create an array representing all grid points, and assign all values to 0. This is a room property, to indicate which room the point belongs to.</p></li>\n<li><p>When a room is placed, update the room id of all member points.</p></li>\n<li><p>To collision detect, just step through the proposed points of a new room checking for pre-existing assignments.</p></li>\n<li><p>Instead of picking a random room position and size chosen at once, pick a random unassigned point; then instead of a random room size, start with the smallest room size and repeatedly expand the room in one direction until you hit another room.</p></li>\n</ul>\n\n<p>When done placing, delete the grid array.</p>\n\n<p>All these combined should allow you to build everything very quickly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-05T09:51:38.567", "Id": "20176", "ParentId": "19911", "Score": "1" } } ]
{ "AcceptedAnswerId": "19912", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T01:13:50.480", "Id": "19911", "Score": "0", "Tags": [ "javascript", "optimization" ], "Title": "Generating rooms in a map" }
19911
<p>I created a function that rewrites file names according to the available space on screen:</p> <pre><code>@{ var index = 0; foreach (var item in Model) { &lt;div class="gallery-item"&gt; &lt;a href="@item.Uri" title="Click to open file" target="_blank" style="display:block; width: 100%;"&gt; var id = "filename_" + ++index; @Html.SpanFor(i =&gt; item.FileName, new { id = id, title = item.FileName, style = "white-space: nowrap;" }) &lt;/a&gt; &lt;/div&gt; } } @section Scripts { &lt;script type="text/javascript"&gt; function adaptWidth(span) { var span = $(span); var origfilename = span.text(); var ext = origfilename.split('.').pop(); var filename = origfilename.substr(0, origfilename.length - ext.length - 1); var text = origfilename; while (span.outerWidth() &gt; span.parent().innerWidth()) { span.text(text = (filename = filename.substr(0, filename.length - 4) + '...') + ext); } } $(document).ready(function () { $('span[id^=filename_]').each(function (i) { adaptWidth(this) }); }); &lt;/script&gt; } </code></pre> <p>Here are the results before and after running script:</p> <p>Before:</p> <p><img src="https://i.stack.imgur.com/VN5B6.png" alt="enter image description here"> </p> <p>After:</p> <p><img src="https://i.stack.imgur.com/kc9d9.png" alt="enter image description here"></p> <p>The function runs quite fast for now, but should I be worried from future impact? Any other suggestion or alternatives? Optimization?</p> <p>I thought about splitting it to 3 spans, 1 for filename, second for <code>...</code>, and 3rd for the extension, but I don't really know how to make the overflow of the first be hidden under the other two. Besides, if a truncation isn't required, it's gonna look weird.</p>
[]
[ { "body": "<p>In general case I would to get text_width and container_width, then <code>calculate new_string_length=container_width/text_width*length</code>, than setup increase or decrease text, depending on result_text_width > container_width and do the loop like yours.</p>\n\n<p>This is really needed only if strings have a very big size.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T03:20:26.583", "Id": "31831", "Score": "0", "body": "1) It's for filenames, how long can a filename be? I guess not too long. 2) I'm affraid you missed out the whole point, the reason I needed this function is because the font is not a fixed-width one, the width varies between the various characters in it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T03:21:57.487", "Id": "31832", "Score": "0", "body": "2) not i not missed, I just think that change length before loop will decrease interations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T03:25:52.557", "Id": "31834", "Score": "1", "body": "fyi in xfs max filename size is 255 bytes, not sure if it big or not, depend how often you plan call such function" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T02:39:16.663", "Id": "19915", "ParentId": "19913", "Score": "4" } }, { "body": "<p>Here are a couple tweeks for your code. I integrated <a href=\"https://codereview.stackexchange.com/a/19915/20138\">@eicto's suggestion</a>, which is the first step in applying an <a href=\"http://en.wikipedia.org/wiki/Interpolation_search\" rel=\"nofollow noreferrer\">interpolated search</a>.</p>\n\n<pre><code>var $spans = $('span'),\n parentWidth = $spans.first().parent().innerWidth();\n\n$spans.each(function () { \n adaptWidth(this, parentWidth);\n});\n\nfunction adaptWidth(elm, maxW) {\n\n // make a var `$elm` so know it's a jQuery object\n var $elm = $(elm),\n // use `lastIndexOf()` to split the filename and\n // extension halves instead of splitting into an array\n fullname = $elm.text(),\n idx = $elm.text().lastIndexOf('.'),\n name = fullname.substr(0, idx),\n ext = fullname.substr(idx),\n // factor is the ratio of the space available for\n // the text vs the space it currently takes up\n factor = maxW / $elm.outerWidth(),\n // idx is a first guess at where the cutoff will be\n idx = (fullname.length+4) * factor;\n\n idx = Math.round(idx);\n\n while ($elm.outerWidth() &gt; maxW) {\n name = name.substr(0, --idx);\n $elm.text(name + '...' + ext);\n }\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/gsHNY/3/\" rel=\"nofollow noreferrer\">The jsFiddle i was testing with.</a></p>\n\n<p>Edit:</p>\n\n<p>A few edits in the text and, per a comment from the OP, updated the code to determine the max-width only once.</p>\n\n<p><sub>As a side-note, <a href=\"http://en.wikipedia.org/wiki/Interpolation_search\" rel=\"nofollow noreferrer\">apparently</a> this type of search is called an <em>interpolation-sequential search</em>.</sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T12:05:13.287", "Id": "31916", "Score": "0", "body": "Since the tiles are shared width, I will check its size only once. Answer updated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T07:39:43.547", "Id": "31948", "Score": "0", "body": "@Shimmy Good to know. I don't see your edit so I added the change." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T10:15:09.023", "Id": "19963", "ParentId": "19913", "Score": "2" } } ]
{ "AcceptedAnswerId": "19963", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T01:58:30.990", "Id": "19913", "Score": "3", "Tags": [ "javascript", "jquery", "file" ], "Title": "Rewriting file names according to the available screen space" }
19913
<p>I have following HTML class collector. Is there a better way than <code>[]tap</code> for this?</p> <pre><code>def tr_classes(user) classes = [].tap do |c| c &lt;&lt; "error" if user.company.nil? c &lt;&lt; "disabled" if user.disabled? end if classes.any? " class=\"#{classes.join(" ")}\"" end end &lt;tr&lt;%= tr_classes(user) %&gt;&gt; &lt;td&gt;&lt;%= user.name %&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre>
[]
[ { "body": "<p>Notes:</p>\n\n<ul>\n<li>This <code>tap</code> usage is not uncommon to see but IMHO it's very, very dubious. You can use a functional approach (see code below).</li>\n<li>I wouldn't return the string along with the attribute, just the array of classes (which Rails3 helpers understand).</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>def tr_classes(user)\n [\n (\"error\" if !user.company),\n (\"disabled\" if user.disabled?),\n ].compact.presence\nend\n</code></pre>\n\n<p>Tables are usually easier to build from helpers. You now would use the function that way:</p>\n\n<pre><code>content_tag(:tr, :class =&gt; tr_classes(user)) do\n content_tag(:td, user.name)\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T12:37:10.563", "Id": "31992", "Score": "0", "body": "Glad somebody suggested `content_tag`; I find opening a `<%= %>` to mess with the individual attributes of an opening HTML tag to be particularly awful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T20:02:17.747", "Id": "19950", "ParentId": "19914", "Score": "3" } }, { "body": "<p>What do you mean a \"better way\" than <code>tap</code>? <strong>Why</strong> are you using <code>tap</code> at all? Initialize an array. Conditionally append items to it. This pattern is as old as time, and there is no reason to shoe-horn in a Ruby-esque solution.</p>\n\n<pre><code>classes = [].tap do |c|\n c &lt;&lt; \"error\" if user.company.nil?\n c &lt;&lt; \"disabled\" if user.disabled?\nend\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>classes = []\nclasses &lt;&lt; \"error\" if user.company.nil?\nclasses &lt;&lt; \"disabled\" if user.disabled?\n</code></pre>\n\n<p>You've added <strong>so much</strong> complexity, both functionally and visually, for literally no gain. You've produced <em>more</em> and <em>uglier</em> code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-02T12:59:49.977", "Id": "32095", "Score": "0", "body": "I also dislike this use of `tap`, but I guess that the OP is using it because it's not uncommon to see. The only good thing about this pattern is that side-effects are confined into a block, that maybe useful with other objects, with an array it's completely overkill." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T12:42:55.283", "Id": "20021", "ParentId": "19914", "Score": "1" } } ]
{ "AcceptedAnswerId": "19950", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T02:28:14.333", "Id": "19914", "Score": "0", "Tags": [ "ruby", "html", "ruby-on-rails" ], "Title": "Refactoring a HTML class collector?" }
19914
<p>I am wondering if someone can take a look at my lock-free, circular ring implementation which I use to implement a background logger.</p> <p>The <code>CircularRing</code> pre-allocates <code>LoggableEntity</code> elements and stores them in an AtomicReferenceArray. Then, I have multiple producer threads which will enqueue elements and single consumer thread which will dequeue elements in a bulk and write them to a storage device.</p> <p>I track the index where the next produced item and the next consumed item should come from. Once the capacity is reached, the indices wrap.</p> <p>My goals behind this implementations are the following:</p> <ol> <li><p>Create a lock free, thread-safe data structure which can store pre-allocated elements.</p></li> <li><p>Producer should never wait to enqueue but rather wrap if the capacity is reached.</p></li> <li><p>The relative order of elements within a producer (thread) must be respected. For example, if <code>producer1</code> and <code>producer2</code> produces A, B, C and P, Q, R at the same time; any interspersing of the elements is fine as long as the relative order is maintained.</p></li> <li><p>Finally, when the consumer index is equal to the producer index; the consumer waits by busy spinning.</p></li> </ol> <p></p> <pre><code>public final class LoggableEntity { private long time; private String message; public static final LoggableEntity getInstance() { return new LoggableEntity(); } //Setters and Getters } public final class CircularRing { private final int ringCapacity; private final int ringCapacityIndex; private final AtomicInteger consumerIndex; private final AtomicInteger producerIndex; private final AtomicReferenceArray&lt;LoggableEntity&gt; ringBuffer; private final static int DEFAULT_BUFFER_CAPACITY = 1024; private final static int DEFAULT_RING_CAPACITY = 16 * 1024; public CircularRing( ) { this( DEFAULT_RING_CAPACITY, DEFAULT_BUFFER_CAPACITY ); } public CircularRing( int ringCapacity, int bufferCapacity ) { this.ringCapacity = ringCapacity; this.ringCapacityIndex = ringCapacity -1; this.consumerIndex = new AtomicInteger( -1 ); this.producerIndex = new AtomicInteger( -1 ); this.ringBuffer = new AtomicReferenceArray&lt;LoggableEntity&gt;( ringCapacity ); for( int i =0; i&lt; ringCapacity; i++ ) { addLazily( i , LoggableEntity.getInstance() ); } } public final int getCurrentConsumerIndex() { return consumerIndex.get(); } public final int getNextConsumerIndex() { return incrementModAndGet( consumerIndex ); } private final int incrementModAndGet( AtomicInteger aInt ) { if ( aInt.get() &lt; ringCapacityIndex ) { return aInt.incrementAndGet(); } else { for (;;) { int current = aInt.get(); int next = (current + 1) % ringCapacity; if( aInt.compareAndSet(current, next) ) return next; } } } public final int getCurrentProducerIndex() { return producerIndex.get(); } public final int getNextProducerIndex() { return incrementModAndGet( producerIndex ); } public final LoggableEntity poll( int index ) { return ringBuffer.get( index ); } public final void addLazily( int index, LoggableEntity entity ) { ringBuffer.lazySet( index, entity ); } </code></pre> <p><strong>Logger</strong></p> <pre><code>public final class CircularSmartLogger { private volatile boolean keepLogging; private final CircularRing circularRing; private final ExecutorService executor; private final BackgroundCircularLogger backLogger; public CircularSmartLogger( int bulkSize ){ this.circularRing = new CircularRing(); this.backLogger = new BackgroundCircularLogger( bulkSize ); this.executor = Executors.newCachedThreadPool(); } public final void init() { keepLogging = true; executor.execute( backLogger ); } public final int getNextProducerIndex( ) { return circularRing.getNextProducerIndex(); } public final LoggableEntity poll( int index ) { return circularRing.poll( index ); } public final void addLazily( int index, LoggableEntity data ) { circularRing.addLazily( index, data ); } public final void stop() { keepLogging = false; } private final class BackgroundCircularLogger implements Runnable { private int pIndex; private int cIndex; private final int bulkSize; public BackgroundCircularLogger( int bulkSize ) { this.pIndex = -1; this.cIndex = -1; this.bulkSize = bulkSize; } @Override public void run( ) { while( keepLogging ) { while ( (cIndex = circularRing.getCurrentConsumerIndex()) == (pIndex = circularRing.getCurrentProducerIndex()) ) { LockSupport.parkNanos( 1L ); } int items = pIndex - cIndex; items = ( items &gt; bulkSize ) ? bulkSize : items; for ( int i =0; i &lt; items; i++ ) { int nextIdx = circularRing.getNextConsumerIndex(); LoggableEntity data = circularRing.poll( nextIdx ); //Write attributes of "data" it to a Storage Device } } } } } </code></pre> <p><strong>Tester</strong></p> <pre><code>public class CircularRingTester { public static void main( String[] args ) { CircularSmartLogger logger = new CircularSmartLogger( 50 ); logger.init(); int next = logger.getNextProducerIndex(); LoggableEntity data = logger.poll( next ); data.setTime( System.currentTimeMillis() ); data.setMessage("This is a simulated message."); logger.addLazily( next, data ); } } </code></pre> <p>Any comments, pointers etc are appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T18:43:34.660", "Id": "31931", "Score": "0", "body": "Why are you exposing the index? The very fact that it's a ring buffer is immaterial; you should implement [java.util.Queue](http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html) or a sub-interface (`BlockingQueue`? assuming this is for learning, otherwise you should probably be using an existing implementation). `final` classes don't need methods marked `final`. Don't instantiate other classes in constructors, inject them instead. `LoggableEntity` should be immutable - your current implementation is not threadsafe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T20:48:51.463", "Id": "31965", "Score": "0", "body": "Thanks but this Ring impl behaves differently from a Queue/BlockingQueue. The ring pre-populates LoggableEntity objects. Poll() returns the object and add() stores it back into the ring. Also, the producer never blocks. I thought of using ConcurrentLinkedQueue but it's quite heavy and I don't need its additional features. The indices are exposed to ensure the atomicity of offers()/puts(). If either of them first look up an index and then stores/removes objects, the method would have to be locked. incrementModAndGet() is indeed broken and I am hoping to find a way to fix it without locking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T21:19:43.010", "Id": "31967", "Score": "0", "body": "Pre-populating your LoggableEntity objects is actually a _problem_ (because they aren't threadsafe). You **conceptually** have a queue, the fact that internally its implemented with a buffer is immaterial; personally, I'd probably use an [ArrayBlockingQueue](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ArrayBlockingQueue.html). Currently, with the producer not blocking, you're overwriting elements that potentially haven't been consumed yet. If the producer shuts down, you will consume elements multiple times. Exposing the indices has no effect on atomicity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T01:40:06.977", "Id": "31983", "Score": "0", "body": "You may find [this](http://codereview.stackexchange.com/q/12691/11913) of interest. It is not what you want but it may be a better starting point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T18:34:12.153", "Id": "32162", "Score": "0", "body": "Thanks @Clockwork-Muse. I am quite sure pre-populating LoggableEntity objects in not a problem. Yes, I could have used a structure that java provides but that doesn't really enable learning or discussions. :) I mean to allow the producers overwrite the older entries. However, what you say is correct that if producer wraps (producer index < writer index), the consumer will write dups. I am working to fix it. Thanks." } ]
[ { "body": "<p>I think there is a synchronization problem in <code>incrementModAndGet</code>. It is not <code>synchronized</code>, thus it can happen that two threads reaches the first if when the current index is at the end of the buffer, both passes the condition and the second that calls to <code>aInt.incrementAndGet()</code> will get an index that is outside of the valid range.</p>\n\n<p>Instead of trying to find a suitable index with mod, why don't you go with one sequence of numbers and use mod when you insert into the ring? I.e. in CircularRing</p>\n\n<pre><code>public final void addLazily( int index, LoggableEntity entity ){\n ringBuffer.lazySet( index % ringCapacity, entity );\n}\n</code></pre>\n\n<p>Also you could sophisticate the tester class somewhat more, by using more threads.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T20:22:19.447", "Id": "31962", "Score": "0", "body": "Thanks Andras. I like your idea of modding when inserting into the ring. I checked and looks like the mod function isn't thread safe either. However, in spite of it, I *think* your solution will work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T20:29:29.347", "Id": "31964", "Score": "0", "body": "To elaborate, since the mod (%) function itself isn't thread safe, I am unsure how addLazily() will behave if multiple threads calls it at the same time.\nTo be honest, my implementation of incrementModAndGet() is broken as well. The else part is atomic where as the if part isn't. I can't think of any other way to make it thread-safe without locking it \n(which defeats the whole purpose of attempting to write a lock-free impl). \nAny additional ideas would be most welcome. Thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T18:14:43.827", "Id": "19975", "ParentId": "19916", "Score": "0" } }, { "body": "<p>If the producers run faster than the consumer, then entries in the CircularRing will eventually be overwritten. This will also expose concurrent access to the LoggableEntity objects, which isn't thread-safe.</p>\n\n<p>When you are doing bulk-reads from the buffer, you can also bulk-increment the consumer index and potentially save CAS instructions.</p>\n\n<p>If this buffer isn't explicitly single-consumer, then the bulk-read code is racy and can run ahead of the producers. Again, potentially causing concurrent access to the LoggableEntities.</p>\n\n<p>Have you considered using the Disruptor library? <a href=\"http://lmax-exchange.github.com/disruptor/\" rel=\"nofollow\">http://lmax-exchange.github.com/disruptor/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T18:27:47.763", "Id": "32160", "Score": "0", "body": "Thanks Christian. I do want to let the producers wrap around the ring and overwrite the older entries. Can you please explain how that would make it not thread-safe? Point well taken about bulk reads. I plan to have just one consumer reading from the buffer and on a second look, consumerIndex variable can just be a volatile int (as opposed to AtomicInteger) as it will only be incremented by one consumer thread. Funny that you mention Disruptor. My ring idea is honorably borrowed from Disruptor :) but I wanted to write my own implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-07T16:07:16.427", "Id": "32365", "Score": "0", "body": "Wrapping around isn't a problem as long as you somehow ensure that you don't overwrite entries that have been consumed. As I read the code (and I could be wrong) it looks like the producer can run ahead of the consumer, overwriting entries that either have not been consumed or are in the process of being consumed, and that's a problem when they are mutable (and mutable entries are part of the point of these kinds of ring-buffers - important for performance by reducing the allocation rate)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T15:32:09.070", "Id": "32430", "Score": "0", "body": "Hi Christian, thanks once again. I have modified the code to include, what disruptor calls a two-phase commit. In phase 1, producer looks up the entity from the next index in the array and modifies it. In phase 2, it stores it back in the array. The background logger now tracks the phase-2 index. So the background thread will only writes those entities which have been modified and stored." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T23:09:44.143", "Id": "20034", "ParentId": "19916", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T03:16:32.837", "Id": "19916", "Score": "2", "Tags": [ "java", "thread-safety", "lock-free", "atomic", "circular-list" ], "Title": "Lock-Free Ring Implementation" }
19916
<p>I have a data structure, containing time span nodes, with the following properties:</p> <ul> <li>Nodes are sorted ascending</li> <li>Time spans will not overlap, but may have gaps between them</li> <li>Each node will have a start datetime and a finish datetime</li> <li>The last node's finish may also be null (not finished yet)</li> </ul> <p>I want to be able to find the node that intersects a given datetime, or return false if no match is found — basically resembling the following sql query for a sql table with similar properties as my data structure:</p> <pre><code>SELECT t.* FROM table t WHERE t.start &lt;= @probeDate AND ( t.finish &gt;= @probeDate OR t.finish IS NULL ) </code></pre> <p>I've concluded that a (variation of a) binary search is probably the most efficient search algorithm. So, this is what I have come up with so far:</p> <pre><code>&lt;?php class Node { protected $start; protected $finish; public function __construct( DateTime $start, DateTime $finish = null ) { $this-&gt;start = $start; $this-&gt;finish = $finish; } public function getStart() { return $this-&gt;start; } public function getFinish() { return $this-&gt;finish; } public function __toString() { /* for easy displaying of the timespan */ return $this-&gt;start-&gt;format( 'H:i:s' ) . ' - ' . ( null !== $this-&gt;finish ? $this-&gt;finish-&gt;format( 'H:i:s' ) : '∞' ); } } class NodeList { protected $nodes; public function __construct( array $nodes = array() ) { $this-&gt;nodes = $nodes; } public function find( DateTime $date ) { $min = 0; $max = count( $this-&gt;nodes ) - 1; return $this-&gt;binarySearch( $date, $min, $max ); } protected function binarySearch( $date, $min, $max ) { if( $max &lt; $min ) { return false; } else { $mid = floor( $min + ( ( $max - $min ) / 2 ) ); $node = $this-&gt;nodes[ $mid ]; $start = $node-&gt;getStart(); $finish = $node-&gt;getFinish(); if( $date &lt; $start ) { return $this-&gt;binarySearch( $date, $min, $mid - 1 ); } else if( $date &gt; $finish ) { if( $finish == null ) { return $node; } else { return $this-&gt;binarySearch( $date, $mid + 1, $max ); } } else { return $node; } } } } </code></pre> <p>I am testing it with the following:</p> <pre><code>$nodes = array( new Node( new DateTime( '01:01:00' ), new DateTime( '01:05:00' ) ), new Node( new DateTime( '01:06:00' ), new DateTime( '01:10:00' ) ), new Node( new DateTime( '01:11:00' ), new DateTime( '01:15:00' ) ), new Node( new DateTime( '01:16:00' ), new DateTime( '01:20:00' ) ), new Node( new DateTime( '01:21:00' ), new DateTime( '01:25:00' ) ), new Node( new DateTime( '01:26:00' ), new DateTime( '01:30:00' ) ), new Node( new DateTime( '01:31:00' ), new DateTime( '01:35:00' ) ), new Node( new DateTime( '01:36:00' ), new DateTime( '01:40:00' ) ), new Node( new DateTime( '01:41:00' ) ) ); $list = new NodeList( $nodes ); $date = new DateTime( '01:00:00' ); for( $i = 0; $i &lt; 100; $i++, $date-&gt;modify( '+30 seconds' ) ) { $node = $list-&gt;find( $date ); echo 'find: ' . $date-&gt;format( 'H:i:s' ) . PHP_EOL; echo ( $node !== false ? (string) $node : 'false' ) . PHP_EOL . PHP_EOL; } </code></pre> <p>Do you see any inherent flaws and/or ways to improve this algorithm? Perhaps you even know of a more time efficient algorithm to accomplish the same?</p> <p>PS.: Don't worry about the internal integrity of <code>NodeList</code> and <code>Node</code> (checking for invalid nodes, invalid min and max datetimes, checking overlaps, etc.) — this is just a quick and dirty concept. I'm primarily interested in the search algorithm in <code>NodeList::find()</code> and consequently <code>NodeList::binarySearch()</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T14:52:36.203", "Id": "31879", "Score": "0", "body": "You will probably get better luck with algorithms on either SO or Programmers.SO. This site is more geared towards code review, not algorithm review. I wish I could help more, but I was absolutely terrible when I took algorithms. Best of luck" } ]
[ { "body": "<h3>Flatter code is less arrow-shaped</h3>\n\n<p>In cases like this:</p>\n\n<blockquote>\n<pre><code>if( $max &lt; $min )\n{\n return false;\n}\nelse\n{\n // more deeply nested conditions ...\n}\n</code></pre>\n</blockquote>\n\n<p>When the <code>if</code> branch ends with a <code>return</code> statement,\nyou can eliminate the <code>else</code> branch,\nmaking the code flatter and less arrow-shaped,\nwhich often makes it easier to read:</p>\n\n<pre><code>if( $max &lt; $min )\n{\n return false;\n}\n\n// more code ...\n</code></pre>\n\n<h3>Fishy comparison</h3>\n\n<p>Although this is apparently valid PHP, comparing a date against a <code>null</code> value using the <code>&gt;</code> operator seems like a dirty hack:</p>\n\n<blockquote>\n<pre><code>else if( $date &gt; $finish )\n{\n if( $finish == null )\n</code></pre>\n</blockquote>\n\n<p>I would reorganize the conditions in that piece of code:</p>\n\n<pre><code>if( $max &lt; $min )\n{\n return false;\n}\n\n$mid = floor( $min + ( ( $max - $min ) / 2 ) ); \n$node = $this-&gt;nodes[ $mid ];\n$start = $node-&gt;getStart();\n$finish = $node-&gt;getFinish();\n\nif( $date &lt; $start )\n{\n return $this-&gt;binarySearch( $date, $min, $mid - 1 );\n}\n\nif( $finish == null )\n{\n return $node;\n}\n\nif( $date &gt; $finish )\n{\n return $this-&gt;binarySearch( $date, $mid + 1, $max );\n}\n\nreturn $node;\n</code></pre>\n\n<h3>Minor optimization</h3>\n\n<p>The <code>find</code> method recalculates the size of <code>$this-&gt;nodes</code>,\neven though it cannot change after construction.\nIt would be better to calculate the size once,\nat construction time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-12T22:14:13.567", "Id": "152505", "ParentId": "19919", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T10:28:29.877", "Id": "19919", "Score": "3", "Tags": [ "php", "optimization", "algorithm", "binary-search" ], "Title": "Binary search algorithm for non-overlapping time spans and possible gaps" }
19919
<p>I have a file containing lines having this structure :</p> <blockquote> <pre><code>var marker25 = createMarker(point, '&lt;div id="infowindow" style="white-space: nowrap;"&gt;&lt;h3&gt;Katz\'s Deli&lt;/h3&gt;205 E. Houston Street, Manhattan, New York City,&lt;br /&gt;New York, USA&lt;br /&gt;&lt;br /&gt; &lt;a href="/When_Harry_Met_Sally/filming_locations"&gt;&lt;img style="margin-right: 5px; float: left; width: 100px; height: 150px" src="/images/posters/64-title.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;'); var marker26 = createMarker(point, '&lt;div id="infowindow" style="white-space: nowrap;"&gt;&lt;h3&gt;Rockerfeller Roof Gardens&lt;/h3&gt;5th Avenue between 49th &amp;amp; 50th Streets, Manhattan, New York City,&lt;br /&gt;New York, USA&lt;br /&gt;&lt;br /&gt; &lt;a href="/Spider-man/filming_locations"&gt;&lt;img style="margin-right: 5px; float: left; width: 100px; height: 150px" src="/images/posters/8-title.jpg" /&gt;&lt;/a&gt;&lt;/div&gt;'); </code></pre> </blockquote> <p>I want to quickly be able to have as a result line of this type:</p> <pre><code>Katz\'s Deli 205 E. Houston Street, Manhattan, New York City,New York, USA,When_Harry_Met_Sally Rockerfeller Roof Gardens,5th Avenue between 49th &amp;amp; 50th Streets,,New York, USA, Spider-man </code></pre> <p>To reiterate, I want to remove all HTML/JS strings to keep only addresses, country and so on.</p> <p>What I did so far is :</p> <pre><code>grep 'createMarker' New_York_Filming_Locations.php cut -d'&lt;' -f1,2,3,4,5,6,7,8 sed 's/&lt;br \/&gt;/,/g;s/&lt;h3&gt;/,/g;s/&lt;\/h3&gt;/,/g' cut -d',' -f3,4,5,7,8,9,11,12 sed 's/&lt;a href="\///g;s/\/filming_locations"&gt;//g' cut -d',' -f1,2,4,5,6,7 </code></pre> <p>It is done in a pipe, but for the clarity of the questions, I put each command on a separate line.</p> <p>Is this the best way to do it? It is a small file, so I do not care about performance.</p> <p>The <code>sed</code> syntax can be hard to understand. Do you guys know another way to do it using bash?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T20:37:24.703", "Id": "31859", "Score": "2", "body": "Bash, sed and regexps are notoriously not suited for parsing html. Use a specialized library in another language instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T20:44:12.573", "Id": "31860", "Score": "0", "body": "@gniourf_gniourf, I guess for parsing php it is even less suitable. But as I understand this is expecting to be fragile." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T23:11:25.017", "Id": "31864", "Score": "0", "body": "It is just to parse a really small file quickly, without having to use any library or anything. I totally know that it is not suitable, but it is possible. I am interested in the how, not the why :)" } ]
[ { "body": "<p>Consider removing tags with </p>\n\n<pre><code>sed 's/&lt;[^&gt;]*&gt;/ /g'\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T20:40:52.510", "Id": "19933", "ParentId": "19921", "Score": "2" } } ]
{ "AcceptedAnswerId": "19933", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T10:46:06.157", "Id": "19921", "Score": "1", "Tags": [ "parsing", "bash", "sed" ], "Title": "Parsing of a file using sed" }
19921
<p>I am working on a P2P streaming sim (which I think is correct), however I've discovered a huge bottleneck in my code. During the run of my sim, the function I've included below gets called about 25000 times and takes about 560 seconds from a total of about 580 seconds (I used pycallgraph).</p> <p>Can anyone identify any way I could speed the execution up, by optimizing the code (I think I won't be able to reduce the times it gets executed)? The basics needed to understand what the function does, is that the incoming messages consist of <code>[sender_sequence nr</code>, <code>sender_id</code>, <code>nr_of_known_nodes_to_sender</code> (or -1 if the sender departs the network), <code>time_to_live</code>], while the <code>mCache</code> entries these messages update, consist of the same data (except for the third field, which cannot be -1, instead if such a message is received the whole entry will be deleted), with the addition of a fifth field containing the update time.</p> <pre><code>def msg_io(self): # Node messages (not datastream) control # filter and sort by main key valid_sorted = sorted((el for el in self.incoming if el[3] != 0), key=ig(1)) self.incoming = [] # ensure identical keys have highest first element first valid_sorted.sort(key=ig(0), reverse=True) # group by second element grouped = groupby(valid_sorted, ig(1)) # take first element for each key internal = [next(item) for group, item in grouped] for j in internal: found = False if j[3] &gt; 0 : # We are only interested in non-expired messages for i in self.mCache[:]: if j[1] == i[1]: # If the current mCache entry corresponds to the current incoming message if j[2] == -1: # If the message refers to a node departure self.mCache.remove(i) # We remove the node from the mCache self.partnerCache = [partner for partner in self.partnerCache if not partner.node_id == j[1]] else: if j[0] &gt; i[0]: # If the message isn't a leftover (i.e. lower sequence number) i[:4] = j[:] # We update the relevant mCache entry i[4] = turns # We add the current time for the update found = True else: k = j[:] #k[3] -= 1 id_to_node[i[1]].incoming.append(k) # and we forward the message if not j[2] == -1 and not found and (len(self.mCache) &lt; maxNodeCache): # If we didn't have the node in the mCache temp = j[:] temp.append(turns) # We insert a timestamp... self.mCache.append(temp) # ...and add it to the mCache self.internal.remove(j) </code></pre>
[]
[ { "body": "<p><code>valid_sorted</code> is created using <code>sorted</code> function, and then it is sorted again. I don't see how the first sort is helping in any way. Maybe I'm wrong..</p>\n\n<hr>\n\n<p>You create the iterator <code>grouped</code> with the function <code>groupby</code>, but then you turn it into list and then <strong>iterate over it</strong> again. instead - you can do this:</p>\n\n<pre><code>grouped = groupby(valid_sorted, ig(1))\nfor group, item in grouped:\n j = next(item)\n ...\n</code></pre>\n\n<p>That way - you only iterate over it once. :)</p>\n\n<hr>\n\n<p>The inner loop iterating over <code>self.mCache[:]</code> - I don't see why you can't just iterate over <code>self.mCache</code> and that's it. If its members are lists - it will change weither you use <code>[:]</code> or not.</p>\n\n<p>When you use <code>[:]</code> - you create a copy of the list, and that's why It can be bad for memory and speed.</p>\n\n<hr>\n\n<p>The <code>remove</code> function can be quite slow, if you can find a better way to implement your algorithm without using this function - it can be faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T16:22:00.390", "Id": "31851", "Score": "0", "body": "First of all, many thank! I can see the point in removing the sorted (I'm already applying some of the changes), however the reasoning behind the grouped() modifications eludes me...aren't we doing the iteration I'm doing via list comprehension, using an explicit for loop? Isn't that more inefficient?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T16:32:08.247", "Id": "31852", "Score": "0", "body": "Another thing that bothers me, is that since I use remove() on the mCache list, I wonder if it is safe to not slice it when I iterate over it, as you suggest. I think I saw a suggestion somewhere, about a reverse iteration, which should be removal safe" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T13:33:42.617", "Id": "31876", "Score": "0", "body": "As @winston's commet says - it seems like groupby doesn't do what we thought it does, so I guess it doesn't matter anymore :)\nAbout the `remove` use - I think it is ok to use it like you do, and if you'll reverse it - it will have the same effect in my opinion." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T13:43:19.413", "Id": "19924", "ParentId": "19922", "Score": "3" } }, { "body": "<pre><code>def msg_io(self): # Node messages (not datastream) control\n\n # filter and sort by main key\n valid_sorted = sorted((el for el in self.incoming if el[3] != 0), key=ig(1))\n</code></pre>\n\n<p>Don't use abbreviation like <code>ig</code>. It just makes your code harder to read. Also, don't refer to the objects as magic numbers, like 1,2,3. It makes it really hard to figure out what the pieces refer to. </p>\n\n<pre><code> self.incoming = []\n</code></pre>\n\n<p>I'd <code>del self.incoming[:]</code>, to clear the list instead. You'll get some marginal speed benefits.</p>\n\n<pre><code> # ensure identical keys have highest first element first\n valid_sorted.sort(key=ig(0), reverse=True)\n</code></pre>\n\n<p>Don't do multiple sorts. Instead, use a key like <code>lambda el: (el[1],el[0])</code> to sort on both criteria at the same time.</p>\n\n<pre><code> # group by second element\n grouped = groupby(valid_sorted, ig(1))\n</code></pre>\n\n<p>Yeah, this isn't actually doing what you think it does. For this to work it assumed the data is sorted by the <code>[1]</code> item, but you've sorted it by the <code>[0]</code> item.</p>\n\n<p>If you don't actually need to process items in order sorted by key, I'd avoid the sorting altogether. Instead, just loop over <code>incoming</code> and split it into a <code>dict</code> then loop over the dict.</p>\n\n<pre><code> # take first element for each key\n internal = [next(item) for group, item in grouped]\n for j in internal: \n</code></pre>\n\n<p>I'd iterate over the generator and call next in side the for loop. Also avoid using single letter variable names. It makes it hard to figure out what everything is.</p>\n\n<pre><code> found = False\n</code></pre>\n\n<p>Whenever I seed code that assign logic flags, I know there is a better way to do it</p>\n\n<pre><code> if j[3] &gt; 0 : # We are only interested in non-expired messages\n for i in self.mCache[:]:\n</code></pre>\n\n<p>You copy the cache. You do need to do this in order to remove elements. But that's expensive.</p>\n\n<pre><code> if j[1] == i[1]: # If the current mCache entry corresponds to the current incoming message\n</code></pre>\n\n<p>It's expensive to have to loop over the whole cache to try and find a single element. Probably this should be a dictionary. That's avoid the copy and make deleting more efficient.</p>\n\n<pre><code> if j[2] == -1: # If the message refers to a node departure\n self.mCache.remove(i) # We remove the node from the mCache\n self.partnerCache = [partner for partner in self.partnerCache if not partner.node_id == j[1]] \n\n else: \n if j[0] &gt; i[0]: # If the message isn't a leftover (i.e. lower sequence number)\n i[:4] = j[:] # We update the relevant mCache entry\n i[4] = turns # We add the current time for the update\n found = True\n else:\n k = j[:]\n #k[3] -= 1\n</code></pre>\n\n<p>Don't leave dead code in your actual code. That's what source control is for.</p>\n\n<pre><code> id_to_node[i[1]].incoming.append(k) # and we forward the message \n</code></pre>\n\n<p>You are forwarding the message to all the nodes in the cache. That strikes me as rather strange. But perhaps it makes sense for a P2P sim.</p>\n\n<pre><code> if not j[2] == -1 and not found and (len(self.mCache) &lt; maxNodeCache): # If we didn't have the node in the mCache \n temp = j[:]\n temp.append(turns) # We insert a timestamp...\n self.mCache.append(temp) # ...and add it to the mCache\n self.internal.remove(j)\n</code></pre>\n\n<p>Is this supposed to be the <code>internal</code> local variable from earlier? Because its not. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T10:02:42.733", "Id": "31870", "Score": "0", "body": "Yup, you got me there! I was in the process of removing the class variable (self.internal) in favor of a local variable, but it seems I copied and pasted midway!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T04:36:14.170", "Id": "19936", "ParentId": "19922", "Score": "3" } }, { "body": "<p>The solution that I actually implemented, with quite a gain in speed, follows below. In addition, I removed the checks for the third item being zero (placed them in another part of the code), though I don't think the checks had much effect on the delay. The interesting part was the implementation of <code>mCache</code> and the incoming messages using dictionaries, thus getting rid of slow loops. Unfortunately I can think of no proper replacement for the message forwarding loop. As for the gain, on a small test run it clocked 53 seconds instead of 560.</p>\n\n<pre><code>def msg_io(self): # Node messages (not datastream) control\n\n messages = {}\n for incoming_msg in self.incoming:\n k = incoming_msg[1]\n if k not in messages:\n # First appearance of this second-position element\n messages[k] = incoming_msg\n elif messages[k][0] &lt; incoming_msg[0]:\n # We've seen this second-position element before, but this list has a higher first element than the last one we saw\n messages[k] = incoming_msg\n else:\n # We've already seen this second-position element in a list with an equal or higher first element\n pass\n self.incoming = []\n\n\n for j in messages: \n if j in self.mCache:\n if messages[j][2] == -1:\n del(self.mCache[j])\n for partner in self.partnerCache[:]:\n if partner.node_id == j:\n self.partnerCache.remove(partner)\n else: \n if messages[j][0] &gt; self.mCache[j][0]: # If the message isn't a leftover (i.e. lower sequence number)\n self.mCache[j][:4] = messages[j][:] # We update the relevant mCache entry\n self.mCache[j][4] = turns # We add the current time for the update\n\n elif (not messages[j][2] == -1) and (len(self.mCache) &lt; maxNodeCache): # If we didn't have the node in the mCache \n self.mCache[j] = messages[j][:4]\n self.mCache[j].append(turns)\n\n for destinations in self.mCache:\n if not destinations == j:\n id_to_node[destinations].incoming.append(messages[j])\n\n messages = {}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T17:28:13.227", "Id": "19998", "ParentId": "19922", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T11:07:55.517", "Id": "19922", "Score": "3", "Tags": [ "python", "optimization" ], "Title": "P2P streaming sim" }
19922
<p>I'm using this simple plugin to show a simple countdown in my pages, what I would like is to keep it more accurate, cause somentimes it seems it isn't accurate.</p> <p>This is the plugin:</p> <pre><code>/* countdown is a simple jquery plugin for countdowns Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. @source: http://github.com/rendro/countdown/ @autor: Robert Fleischmann @version: 1.0.0 */ (function() { (function($) { $.countdown = function(el, options) { var getDateData, _this = this; this.el = el; this.$el = $(el); this.$el.data("countdown", this); this.init = function() { _this.options = $.extend({}, $.countdown.defaultOptions, options); if (_this.options.refresh) { _this.interval = setInterval(function() { return _this.render(); }, _this.options.refresh); } _this.render(); return _this; }; getDateData = function(endDate) { var dateData, diff; endDate = Date.parse($.isPlainObject(_this.options.date) ? _this.options.date : new Date(_this.options.date)); diff = (endDate - Date.parse(new Date)) / 1000; if (diff &lt; 0) { diff = 0; if (_this.interval) { _this.stop(); } } dateData = { years: 0, days: 0, hours: 0, min: 0, sec: 0, millisec: 0 }; if (diff &gt;= (365.25 * 86400)) { dateData.years = Math.floor(diff / (365.25 * 86400)); diff -= dateData.years * 365.25 * 86400; } if (diff &gt;= 86400) { dateData.days = Math.floor(diff / 86400); diff -= dateData.days * 86400 ; } if (diff &gt;= 3600) { dateData.hours = Math.floor(diff / 3600); diff -= dateData.hours * 3600; } if (diff &gt;= 60) { dateData.min = Math.floor(diff / 60); diff -= dateData.min * 60; } dateData.sec = diff; return dateData; }; this.leadingZeros = function(num, length) { if (length == null) { length = 2; } num = String(num); while (num.length &lt; length) { num = "0" + num; } return num; }; this.update = function(newDate) { _this.options.date = newDate; return _this; }; this.render = function() { _this.options.render.apply(_this, [getDateData(_this.options.date)]); return _this; }; this.stop = function() { if (_this.interval) { clearInterval(_this.interval); } _this.interval = null; return _this; }; this.start = function(refresh) { if (refresh == null) { refresh = _this.options.refresh || $.countdown.defaultOptions.refresh; } if (_this.interval) { clearInterval(_this.interval); } _this.render(); _this.options.refresh = refresh; _this.interval = setInterval(function() { return _this.render(); }, _this.options.refresh); return _this; }; return this.init(); }; $.countdown.defaultOptions = { date: "June 7, 2087 15:03:25", refresh: 1000, render: function(date) { _hey_html = ""; if(date.years &gt; 0){ _hey_html += '&lt;span class="countdown-years" title="years left"&gt;' + date.years + 'year &lt;/span&gt;'; } return $(this.el).html(_hey_html+'&lt;span class="countdown-days" title="days left"&gt; ' + date.days + ' &lt;/span&gt;&lt;span class="countdown-hours" title="hours left"&gt; ' + (this.leadingZeros(date.hours)) + '&lt;small&gt; h &lt;/small&gt; &lt;/span&gt;&lt;span class="countdown-min" title="minutes left"&gt;' + (this.leadingZeros(date.min)) + '&lt;small&gt; m &lt;/small&gt; &lt;/span&gt;&lt;span class="countdown-sec" title="seconds left"&gt;' + (this.leadingZeros(date.sec)) + '&lt;small&gt; s &lt;/small&gt;&lt;/span&gt;'); } }; $.fn.countdown = function(options) { return $.each(this, function(i, el) { var $el; $el = $(el); if (!$el.data('countdown')) { return $el.data('countdown', new $.countdown(el, options)); } }); }; return void 0; })(jQuery); }).call(this); </code></pre> <p>I think there should be some kind of delay when parsing dates in this plugin, dates are PHP generated as Unixtimestamp then I do this:</p> <pre><code>$(function(){ $.each($('.countdown'), function() { var _element = '.countdown-'+$(this).attr("id"); var _id = $(this).attr("id"); if($(_element).length &gt; 0){ var _datetime = $(_element).attr('data-expiration').toLocaleString(); var d = new Date(_datetime).getTime(); var result = new Date(d); _datetime = d; init_countdown(_id,_element,_datetime); } }); }); </code></pre> <p>this is the html</p> <pre><code>&lt;div data-expiration="Jan 01, 2013 20:01:15" id="25" class="span12 countdown label-expiring countdown-25"&gt; </code></pre> <p>Sometimes it doesn't shows the real dates, it seems is in delay of about 20/30 minutes, and I can't understand why.</p> <p>Any help appriaciated, thanks!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-01T00:04:33.803", "Id": "32070", "Score": "0", "body": "Can you post values of the `data-expiration` attribute along with string representations of the corresponding dates that are created in JS for both inaccurate and accurate countdown values?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-01T00:52:50.200", "Id": "32071", "Score": "0", "body": "@tiffon i added the html element where to bind up the plugin, you can try with different **data-expiration** and you will check that sometimes it is not accurate or maybe never accurated at all, thanks!" } ]
[ { "body": "<p>I do not quite understand, why in your code had so many passages from date to date?<br /> if your \"tag attribute\" was already with a correct date format.</p>\n\n<p>I've done some adjustments in the source code, I've tested and I do not see any kind of delay in the source code or in the plugin.</p>\n\n<p>This is the source code and you can test here:</p>\n\n<ul>\n<li><a href=\"http://jsfiddle.net/8HgQ3/1/\" rel=\"nofollow\"><strong>simple mode</strong></a></li>\n<li><a href=\"http://jsfiddle.net/8HgQ3/\" rel=\"nofollow\"><strong>full mode</strong></a></li>\n<li><a href=\"http://jsfiddle.net/8HgQ3/2/\" rel=\"nofollow\"><strong>mixed mode</strong></a></li>\n</ul>\n\n<p><br /></p>\n\n<pre><code>function init_countdown(id,element,datetime,fullmode){\n var endDate = datetime;\n if(!fullmode){\n $(element).countdown({ date: endDate });\n }else{\n $(element).countdown({\n date: endDate,\n render: function(data) {\n var el = $(this.el);\n el.empty()\n .append(\"&lt;div&gt;\" + this.leadingZeros(data.years, 4) + \" &lt;span&gt;years&lt;/span&gt;&lt;/div&gt;\")\n .append(\"&lt;div&gt;\" + this.leadingZeros(data.days, 3) + \" &lt;span&gt;days&lt;/span&gt;&lt;/div&gt;\")\n .append(\"&lt;div&gt;\" + this.leadingZeros(data.hours, 2) + \" &lt;span&gt;hrs&lt;/span&gt;&lt;/div&gt;\")\n .append(\"&lt;div&gt;\" + this.leadingZeros(data.min, 2) + \" &lt;span&gt;min&lt;/span&gt;&lt;/div&gt;\")\n .append(\"&lt;div&gt;\" + this.leadingZeros(data.sec, 2) + \" &lt;span&gt;sec&lt;/span&gt;&lt;/div&gt;\");\n }\n });\n }\n }\n\n\n$(function(){\n var mode=1;\n $.each($('.countdown'), function() {\n var _element = '.countdown-'+$(this).attr(\"id\");\n var _id = $(this).attr(\"id\");\n if($(_element).length &gt; 0){\n var _datetime = $(_element).attr('data-expiration');\n init_countdown(_id,_element,_datetime,(mode^=1));\n }\n });\n});\n</code></pre>\n\n<p>HTML:</p>\n\n<pre><code> &lt;body&gt;\n &lt;div id=\"25\" class=\"span12 countdown label-expiring countdown-25\" data-expiration=\"Jan 01, 2014 20:01:15\"&gt;\n &lt;/div&gt;\n &lt;hr /&gt;\n &lt;div id=\"26\" class=\"span12 countdown label-expiring countdown-26\" data-expiration=\"Jan 01, 2015 20:01:15\"&gt;\n &lt;/div&gt;\n &lt;hr /&gt; \n &lt;div id=\"27\" class=\"span12 countdown label-expiring countdown-27\" data-expiration=\"Jan 01, 2016 20:01:15\"&gt;\n &lt;/div&gt;\n &lt;/body&gt;​\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T13:27:51.737", "Id": "32152", "Score": "0", "body": "great, i can't understand why render: option doesn't works then :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T16:27:15.397", "Id": "32159", "Score": "0", "body": "In the example that I have posted, if you see the \"init_countdown\" there is a parameter called \"fullmode\" this mode allows working with the render, [here](http://jsfiddle.net/8HgQ3/) you can see the example with the three timers in complete form, and in the other example may you see a [mixed mode](http://jsfiddle.net/8HgQ3/2/). I hope I have been helpful" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T07:27:58.883", "Id": "20115", "ParentId": "19923", "Score": "3" } } ]
{ "AcceptedAnswerId": "20115", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T12:08:40.630", "Id": "19923", "Score": "1", "Tags": [ "javascript", "jquery", "plugin", "datetime" ], "Title": "jQuery countdown - accuracy" }
19923
<p>Here I have 2 email validation regexps, which one is better and why?</p> <pre><code>new RegExp("^[a-zA-Z0-9_-]+@[a-zA-Z0-9-]{2,}[.][a-zA-Z]{2,}$", "i"); new RegExp("^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4})*$", ""); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-13T23:30:25.560", "Id": "482017", "Score": "1", "body": "Related [Email validation using JavaScript](https://codereview.stackexchange.com/q/65190/91556)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-14T00:32:02.820", "Id": "482022", "Score": "0", "body": "Assuming this is for associating an email to a person, even if the regexp was perfect, that tells you almost nothing about the validity of that person's email. There is only really one way to check a person's email, and that's to email them." } ]
[ { "body": "<p>Both are totally broken as they both fail to accept the <code>+</code> character in the local part and one of them requires more than one digit for the domain name. Single-digit domain names are perfectly fine in some TLDs (such as <code>.de</code>).</p>\n\n<p>If you really need more validation than a simple \"has the <code>*@*.*</code> format\" check, you need to read this answer on Stack Overflow: <a href=\"https://stackoverflow.com/a/201378/298479\">Using a regular expression to validate an email address</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T15:00:58.397", "Id": "19926", "ParentId": "19925", "Score": "6" } }, { "body": "<p>There probably is no 'good' regexp to validate an email id. The Internet Standard RFC has classified a 500-character long RegExp which according to them is the standard way to validate an email-id. Well, it does work, but it is so messy and almost impossible for most of us to understand.</p>\n\n<pre><code>(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])\n</code></pre>\n\n<p>If you have understood it, then, you need not read further. But if you haven't, go on.</p>\n\n<p><a href=\"http://www.regular-expressions.info/email.html\" rel=\"nofollow\">This page</a> gives a decent info on how to validate an email id using regexp.</p>\n\n<p>I use this one</p>\n\n<pre><code>RegExp(\"^[A-Z0-9._%+-]+@([A-Z0-9.-]+\\.){1,4}[A-Z]{2,4}$\",\"i\")\n</code></pre>\n\n<p>This works fine, atleast for me, but it fails to validate emails on .museum domain or any other domain longer than 4-characters.</p>\n\n<p>Coming to your patterns, both of them are almost same except the fact that the first one uses <code>i</code> modifier and it allows 2 or more than 2 characters as TLD.\nHope it helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T18:22:00.990", "Id": "31883", "Score": "0", "body": "The other problem with the RFCs is that they only care about syntactically valid email addresses. foobar@yahoo.con may be syntactically valid, but it's probably not what the user intended to type, even if the .con domain exists." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T12:39:53.640", "Id": "45389", "Score": "0", "body": "Your suggestion breaks on '@example.com and *@example.com both of which are entirely valid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-23T17:39:44.793", "Id": "45410", "Score": "0", "body": "IP addresses are valid server destinations, too." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T16:51:25.360", "Id": "19944", "ParentId": "19925", "Score": "3" } } ]
{ "AcceptedAnswerId": "19944", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T14:38:13.380", "Id": "19925", "Score": "-3", "Tags": [ "javascript", "regex", "validation" ], "Title": "Which email detection regex is better?" }
19925
<p>Basically, the code looks for certain emoticon characters (like <code>:)</code> or <code>:|</code>) and replace them with an emoji icon. It also does this for emoji keywords like (<code>:blush:</code> or <code>:smirk:</code>).</p> <p>A better explanation is probably on the <a href="https://github.com/hassankhan/emojify.js" rel="nofollow">GitHub repo</a>.</p> <p>What areas of the code should I concentrate on improving, and if possible, how to improve them?</p> <pre><code>(function( global ) { var emojify = (function() { // Get DOM as local variable for simplicity's sake var document = global.window.document; return { // This functions sets configuration options config: function(emoticons, people, nature, objects, places, symbols) { this.emoticons_enabled = typeof emoticons !== 'undefined' ? emoticons : true; this.people_enabled = typeof people !== 'undefined' ? people : true; this.nature_enabled = typeof nature !== 'undefined' ? nature : true; this.objects_enabled = typeof objects !== 'undefined' ? objects : true; this.places_enabled = typeof places !== 'undefined' ? places : true; this.symbols_enabled = typeof symbols !== 'undefined' ? symbols : true; }, // Helper function to find text within DOM findText: function(element, pattern, callback) { for (var childi = element.childNodes.length; childi--&gt;0;) { var child = element.childNodes[childi]; if (child.nodeType == 1) { // Get tag name and class attribute var tag = child.tagName.toLowerCase(), classname; if(child.hasAttribute('class')) classname = child.getAttribute('class').toLowerCase(); // Hacky at the minute, needs to be fixed if (classname) { if (tag !== 'script' &amp;&amp; tag !== 'style' &amp;&amp; tag !== 'textarea' &amp;&amp; classname !== 'no-emojify') this.findText(child, pattern, callback); } else { if (tag !== 'script' &amp;&amp; tag !== 'style' &amp;&amp; tag !== 'textarea') this.findText(child, pattern, callback); } } else if (child.nodeType == 3) { var matches = []; if (typeof pattern === 'string') { console.error('Accepts regex only'); } else { var match; while (match = pattern.exec(child.data)) matches.push(match); } for (var i = matches.length; i--&gt;0;) callback.call(window, child, matches[i]); } } }, // Main method run: function() { var emoticons = [ [/:-*\)/g, 'emojify blush'], [/:-*o/gi, 'emojify scream'], [/(:|;)-*]/g, 'emojify smirk'], [/(:|;)-*d/gi, 'emojify smiley'], [/xd/gi, 'emojify stuck_out_tongue_closed_eyes'], [/:-*p/gi, 'emojify stuck_out_tongue_winking_eye'], [/:-*(\[|@)/g, 'emojify rage'], [/:-*\(/g, 'emojify disappointed'], [/:'-*\(/g, 'emojify sob'], [/:-*\*/g, 'emojify kissing_heart'], [/;-*\)/g, 'emojify wink'], [/:-*\//g, 'emojify pensive'], [/:-*s/gi, 'emojify confounded'], [/:-*\|/g, 'emojify flushed'], [/:-*\$/g, 'emojify relaxed'], [/:-*x/gi, 'emojify mask'], [/&lt;3/g, 'emojify heart'], [/&lt;\/3/g, 'emojify broken_heart'] ], people = [ [/:bowtie:/g, 'emojify bowtie'], [/:smile:/g, 'emojify smile'], // Lots more regex keys ], nature = [ [/:sunny:/g, 'emojify sunny'], [/:umbrella:/g, 'emojify umbrella'], // Lots more regex keys ], objects = [ [/:bamboo:/g, 'emojify bamboo'], [/:gift_heart:/g, 'emojify gift_heart'], // Lots more regex keys ], places = [ [/:109:/g, 'emojify onezeronine'], [/:house:/g, 'emojify house'], // Lots more regex keys ], symbols = [ [/:one:/g, 'emojify one'], [/:two:/g, 'emojify two'], // Lots more regex keys ], r; // Create array of selected icon sets var selected_sets = []; if(this.people_enabled) selected_sets.push(people); if(this.nature_enabled) selected_sets.push(nature); if(this.objects_enabled) selected_sets.push(objects); if(this.places_enabled) selected_sets.push(places); if(this.symbols_enabled) selected_sets.push(symbols); if(this.emoticons_enabled) selected_sets.push(emoticons); // Iterate through selected icon sets for (var index = 0; index &lt; selected_sets.length; index++) { // Iterate through all regexes while (r = selected_sets[index].shift()) { // Find and replace matches with &lt;div&gt; tags this.findText(document.body, r[0], function(node, match) { var wrap = document.createElement('div'); wrap.setAttribute('class', r[1]); node.splitText(match.index); node.nextSibling.nodeValue = node.nextSibling.nodeValue.substr(match[0].length, node.nextSibling.nodeValue.length); wrap.appendChild(node.splitText(match.index)); node.parentNode.insertBefore(wrap, node.nextSibling); }); } } } }; })(); global.emojify = emojify; })( this ); </code></pre>
[]
[ { "body": "<p>here are few improvement area which i would suggest , </p>\n\n<ol>\n<li><p>Current code select all emot element of a document and apply the icon on that , it should be section based or say it should be dependent upon library user (just like jquery does).</p></li>\n<li><p>child.nodeType == 1 is not a good practice better use an enum/ switch for better comparison. </p></li>\n<li><p>better use jquery/underscore to make it usable. jquery extension are easy to write and maintain.</p></li>\n</ol>\n\n<p>section based means I can select dom elements like all div or all paragraph having emot class and then apply your function on that , just like this</p>\n\n<p>$(\".emot\").emotify()</p>\n\n<p>this will select all element having emot class and needs to emotify.</p>\n\n<p>Let me know if you have any more confusion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T13:53:25.780", "Id": "31877", "Score": "0", "body": "Could you elaborate on that? I don't understand what you mean by section-based in 1. Also, I am looking to make this into a jQuery extension soon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T21:55:10.620", "Id": "31937", "Score": "0", "body": "Oh right, I suppose that will be easier to do once I've made it into a jQuery extension then. What about 2? Should I make an enum of node types and switch between them? Also, do you have any good links for converting my module to a jQuery extension?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T03:59:42.033", "Id": "31946", "Score": "0", "body": "Point number 2 is not valid if you use plugin/extension for jQuery. http://docs.jquery.com/Plugins/Authoring , here is the jQuery plugin sample" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T07:30:51.330", "Id": "19937", "ParentId": "19927", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T16:29:58.307", "Id": "19927", "Score": "4", "Tags": [ "javascript", "regex" ], "Title": "Replacing emoticon characters with emoji icons" }
19927
<p>I am trying to solve the following via recursion: In a phone we have each digit mapped to a number.</p> <p>Example:</p> <pre class="lang-none prettyprint-override"><code>1 2(ABC) 3(DEF) 4(GHI) 5(JKL) 6(MNO) 7(PRS) 8(TUV) 9(XYZ) * 0 # </code></pre> <p>I need to print out all the possible sequences of a phone number (example: <code>637-8687</code>). </p> <p>I did the following that seems to solve it:</p> <pre class="lang-java prettyprint-override"><code>static Map&lt;String, String&gt; digits; static{ digits = new HashMap&lt;String, String&gt;(); digits.put("2", "ABC"); digits.put("3", "DEF"); digits.put("4", "GHI"); digits.put("5", "JKL"); digits.put("6", "MNO"); digits.put("7", "PRS"); digits.put("8", "TUV"); digits.put("9", "XYZ"); } public static void printSequences(String phoneNumber, Map&lt;String, String&gt; associations){ if(phoneNumber == null || phoneNumber.isEmpty()){ throw new IllegalArgumentException(); } if(associations == null || associations.isEmpty()){ throw new IllegalArgumentException(); } String[] letters = new String[phoneNumber.length()]; for(int i = 0; i &lt; phoneNumber.length(); i++){ String seq = associations.get(phoneNumber.charAt(i) + ""); if(seq == null)continue; letters[i] = seq; } printSequences(letters, 0, letters.length, ""); } private static void printSequences(String[] letters, int start, int end, String prefix) { if(start == end){ System.out.println(prefix); return; } String sequence = letters[start]; if(sequence == null) return; for(int i = 0; i &lt; sequence.length(); i++){ printSequences(letters, start + 1, end, prefix + sequence.charAt(i)); } } </code></pre> <p>The <code>String[] letters</code> has all the relevant digits (extracted from a <code>Map</code>). In this case it is <code>[MNO, DEF, PRS, TUV, MNO, TUV, PRS]</code> for phone <code>6378687</code>.</p> <p>This code seems to work but does <strong>not</strong> for <code>637-8687</code>. For <code>637-8687</code> it actually prints nothing at all!</p> <p>I am trying to practice recursion, so could you please help me out with this one? Also, is recursion actually the best approach on such a problem?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T10:52:11.140", "Id": "31874", "Score": "0", "body": "You forgot `Q` on `7` and `W` on `9`!" } ]
[ { "body": "<p>Here are some comments from my side:</p>\n\n<ol>\n<li><p>The <code>end</code> parameter is unnecessary. You can just test for <code>start &gt;= letters.length</code> instead. Also, you might want to rename start.</p></li>\n<li><p>It might make sense to wrap your algorithm in a callable method such as <code>private void printSequences(String[] letters)</code>, which just kicks off the recursion by calling <code>printSequences(letters, 0, \"\")</code>.</p></li>\n<li><p>As to your bug, it depends on how exactly you are calling the method above (what is start and end).</p></li>\n<li><p>Your test for <code>letters[start] == null</code> does not seems necessary if the <code>letters</code> array is well-behaved (i.e., does not contain <code>null</code>).</p></li>\n<li><p>Recursion is a decent way to solve this problem.</p></li>\n<li><p>Your bug comes from the fact that when you process \"-\" as a digit, you generate <code>null</code> in <code>letters</code>. When processing <code>letters</code>, you don't call your function recursively but just return. That way, nothing is ever printed, which explains the behavior you describe. The proper way to handle that case would be to call the method recursively without appending anything to the prefix (or to make sure there are no null entries in <code>letters</code>, which I believe is the better way, see point 7).</p></li>\n<li><p>I would use a <code>List&lt;String&gt;</code> for letters. That way you don't end up with <code>null</code> entries.</p></li>\n<li><p>Your <code>IllegalArgumentException</code> should describe the problem. For instance, it could say \"Got illegal phoneNumber\".</p></li>\n<li><p>Your <code>digits</code> map should map characters to strings, not strings to strings. That way you don't have to coerce the character into string with <code>phoneNumber.charAt(i) + \"\"</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T19:06:34.620", "Id": "31855", "Score": "0", "body": "Is recursion the best option for this problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T19:09:28.677", "Id": "31856", "Score": "0", "body": "Yes, recursion is IMO a decent way to solve this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T19:25:45.967", "Id": "31857", "Score": "0", "body": "Posted complete code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T19:58:42.520", "Id": "31858", "Score": "0", "body": "Updated my answer, found your bug." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T18:56:35.200", "Id": "19931", "ParentId": "19929", "Score": "3" } } ]
{ "AcceptedAnswerId": "19931", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T18:19:35.290", "Id": "19929", "Score": "1", "Tags": [ "java", "algorithm", "strings", "recursion" ], "Title": "Recursion to map phone number to strings" }
19929
<p>So I've been working on <a href="http://blog.tmorris.net/understanding-practical-api-design-static-typing-and-functional-programming/">Tony Morris' Tic-Tac-Toe challenge</a>. The rules are as follows:</p> <blockquote> <p>Write an API for playing tic-tac-toe. There should be no side-effects (or variables), at all, for real. The move function will take a game state, a <code>Position</code> and it will return a data type that you write yourself.</p> <p>The following functions (at least) must be supported:</p> <p><code>move</code> (as mentioned) </p> <p><code>whoseTurn</code> (returns which player’s turn it is)</p> <p><code>whoWon</code> (returns who won or if a draw) </p> <p><code>playerAt</code> (returns which player, if any, is at a given position) </p> <p>Importantly, the following must be true:</p> <p>It is a compile-time error to call move or <code>whoseTurn</code> on a game that has been completed It is a compile-time error to call <code>whoWon</code> on a game that has not been completed The <code>playerAt</code> function must be supported on both complete and in-play games </p> <p>Good luck and may the types be with you.</p> </blockquote> <p>This is what I've got so far:</p> <pre><code>object TicTacToe2 { type Board = Map[Position, Option[Move]] sealed trait Winner case object Draw extends Winner sealed trait Move extends Winner case object X extends Move case object O extends Move sealed trait Position case object TL extends Position case object TM extends Position case object TR extends Position case object ML extends Position case object MM extends Position case object MR extends Position case object BL extends Position case object BM extends Position case object BR extends Position case class InProgress(override val board: Board) extends GameState(board) case class Finished(override val board: Board) extends GameState(board) sealed abstract class GameState(val board: Board) { override def toString = this.board.mkString("\n") } private val winningPatterns: Set[Set[Position]] = Set(Set(TL,TM, TR), Set(ML, MM, MR), Set(BL, BM, BR), Set(TL, ML, BL), Set(TM, MM, BM), Set(TR, MR, BR), Set(TL, MM, BR), Set(TR, MM, BL)) def whoseTurn(gameState: InProgress): Option[Move] = { val xs = gameState.board.count{ case (k, v) =&gt; v == Some(X) } val os = gameState.board.count{ case (k, v) =&gt; v == Some(O) } if (xs &gt; os) Some(O) else if (xs &lt; os) Some(X) else None } private def checkPlayerHasWon(gameState: GameState): Option[Winner] = { def hasPlayerWon(player: Move) = { val playerPositions = gameState.board.filter { case (k, v) =&gt; v == Some(player) }.keys.toSet winningPatterns.exists(wp =&gt; wp.subsetOf(playerPositions)) } if (hasPlayerWon(X)) Some(X) else if (hasPlayerWon(O)) Some(O) else if(gameState.board.count{ case (k, v) =&gt; v == None } == 0) Some(Draw) else None } def move(gameState: InProgress, position: Position, player: Move): GameState = { val tempGame = InProgress { gameState.board.updated(position, Some(player)) } checkPlayerHasWon(tempGame) match { case None =&gt; InProgress { tempGame.board } case Some(winner) =&gt; Finished { gameState.board } } } def playerAt(gameState: GameState, position: Position): Option[Move] = gameState.board.get(position).get def whoWonOrDraw(finishedGame: Finished): Winner = checkPlayerHasWon(finishedGame).get } object TicTacToeApplication2 { import TicTacToe2._ def createGame = InProgress { List(TL, TM, TR, ML, MM, MR, BL, BM, BR).map((_, None)).toMap } } </code></pre> <p><strong>My biggest concern so far is:</strong> How do I play this game as a client without resorting to painful typechecking/casting patterns? My tests use this sort of approach:</p> <pre><code>new BlankBoardTest { val newGameState: InProgress = move(gameState, TR, O).asInstanceOf[InProgress] val newGameState2 = move(newGameState, BM, X) newGameState2 match { case game @ InProgress(_) =&gt; { assert(playerAt(game, TR) === Some(O)) assert(playerAt(game, BM) === Some(X)) } case _ =&gt; fail } } </code></pre> <p>See how I'm pattern matching on the type like that? Is there a way to avoid doing this and chain them together so a client can play them without having to EXPLICITLY typecheck on the <code>gameState</code>? Perhaps using a monad and for-comprehensions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-31T14:08:07.063", "Id": "32059", "Score": "0", "body": "here's the answers.\nhttps://github.com/tonymorris/course/tree/answers/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-31T14:14:30.323", "Id": "32060", "Score": "0", "body": "I'm not a Scala programmer, so I cannot comment on his Scala solution. But his Java API is worthless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-31T23:41:34.677", "Id": "32069", "Score": "0", "body": "I'm curious as to why you say it's worthless?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-01T10:05:37.157", "Id": "32078", "Score": "0", "body": "First of all, an API is about simplicity, orthogonality and understandability. \nTrying to write Haskell code in Java results in code just as ugly as Win32 C code in Haskell.\nActually reading C-style code written in C++ hurts my eyes and more importantly my brain\nand C++ style code written through abuse of C macros does the same. Your product does not have a smooth surface if your cutting against the grain." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-01T10:07:57.147", "Id": "32079", "Score": "0", "body": "This is a learning exercise to better exploit the powers of a type system, not something you would necessarily put into production. Did you read the blog post? I actually think his Java solution reads quite well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-01T10:30:23.517", "Id": "32080", "Score": "0", "body": "Using Continuation Passing Style instead of checked exceptions \nand recursion instead of loops in any non trivial Java will result in *stack overflow*s. \nIt is one reason you will have bug reports. \nDeep stacks also complicate memory management.\n\nWith good designed APIs if a user(that is a developer)\nmakes an error that results in a stack trace,\nif your runtime env provides them.\nIn normal APIs, where library code rarely calls client code\nit is easy to spot the error.\nIf the trace consists of a mix of client and library frames\nseveral hundred each throughly shuffled, ..." } ]
[ { "body": "<p>why do you extend Move also of Winner?</p>\n\n<p>what is the relation between every move object and winning state?</p>\n\n<pre><code> sealed trait Move extends Winner\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-01T07:41:59.187", "Id": "32074", "Score": "0", "body": "Good question. It's purely for code reuse. I think their IS a relation, though it's not done any favors by the naming." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-01T07:34:32.180", "Id": "20074", "ParentId": "19940", "Score": "2" } }, { "body": "<p>This is not an answer to the bounty question.</p>\n\n<pre><code> def whoseTurn(gameState: InProgress): Option[Move] = {\n val xs = gameState.board.count{ case (k, v) =&gt; v == Some(X) }\n val os = gameState.board.count{ case (k, v) =&gt; v == Some(O) }\n if (xs &gt; os) Some(O) else if (xs &lt; os) Some(X) else None\n }\n</code></pre>\n\n<p>For an in-progress game whose turn it is is always certain. this method should not return an optional type. \nthere is a bug in the last line. It's the first player's (<strong>X</strong> I think) turn if no of <strong>X</strong> s and <strong>O</strong> s on the board are equal.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-01T11:46:53.963", "Id": "20076", "ParentId": "19940", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T12:34:48.517", "Id": "19940", "Score": "5", "Tags": [ "object-oriented", "functional-programming", "scala" ], "Title": "Typesafe Tic-Tac-Toe API" }
19940
<p>Here is a link to my project, more details regarding the Diffie Hellman Key Exchange using MODP cyclic grous are available here, no ECP currently implemented</p> <p><a href="https://en.wikipedia.org/wiki/Diffie_hellman" rel="nofollow">https://en.wikipedia.org/wiki/Diffie_hellman</a></p> <p>I would like to know if I my code could be improved or if the BCMath implementation can pe significantly improved, because :</p> <p>Using groups defined in available RFCs</p> <ul> <li>GMP code is very fast <ul> <li>Group 2 : 0.03 ~ 0.05 seconds</li> </ul></li> <li>BCMath implementation is slow <ul> <li>Group 2 : 10 ~ 15 seconds</li> </ul></li> </ul> <p><a href="https://github.com/cristib89/diffie-hellman" rel="nofollow">https://github.com/cristib89/diffie-hellman</a></p> <p>Calculation time grows exponentially as the size of the group increases</p> <p><strong>Later edit : source code below</strong></p> <p><em>Usage example</em></p> <pre><code> &lt;?php require "DiffieHellmanBC.inc.php"; require "DiffieHellmanGMP.inc.php"; require "MathUtils.inc.php"; set_time_limit(0); $start = microtime(true); $d1 = new DiffieHellmanGMP(); $d1-&gt;usePredefinedGroup("group2"); $d2 = new DiffieHellmanGMP(); $d2-&gt;usePredefinedGroup("group2"); $aux = $d1-&gt;sendLocalPublicKey(); $d2-&gt;receiveRemotePublicKey($aux); $aux = $d2-&gt;sendLocalPublicKey(); $d1-&gt;receiveRemotePublicKey($aux); $a=$d1-&gt;calculateSharedSecretKey(); $b=$d2-&gt;calculateSharedSecretKey(); echo "&lt;hr/&gt;GMP implementation &lt;hr/&gt;"; iF($a==$b) echo "OK"; else echo "NOK"; echo "&lt;br/&gt;"; print_r($d1-&gt;diagnose()); echo "&lt;br/&gt;"; print_r($d2-&gt;diagnose()); echo "&lt;br/&gt;"; echo hash("SHA1",$a); echo "&lt;br/&gt;"; echo hash("SHA256",$a); echo "&lt;br/&gt;"; echo hash("SHA512",$a); echo "&lt;br/&gt;"; $end = microtime(true); echo ($end-$start)." seconds"; $start = microtime(true); $d1 = new DiffieHellmanBC(); $d1-&gt;usePredefinedGroup("group2"); $d2 = new DiffieHellmanBC(); $d2-&gt;usePredefinedGroup("group2"); $aux = $d1-&gt;sendLocalPublicKey(); $d2-&gt;receiveRemotePublicKey($aux); $aux = $d2-&gt;sendLocalPublicKey(); $d1-&gt;receiveRemotePublicKey($aux); $a=$d1-&gt;calculateSharedSecretKey(); $b=$d2-&gt;calculateSharedSecretKey(); echo "&lt;hr/&gt;BCMath implementation &lt;hr/&gt;"; iF($a==$b) echo "OK"; else echo "NOK"; echo "&lt;br/&gt;"; print_r($d1-&gt;diagnose()); echo "&lt;br/&gt;"; print_r($d2-&gt;diagnose()); echo "&lt;br/&gt;"; echo hash("SHA1",$a); echo "&lt;br/&gt;"; echo hash("SHA256",$a); echo "&lt;br/&gt;"; echo hash("SHA512",$a); echo "&lt;br/&gt;"; $end = microtime(true); echo ($end-$start)."seconds"; ?&gt; </code></pre> <p><em>BCMath implementation</em></p> <pre><code>&lt;?php class DiffieHellmanBC{ private $group = array("prime"=&gt;"", "generator"=&gt;""); private $localPrivateKey, $localPublicKey, $remotePublicKey; private $sharedSecretKey; private $mathutils; /* * predefined groups */ private $groups = array( "testGroup"=&gt;array("prime"=&gt;"17","generator"=&gt;"5"), "group1"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A3620FFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group2"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group5"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group14"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group15"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group16"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199FFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group17"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DCC4024FFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group18"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD922222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC50846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E7160C980DD98EDD3DFFFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group22"=&gt;array("prime"=&gt;"B10B8F96A080E01DDE92DE5EAE5D54EC52C99FBCFB06A3C69A6A9DCA52D23B616073E28675A23D189838EF1E2EE652C013ECB4AEA906112324975C3CD49B83BFACCBDD7D90C4BD7098488E9C219A73724EFFD6FAE5644738FAA31A4FF55BCCC0A151AF5F0DC8B4BD45BF37DF365C1A65E68CFDA76D4DA708DF1FB2BC2E4A4371","generator"=&gt;"A4D1CBD5C3FD34126765A442EFB99905F8104DD258AC507FD6406CFF14266D31266FEA1E5C41564B777E690F5504F213160217B4B01B886A5E91547F9E2749F4D7FBD7D3B9A92EE1909D0D2263F80A76A6A24C087A091F531DBF0A0169B6A28AD662A4D18E73AFA32D779D5918D08BC8858F4DCEF97C2A24855E6EEB22B3B2E5"), "group23"=&gt;array("prime"=&gt;"AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC2129037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708B3BF8A317091883681286130BC8985DB1602E714415D9330278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486DCDF93ACC44328387315D75E198C641A480CD86A1B9E587E8BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71CF9DE5384E71B81C0AC4DFFE0C10E64F","generator"=&gt;"AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFAAB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7C17669101999024AF4D027275AC1348BB8A762D0521BC98AE247150422EA1ED409939D54DA7460CDB5F6C6B250717CBEF180EB34118E98D119529A45D6F834566E3025E316A330EFBB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC017981BC087F2A7065B384B890D3191F2BFA"), "group24"=&gt;array("prime"=&gt;"87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597","generator"=&gt;"3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659") ); public function __construct(){ $this-&gt;mathutils = new MathUtils(); } public function getGroup(){ /* * returns current public group */ return $this-&gt;group; } public function setGroup($group){ /* * sets public group */ $this-&gt;group["prime"] = $group["prime"]; $this-&gt;group["generator"] = $group["generator"]; } public function getPrime(){ return $this-&gt;group["prime"]; } public function getGenerator(){ return $this-&gt;group["generator"]; } public function setPrime($num){ $this-&gt;group["prime"] = $num; } public function setGenerator($num){ $this-&gt;group["generator"] = $num; } public function getPredefinedGroups(){ /* * returns predefined groups */ return $this-&gt;groups; } public function usePredefinedGroup($group){ /* * use a predefined group */ $this-&gt;setGroup($this-&gt;groups[$group]); } public function getLocalPrivateKey(){ return $this-&gt;localPrivateKey; } public function getLocalPublicKey(){ return $this-&gt;localPublicKey; } public function getRemotePublicKey(){ return $this-&gt;remotePublicKey; } public function setLocalPrivateKey($num){ $this-&gt;localPrivateKey = $num; } public function setLocalPublicKey($num){ $this-&gt;localPublicKey = $num; } public function setRemotePublicKey($num){ $this-&gt;remotePublicKey = $num; } public function sendLocalPublicKey(){ /* * stores localPrivateKey and returns localPublicKey */ $prime = $this-&gt;mathutils-&gt;bchexdec($this-&gt;getPrime()); $generator = $this-&gt;mathutils-&gt;bchexdec($this-&gt;getGenerator()); $this-&gt;localPrivateKey = $this-&gt;mathutils-&gt;bcrandom("1",$prime); $this-&gt;localPublicKey = bcpowmod($generator,$this-&gt;localPrivateKey, $prime); return $this-&gt;localPublicKey; } public function receiveRemotePublicKey($remotePublicKey){ /* * gets remotePublicKey, used for calculation of sharedSecretKey */ $this-&gt;remotePublicKey = $remotePublicKey; } public function calculateSharedSecretKey(){ /* * calculates sharedSecretKey */ $prime = $this-&gt;mathutils-&gt;bchexdec($this-&gt;getPrime()); $this-&gt;sharedSecretKey = bcpowmod($this-&gt;remotePublicKey,$this-&gt;localPrivateKey,$prime); return $this-&gt;sharedSecretKey; } public function discardCryptoData(){ /* * deletes data from memory */ $this-&gt;localPrivateKey = ""; $this-&gt;localPublicKey = ""; $this-&gt;remotePublicKey = ""; $this-&gt;sharedSecretKey = ""; } public function diagnose(){ return array($this-&gt;localPrivateKey,$this-&gt;localPublicKey,$this-&gt;remotePublicKey,$this-&gt;sharedSecretKey); } } ?&gt; </code></pre> <p><em>GMP implementation</em></p> <pre><code>&lt;?php class DiffieHellmanGMP{ private $group = array("prime"=&gt;"", "generator"=&gt;""); private $localPrivateKey, $localPublicKey, $remotePublicKey; private $sharedSecretKey; private $mathutils; /* * predefined groups */ private $groups = array( "testGroup"=&gt;array("prime"=&gt;"17","generator"=&gt;"5"), "group1"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A3620FFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group2"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group5"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group14"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group15"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group16"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199FFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group17"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DCC4024FFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group18"=&gt;array("prime"=&gt;"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD922222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC50846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E7160C980DD98EDD3DFFFFFFFFFFFFFFFFF","generator"=&gt;"2"), "group22"=&gt;array("prime"=&gt;"B10B8F96A080E01DDE92DE5EAE5D54EC52C99FBCFB06A3C69A6A9DCA52D23B616073E28675A23D189838EF1E2EE652C013ECB4AEA906112324975C3CD49B83BFACCBDD7D90C4BD7098488E9C219A73724EFFD6FAE5644738FAA31A4FF55BCCC0A151AF5F0DC8B4BD45BF37DF365C1A65E68CFDA76D4DA708DF1FB2BC2E4A4371","generator"=&gt;"A4D1CBD5C3FD34126765A442EFB99905F8104DD258AC507FD6406CFF14266D31266FEA1E5C41564B777E690F5504F213160217B4B01B886A5E91547F9E2749F4D7FBD7D3B9A92EE1909D0D2263F80A76A6A24C087A091F531DBF0A0169B6A28AD662A4D18E73AFA32D779D5918D08BC8858F4DCEF97C2A24855E6EEB22B3B2E5"), "group23"=&gt;array("prime"=&gt;"AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC2129037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708B3BF8A317091883681286130BC8985DB1602E714415D9330278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486DCDF93ACC44328387315D75E198C641A480CD86A1B9E587E8BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71CF9DE5384E71B81C0AC4DFFE0C10E64F","generator"=&gt;"AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFAAB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7C17669101999024AF4D027275AC1348BB8A762D0521BC98AE247150422EA1ED409939D54DA7460CDB5F6C6B250717CBEF180EB34118E98D119529A45D6F834566E3025E316A330EFBB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC017981BC087F2A7065B384B890D3191F2BFA"), "group24"=&gt;array("prime"=&gt;"87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597","generator"=&gt;"3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659") ); public function __construct(){ $this-&gt;mathutils = new MathUtils(); } public function getGroup(){ /* * returns current public group */ return $this-&gt;group; } public function setGroup($group){ /* * sets public group */ $this-&gt;group["prime"] = $group["prime"]; $this-&gt;group["generator"] = $group["generator"]; } public function getPrime(){ return $this-&gt;group["prime"]; } public function getGenerator(){ return $this-&gt;group["generator"]; } public function setPrime($num){ $this-&gt;group["prime"] = $num; } public function setGenerator($num){ $this-&gt;group["generator"] = $num; } public function getPredefinedGroups(){ /* * returns predefined groups */ return $this-&gt;groups; } public function usePredefinedGroup($group){ /* * use a predefined group */ $this-&gt;setGroup($this-&gt;groups[$group]); } public function getLocalPrivateKey(){ return $this-&gt;localPrivateKey; } public function getLocalPublicKey(){ return $this-&gt;localPublicKey; } public function getRemotePublicKey(){ return $this-&gt;remotePublicKey; } public function setLocalPrivateKey($num){ $this-&gt;localPrivateKey = $num; } public function setLocalPublicKey($num){ $this-&gt;localPublicKey = $num; } public function setRemotePublicKey($num){ $this-&gt;remotePublicKey = $num; } public function sendLocalPublicKey(){ /* * stores localPrivateKey and returns localPublicKey */ $prime = $this-&gt;mathutils-&gt;gmphexdec($this-&gt;getPrime()); $generator = $this-&gt;mathutils-&gt;gmphexdec($this-&gt;getGenerator()); $this-&gt;localPrivateKey = $this-&gt;mathutils-&gt;gmprandom("1",$prime); $this-&gt;localPublicKey = gmp_strval(gmp_powm($generator,$this-&gt;localPrivateKey, $prime)); return $this-&gt;localPublicKey; } public function receiveRemotePublicKey($remotePublicKey){ /* * gets remotePublicKey, used for calculation of sharedSecretKey */ $this-&gt;remotePublicKey = gmp_strval($remotePublicKey); } public function calculateSharedSecretKey(){ /* * calculates sharedSecretKey */ $prime = $this-&gt;mathutils-&gt;gmphexdec($this-&gt;getPrime()); $this-&gt;sharedSecretKey = gmp_strval(gmp_powm($this-&gt;remotePublicKey,$this-&gt;localPrivateKey,$prime)); return $this-&gt;sharedSecretKey; } public function diagnose(){ return array($this-&gt;localPrivateKey,$this-&gt;localPublicKey,$this-&gt;remotePublicKey,$this-&gt;sharedSecretKey); } public function discardCryptoData(){ /* * deletes data from memory */ $this-&gt;localPrivateKey = ""; $this-&gt;localPublicKey = ""; $this-&gt;remotePublicKey = ""; $this-&gt;sharedSecretKey = ""; } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T17:11:35.280", "Id": "31881", "Score": "1", "body": "You should add your code directly in your post, per [FAQ](http://codereview.stackexchange.com/faq#questions). Otherwise you risk having your question being closed as off topic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:17:50.823", "Id": "34161", "Score": "1", "body": "I'd worry abound timing side-channel attacks. Cryptographic code needs constant time operations, general purpose math library are typically variable time. Such leaks can allow an attacker to figure out your private key. This has happened to older OpenSSL versions." } ]
[ { "body": "<p>Just a heads up: You don't have to include the \".php\" extension on \".inc\" files. They are typically considered separate extensions. The \".inc\" extension usually indicates a file to be included, such as a template file, not a class file. However, this is probably more of a point of preference rather than standard. It is merely something I have observed and adopted in my own work.</p>\n\n<p>You should avoid manipulating the time limit. If your application requires you to modify that value, then you should know something is wrong. The reason this should be avoided is because you cause your server to hang while it waits for the application to finish and this can easily mask issues such as infinite loops. Typically the thing to do here is to limit how much work you are doing. Another option is to attempt to refactor your code to speed up the processing. In the end it just depends on your circumstances.</p>\n\n<p>There is an essential OOP principle you are neglecting in your usage example: \"Don't Repeat Yourself\" (DRY). As the name implies, your code should not repeat itself. From everything I can gather you are creating two very similar instances of the <code>DiffieHellmanGMP</code> class. There is an adage that says, \"You can either do something once, or many times; There is no such thing as doing something only twice.\" I probably slaughtered that quote, but you get the idea. The adage and principle go hand in hand. So in this instance, the ideal thing to do is to create a loop to instantiate each instance. And since we should know variable-variables are bad, we will instead use an array to store our instances.</p>\n\n<pre><code>$instances = array();\n$numInstances = 2;\nfor( $i = 0; $i &lt; $numInstances; $i++ ) {\n $instance = new DiffieHellmanGMP();\n $instance-&gt;usePredefinedGroup( 'group2' );\n\n $aux = $instance-&gt;sendLocalPublicKey();\n $instance-&gt;receiveRemotePublicKey( $aux );\n\n $secretKey = $instance-&gt;calculateSharedSecretKey();\n\n //finish instantiating...\n\n $savedInstance = compact( 'instance', 'secretKey', etc... );\n $instances[ $i ] = $savedInstance;\n}\n</code></pre>\n\n<p>Another point of contention here is the use of HTML in your PHP. I would avoid this if at all possible, especially if that HTML is static. I don't know of any IDEs that support proper tag matching/highlighting with embedded HTML, and its always better, in my opinion, to have the logic separated from the display as they are separate concerns. So an alternative here is to escape temporarily from PHP to output your HTML, or, more ideally, you can separate it entirely by creating a template. For example:</p>\n\n<pre><code>$encryption = array(\n 'SHA1',\n 'SHA256',\n 'SHA512'\n);\nforeach( $encryption as $crypt ) {\n echo hash( $crypt, $a );\n?&gt;\n&lt;br /&gt;\n&lt;?php\n}\n\n//or in another file you include in its place\n\n&lt;?php foreach( $encryption as $crypt ) : ?&gt;\n\n&lt;?php echo hash( $crypt, $a ); ?&gt;\n&lt;br /&gt;\n\n&lt;?php endforeach; ?&gt;\n</code></pre>\n\n<p>That's kind of a bad example because of how little HTML is being output, but it gives you an idea. Another possibility here, though one I wouldn't be too fond of, is to use <code>nl2br()</code>, to create those newlines for you. I only mention it because of how frequently you seem to add those breaks.</p>\n\n<p>Please, always use braces. For one thing, they reduce the likelihood of making a mistake, and for another they can be confusing, especially to those who have never seen the syntax before and don't understand the pitfalls.</p>\n\n<pre><code>if( $a == $b ) {\n echo \"OK\";\n} else {\n echo \"NOK\";\n}\n</code></pre>\n\n<p>Another option would be to use a ternary statement if you are insistent upon single line statements. Don't go overboard with these, ternary statements are meant to be an aid, not a hindrance, and they should never detract from legibility. Not everyone likes these, but I do find them useful for small and simple tasks such as this.</p>\n\n<pre><code>echo $a == $b ? 'OK' : 'NOK';\n</code></pre>\n\n<p>It appears that you are attempting to use doccomments here, otherwise you should just use the double forward slash to initiate a normal, single line, comment. However, I'm not suggesting you use normal comments, just trying to explain the difference. If your code is self-documenting you should only ever need doccomments. Doccomments have two asterisks to begin them and they should always be before the element they are to document. I notice that some of your comments are internal to the methods. These will not work as doccomments, even if they did have the correct syntax.</p>\n\n<pre><code>/** short desc.\n *\n * long\n * description\n *\n * @param\n * @return\n * etc...\n */\n</code></pre>\n\n<p>Alright, I'm not going to even begin to hazard a guess as to what those long alpha-numeric strings are supposed to be, but you might think about saving those values to a database of some sort. You can use anything: A simple text file, JSON, MySQL, and XML to name but a few. But they only add clutter here and that should be avoided. Store them somewhere, then retrieve them when needed.</p>\n\n<p>You should consider injecting your dependencies to avoid tight coupling. This is one of the major benefits of an OOP design. Doing this will make any future expansion easier. For instance, in the below snippet I require that the injected value be of the <code>MathUtils</code> family. That doesn't mean it has to be the <code>MathUtils</code> class, only that it be related to it. This means that should the <code>MathUtils</code> class ever be expanded, then that class can then be injected instead and should work seamlessly with this one.</p>\n\n<pre><code>public function __construct( MathUtils $mathutils ) {\n $this-&gt;mathutils = $mathutils;\n}\n</code></pre>\n\n<p>Always verify that your public methods accept only those values that you expect. In your <code>setGroup()</code> method you aren't doing this. That means that the <code>$group</code> I could inject into this could be a string, or integer, or some other class even. Using type hinting will prevent any other type of value from being injected other than those that you want.</p>\n\n<pre><code>public function setGroup( Array $group ) {\n</code></pre>\n\n<p>Another thing you will want to verify is that the array being passed to <code>setGroup()</code> has the right elements. Your code is just assuming that it will have the <code>prime</code> and <code>generator</code> elements and never checks for them. This can cause issues, especially with a public method. Public methods are almost like user information from a form. You should always verify it.</p>\n\n<p><strong>SNIPPED TO EDITED SECTION</strong></p>\n\n<p>Now, I don't know what is causing your speed issues. The code you provided doesn't seem to be so inefficient, except for the DRY references I made. But then again, I think your issue might not be in either of these classes, but rather in one of the other ones; Such as the <code>MathUtils</code> class. To get a better idea of where the culprit might be, you should probably profile every action to determine where the most time is being eaten up. Apply the advice in this answer to whatever you find. More than likely its a DRY issue, or its just that you are attempting to do too much.</p>\n\n<p>The only other advice I have that might interest you is a suggestion to take a look into using the magic getter and setter methods. Most of your <code>get*()</code> and <code>set*()</code> methods appear to use the <code>$group</code> property array. If you set up your getter and setter methods to automatically use this array, then you can avoid having to write each getter and setter manually. For instance, here's how the getter might look:</p>\n\n<pre><code>public function __get( $key ) {\n return isset( $this-&gt;group[ $key ] ) ? $this-&gt;group[ $key ] : FALSE;\n}\n</code></pre>\n\n<p>Now, you're not going to be able to use that for everything obviously, but that should definitely alleviate the worst of it. Then again, this is something some people don't like to use, so it is entirely up to you.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>You should consider combining your DiffieHellmanBC and DiffieHellmanGMP classes into a base class to extend from. And if you make the base class an abstract class, you can add abstract methods for those methods of the same name that differ between the versions to create a common interface. This will allow for future expansion and reduces the amount of repeated code, following DRY. The advantage of extending the class means that you don't have to repeat all of those things they have in common, instead they will be inherited by any class that extends it. The only thing you will really have to change is all of those private properties. Protected is almost identical to private except that a protected element is shared with any child classes whereas private remains invisible.</p>\n\n<pre><code>abstract class DiffieHellman {\n protected $group = array(\"prime\"=&gt;\"\", \"generator\"=&gt;\"\");\n protected $localPrivateKey, $localPublicKey, $remotePublicKey;\n protected $sharedSecretKey;\n protected $mathutils;\n\n protected $groups = array(\n //etc...\n ); \n\n public function __construct( MathUtils $mathutils ) {\n $this-&gt;mathutils = $mathutils;\n }\n\n //etc...\n\n /**\n * Another advantage to base classes, especially abstract ones,\n * is the ability to get the doccomments out of the way.\n * This is essentially the application's API.\n */\n abstract public function sendLocalPublicKey();\n}\n\nclass DiffieHellmanBC extends DiffieHellman {\n //no need to redefine the properties or constructor.\n //just add anything specific to this class for example:\n\n public function sendLocalPublicKey(){\n $prime = $this-&gt;mathutils-&gt;bchexdec($this-&gt;getPrime());\n $generator = $this-&gt;mathutils-&gt;bchexdec($this-&gt;getGenerator());\n $this-&gt;localPrivateKey = $this-&gt;mathutils-&gt;bcrandom(\"1\",$prime);\n $this-&gt;localPublicKey = bcpowmod($generator,$this-&gt;localPrivateKey, $prime);\n return $this-&gt;localPublicKey;\n }\n}\n\nclass DiffieHellmanGMP extends DiffieHellman {\n //no need to redefine the properties or constructor.\n //just add anything specific to this class for example:\n\n public function sendLocalPublicKey(){\n $prime = $this-&gt;mathutils-&gt;gmphexdec($this-&gt;getPrime());\n $generator = $this-&gt;mathutils-&gt;gmphexdec($this-&gt;getGenerator());\n $this-&gt;localPrivateKey = $this-&gt;mathutils-&gt;gmprandom(\"1\",$prime);\n $this-&gt;localPublicKey = gmp_strval(gmp_powm($generator,$this-&gt;localPrivateKey, $prime));\n return $this-&gt;localPublicKey;\n }\n}\n</code></pre>\n\n<p>I still say your problem is not here, but is in the <code>MathUtils</code> class. If you want to know what is causing all the issues, I suggest you profile your <code>MathUtils</code> methods. After you track down the offending methods you can post just those to see if anyone has any other suggestions. Though I suggest if you do that you do so in a new question to preserve this one. However, if, as you say, the BC math version has been proven less efficient, then there isn't much to be done except refactor for efficiency. Why not just use the GMP version?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T19:09:06.093", "Id": "31886", "Score": "0", "body": "thank you for your feedback , here's the interesting bit, those long alphanumeric strings are actually very large prime numbers represented as hex values, the reason I put set_timelimit(0) was because BCMath is very very slow compared to GMP, I want to know if the BCMath implementation can be improved ... there are many question on StackOverflow saying that BCMath isn't as efficient as GMP for large mathematical calculations" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T19:12:50.900", "Id": "31887", "Score": "0", "body": "regarding the speed issues, i once tested each action and/or method with microtime() on my usage scenario and bcmath operations took the longest ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T20:04:54.900", "Id": "31893", "Score": "0", "body": "Oh, you know what... When I copied this over to my text editor to take a look at this I didn't notice that part of it got cut off. The GMP implementation that I saw only had the constructor, so I'll take another look at it in a few and get back to you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T21:51:35.713", "Id": "31898", "Score": "0", "body": "@cristi_b: Alright, post has been updated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T05:37:26.177", "Id": "31912", "Score": "0", "body": "i will rework my code then, your info is useful" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-27T11:31:16.033", "Id": "148814", "Score": "0", "body": "I am not sure how your answer is addressing OP's concern about timing issues? and By the way there are always two of `DiffieHellmanGMP` and not more, not less and normally each of them are running in separate process. That is why OP does not have them in an array. Same rule applies to `DiffieHellmanBC`" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T18:58:07.697", "Id": "19949", "ParentId": "19945", "Score": "3" } } ]
{ "AcceptedAnswerId": "19949", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T16:55:02.870", "Id": "19945", "Score": "2", "Tags": [ "php", "cryptography" ], "Title": "Review my Diffie Hellman class" }
19945
<p><em>Service Class</em></p> <pre><code># services/search.rb class Search include Rails.application.routes.url_helpers include ActionView::Helpers::TagHelper def initialize(term, app_ids) @term = term @app_ids = app_ids end def results term = @term app_ids = @app_ids multi_search = Tire.multi_search do no_app_indices = [Event, PastEvent, Review].map {|c| c.tire.index_name} search :without_app, indices: no_app_indices do query { string term } end app_indices = [Question, Answer, Link, ServiceProvider].map {|c| c.tire.index_name} search :with_app, indices: indices do query do filtered do query { string term } filter :terms, app_id: app_ids end end end end multi_search.results[:with_app].to_a + multi_search.results[:without_app].to_a end def autocomplete results.map do |result| title, caption, route = set_item_based_on_type(result) {title: strip_tags(title), label: set_label(strip_tags(title), caption), value: route} end end def strip_tags(title) title.gsub(%r{&lt;/?[^&gt;]+?&gt;}, '').strip end </code></pre> <p><em>Specs</em></p> <pre><code>describe Search do before(:all) do Question.index.delete Question.tire.create_elasticsearch_index @question1 = create :question, content: "Some super question?" @question2 = create :question, content: "Some extra question?" app = create :app, name: "Marketing", id: 76 @question1 = create :question, content: "Some super question?", app: app @question2 = create :question, content: "Some extra question?", app: app # wait for indexing to finish sleep 1 end describe "#results" do it "returns matched results" do Search.new("Some", [76]).results.map(&amp;:content).should == ["Some super question?", "Some extra question?"] end it "excludes not matching results" do Search.new("extra", [76]).results.map(&amp;:content).should == ["Some extra question?"] end it "returns no matches" do Search.new("hiper", [76]).results.map(&amp;:content).should == [] end it "should filter results by app" do Search.new("some", [77]).results.map(&amp;:content).should == [] end end describe "#autocomplete" do it "returns array with matching items" do Search.new("super", [76]).autocomplete.should == [{ :title=&gt;@question1.content, :label=&gt;"Some &lt;span class=\"bold\"&gt;super&lt;/span&gt; question? &lt;span class=\"search-type\"&gt;Question&lt;/span&gt;", :value=&gt;"/Marketing/q/#{@question1.id}" }] end end describe "#strip_tags" do it "should strip title" do Search.new("super", [76]).strip_tags("&lt;p&gt;Some text&lt;/p&gt; ").should == "Some text" end end </code></pre> <p>Is there a better way to test that methods in service class ?</p>
[]
[ { "body": "<p>Use <code>let</code> (or <code>let!</code>) to set up your fixtures instead of the instance variables. </p>\n\n<pre><code>let!(:app) { create :app, name: \"Marketing\", id: 76 }\nlet!(:question1) { create :question, content: \"Some super question?\" }\nlet!(:question2) { create :question, content: \"Some extra question?\" }\nlet!(:with_app1) { create :question, content: \"Some super question?\", app: app }\nlet!(:with_app2) { create :question, content: \"Some extra question?\", app: app }\n</code></pre>\n\n<p>Use <code>subject</code> (in combination with <code>let</code>). Here are some examples:</p>\n\n<pre><code>describe \"#results\" do\n subject { Search.new(keyword, [app_id]).results.map(&amp;:content) }\n\n context \"existing app_id\" do\n let(:app_id) { 76 }\n\n context \"multiple matches\" do\n let(:keyword) { \"Some\" }\n\n its(:size) { should == 2 }\n it { should include(with_app1.content) }\n it { should include(with_app2.content) }\n end\n\n context \"single matches\" do\n let(:keyword) { \"extra\" }\n\n its(:size) { should == 1 }\n it { should include(with_app2.content) }\n end\n\n context \"no matches\" do\n let(:keyword) { \"hiper\" }\n\n it { should be_empty }\n end\n end\n\n context \"non-exisiting app_id\" do\n let(:keyword) { \"some\" }\n let(:app_id) { 123 }\n\n it { should be_empty }\n end\nend\n</code></pre>\n\n<p>You will end up with more code if you follow this through, but also with more and finer grained examples (each <code>it</code> or <code>its</code> block is a single example). </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T04:24:10.750", "Id": "20015", "ParentId": "19947", "Score": "2" } } ]
{ "AcceptedAnswerId": "20015", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T17:30:19.020", "Id": "19947", "Score": "1", "Tags": [ "ruby", "ruby-on-rails", "rspec" ], "Title": "Refactor specs for service class methods" }
19947
<p>Trying to see if anyone sees any potential flaws with this submit function. One concern is this line:</p> <pre><code>/* Not sure if this is needed if ($this-&gt;session-&gt;userdata('failed_logins')) { // User has previous failed logins in session $failed_logins = $this-&gt;session-&gt;userdata('failed_logins'); } */ /** * submit function. * * @access public * @param string $post_username * @param string $post_password * @return json data string */ public function submit($post_username = NULL, $post_password = NULL) { // Set variable defaults $output_status = 'Notice'; $output_title = 'Not Processed'; $output_message = 'The request was unprocessed!'; // Set validation rules for post data $this-&gt;form_validation-&gt;set_rules('username', 'Username', 'trim|required|xss_clean|min_length[6]|max_length[12]|regex_match[/[a-z0-9]/]'); $this-&gt;form_validation-&gt;set_rules('password', 'Password', 'trim|required|xss_clean|min_length[6]|max_length[12]|regex_match[/[a-z0-9]/]'); $this-&gt;form_validation-&gt;set_rules('remember', 'Remember Me', 'trim|xss_clean|integer'); if ($this-&gt;form_validation-&gt;run() == TRUE) { // Form validation passed // Number of error flags $x = 0; // Post values from login form $post_username = $this-&gt;input-&gt;post('username'); $post_password = $this-&gt;input-&gt;post('password'); // Get user data from post username value $user_data = $this-&gt;users_model-&gt;get_users(array('usernames' =&gt; $post_username), 'row'); //print_r($user_data); //die(); if ($user_data !== NULL) { // User was found in database if ($user_data-&gt;lock_date !== '0000-00-00 00:00:00') { // User is locked out // Get the current GMT time $current_time = now(); if (strtotime($user_data-&gt;lock_date) &gt; $current_time) { // User is still locked out $output_status = 'Error'; $output_title = 'Account Locked'; $output_message = 'This user account is current locked!'; $x++; } else { // User can be unlocked and form be resubmitted $this-&gt;users_model-&gt;unlock_user($user_data-&gt;user_id); $this-&gt;submit($post_username, $post_password); return FALSE; } } if ($x == 0) { // No error flags reported // User is not locked out if ($user_data-&gt;user_status_id == 1) { $output_status = 'Error'; $output_title = 'Account Unverified'; $output_message = 'Sorry you must verify your account before logging in!'; $x++; } if ($user_data-&gt;user_status_id == 3) { $output_status = 'Error'; $output_title = 'Account Suspended'; $output_message = 'Your account has been suspended!'; $x++; } if ($user_data-&gt;user_status_id == 4) { $output_status = 'Error'; $output_title = 'Account Banned'; $output_message = 'Your account has been banned!'; $x++; } if ($user_data-&gt;user_status_id == 5) { $output_status = 'Error'; $output_title = 'Account Deleted'; $output_message = 'Your account has been deleted!'; $x++; } if ($x == 0) { // No error flags reported // User is registered and verified $regenerated_post_password = $this-&gt;functions_model-&gt;regenerate_password_hash($post_password, $user_data-&gt;password_hash); /* Not sure if this is needed if ($this-&gt;session-&gt;userdata('failed_logins')) { // User has previous failed logins in session $failed_logins = $this-&gt;session-&gt;userdata('failed_logins'); } */ if ($regenerated_post_password == $user_data-&gt;password) { // Password from login form matches user stored password // Set session variable with user id and clear previous failed login attempts $this-&gt;session-&gt;set_userdata('xtr', $user_data-&gt;user_id); $this-&gt;session-&gt;unset_userdata('failed_logins'); $output_status = 'Success'; $output_title = 'Login Success'; $output_message = 'Successful login! Sending you to the dashboard'; } else { // Password from login from does not match user stored password if (is_integer($failed_logins)) { // User has atleast one failed login attempt for the current session if ($failed_logins == 4) { $wait_time = 60 * 15; $lock_out_time = $current_time + $wait_time; /* Find out about if I can do this part differently. $lock_out_date = gmdate('Y-m-d H:i:s', $lock_out_time); */ $this-&gt;users_model-&gt;lock_out_user($user_data-&gt;user_id, $lock_out_date); //$this-&gt;functions_model-&gt;send_email('maximum_failed_login_attempts_exceeded', $user_data-&gt;email_address, $user_data) $output_status = 'Error'; $output_title = 'Account Locked'; $output_message = 'Your account is currently locked, we apologize for the inconvienence. You must wait 15 minutes before you can log in again! An email was sent to the owner of this account! Forgotten your username or password? &lt;a href="forgotusername"&gt;Forgot Username&lt;/a&gt; or &lt;a href="forgotpassword"&gt;Forgot Password&lt;/a&gt;'; } else { // User has a few more chances to get password right $failed_logins++; $this-&gt;session-&gt;set_userdata('failed_logins', $failed_logins); $output_status = 'Error'; $output_title = 'Incorrect Login Credentials'; $output_message = 'Incorrect username and password credentials!'; } } else { // First time user has not entered username and password correctly $this-&gt;session-&gt;set_userdata('failed_logins', 1); $output_status = 'Error'; $output_title = 'Incorrect Login Credentials'; $output_message = 'Incorrect username and password credentials!'; } $time_of_attempt = gmdate('Y-m-d H:i:s'); $this-&gt;users_model-&gt;increase_login_attempt($this-&gt;input-&gt;ip_address(), $post_username, $time_of_attempt); } } // if ($x = 0) User is registered and verified } // if ($x = 0) User is not locked out } else { // User was not found in database $output_status = 'Error'; $output_title = 'User Not Found'; $output_message = 'The user was not found in the database!'; } } else { // Form validation failed $output_status = 'Error'; $output_title = 'Form Not Validated'; $output_message = 'The form did not validate successfully!'; } echo json_encode(array('output_status' =&gt; $output_status, 'output_title' =&gt; $output_title, 'output_message' =&gt; $output_message, 'error_messages' =&gt; $this-&gt;form_validation-&gt;error_array())); } </code></pre> <p>EDIT 2: This is what I have so far. Any additional ideas?</p> <pre><code>public function form_is_valid() { $this-&gt;form_validation-&gt;set_rules('username', 'Username', 'trim|required|xss_clean|min_length[6]|max_length[12]|regex_match[/[a-z0-9]/]'); $this-&gt;form_validation-&gt;set_rules('password', 'Password', 'trim|required|xss_clean|min_length[6]|max_length[12]|regex_match[/[a-z0-9]/]'); return $this-&gt;form_validation-&gt;run(); } public function submit() { $output_status = 'Notice'; $output_title = 'Not Processed'; $output_message = 'The request was unprocessed!'; if ($this-&gt;form_is_valid()) { $output_status = 'Success'; $output_title = 'Form Submitted Successfully'; $output_message = 'The form did validate successfully!'; } else { $output_status = 'Error'; $output_title = 'Form Not Validated'; $output_message = 'The form did not validate successfully!'; } echo json_encode(array('output_status' =&gt; $output_status, 'output_title' =&gt; $output_title, 'output_message' =&gt; $output_message, 'error_messages' =&gt; $this-&gt;form_validation-&gt;get_error_array())); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T20:59:30.467", "Id": "31895", "Score": "0", "body": "for starts Replace `if ($this->form_validation->run() == TRUE)` for `if ($this->form_validation->run())` you don't need to compare `if(true == true)`" } ]
[ { "body": "<p><strong>Replace</strong> </p>\n\n<p><code>if ($this-&gt;form_validation-&gt;run() == TRUE)</code> <strong>for</strong> <code>if ($this-&gt;form_validation-&gt;run())</code> </p>\n\n<p>You don't need to compare <code>if(true == true)</code></p>\n\n<hr>\n\n<p><strong>In this part:</strong></p>\n\n<pre><code>if ($user_data-&gt;user_status_id == 1)\n{\n $output_status = 'Error';\n $output_title = 'Account Unverified';\n $output_message = 'Sorry you must verify your account before logging in!';\n $x++;\n}\n\nif ($user_data-&gt;user_status_id == 3)\n{\n $output_status = 'Error';\n $output_title = 'Account Suspended';\n $output_message = 'Your account has been suspended!';\n $x++;\n}\n\nif ($user_data-&gt;user_status_id == 4)\n{\n $output_status = 'Error';\n $output_title = 'Account Banned';\n $output_message = 'Your account has been banned!';\n $x++;\n}\n\nif ($user_data-&gt;user_status_id == 5)\n{\n $output_status = 'Error';\n $output_title = 'Account Deleted';\n $output_message = 'Your account has been deleted!';\n $x++;\n}\n</code></pre>\n\n<p>Replace <code>IF</code> for <code>ELSE IF</code> or <code>SWITCH</code>.</p>\n\n<hr>\n\n<p><strong>Extra (optional)</strong>\nyour code <code>if ($x == 0)</code> has another <code>if ($x == 0)</code> inside itself. you don't need it if you just use a <strong>bool</strong> flag instead. Changing <code>x</code> is not good.</p>\n\n<hr>\n\n<p>Read about <a href=\"http://ellislab.com/codeigniter/user-guide/libraries/sessions.html\" rel=\"nofollow\">Sessions in CodeIgniter</a>, will help you understand this part. </p>\n\n<pre><code>if ($this-&gt;session-&gt;userdata('failed_logins'))\n{\n // User has previous failed logins in session\n $failed_logins = $this-&gt;session-&gt;userdata('failed_logins');\n}\n</code></pre>\n\n<p>The <code>$this-&gt;session-&gt;userdata('failed_logins')</code> verify if you have created this session. <em>The code you posted doesn't countain this creation.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T21:50:43.697", "Id": "31897", "Score": "0", "body": "Can you explain the last part further because after reading the documentation I'm still confused on what would be a better use with this bit of code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T23:02:48.693", "Id": "31906", "Score": "0", "body": "Also about the part of the flag what do you suggest because I do error checking then if I'm still good after the first round of error flags then I need to do a second round of error checking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T12:38:26.607", "Id": "31917", "Score": "0", "body": "When you start `$x = 0;` you can also starts a bool variable, let's say... `$NoError = true` then in the second `if ($x == 0)` you can use `if($NoError)`. Also change the `$x++;` for `$NoError= false;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T12:42:17.740", "Id": "31918", "Score": "0", "body": "@KevinSmith [about sessions in php](http://www.w3schools.com/php/php_sessions.asp) the link for codeigniter is in the answer already. the `$this->session->userdata('failed_logins')` is **NEVER** created in the code that you posted, so this if will **NEVER** be used. Just remove it. (Or find the part that you load the session)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T21:19:59.177", "Id": "19954", "ParentId": "19951", "Score": "1" } }, { "body": "<p>The access parameter in your doccomments is unnecessary. Any application that is sophisticated enough to provide doccomment hints is also sophisticated enough to tell you the access method automatically. At least I have yet to find one that contradicts this.</p>\n\n<p>Your function is doing entirely too much. The Single Responsibility Principle states that a function/method should be in charge of doing one thing and one thing only, and should not be concerned with all of the smaller tasks associated with doing it. Additionally, the name of that function should be indicative of what it is supposed to do. Believe it or not, you've already separated your code, at least partially, by this principle. You just haven't done so with methods (Hint: the next paragraph).</p>\n\n<p>Internal comments only add clutter to your code. If your code is self-documenting and following standard practices, then internal comments become unnecessary. The only comments you should really need are doccomments. Let your code speak for itself. If something isn't clear enough, either make note of it in the doccomments, or clean up the code to make it clearer.</p>\n\n<p>Your code is severely suffering from the Arrow Anti-Pattern. This pattern illustrates code that has been excessively indented to come to points like an arrow, or multiple arrows. Sometimes also known as being mountainous. The arrow shapes is one indication of such a violation, but may not always be visible. There are a few things you can do to avoid violating this pattern: you can reverse long if statements for shorter else statements, dropping the else and unindenting the contents; you can return early, which also helps with efficiency; and you can create defaults. The following code accomplishes all three:</p>\n\n<pre><code>$output_status = 'Error';\n$output_title = 'Form Not Validated';\n$output_message = 'The form did not validate successfully!';\n$error_messages = array();\n\nif( ! $this-&gt;form_validation-&gt;run() ) {\n return json_encode( compact(\n 'output_status',\n 'output_title',\n 'output_message',\n 'error_messages'\n ) );\n} //else {//the else is now implied because we returned early\n\n//the rest of the code can be unindented now\n</code></pre>\n\n<p>So you may notice a few other things. The first is something that Michel pointed out in his answer. There is no need to explicitly check for a boolean unless you are explicitly looking for one. PHP automatically converts 0, NULL, FALSE, -1, or any string equivalent or empty string to FALSE. Everything else is considered \"loosely\" <code>==</code> TRUE. So unless you are explicitly <code>===</code> looking for that value, there is no need to explicitly ask for it.</p>\n\n<pre><code>if( \"TRUE\" == TRUE ) {//TRUE and unnecessary\nif( \"TRUE\" ) {//TRUE\nif( \"TRUE\" === TRUE ) {//FALSE because of types\n</code></pre>\n\n<p>The next is that I removed the <code>echo</code> from your code. You should avoid this as it makes your code less reusable. Returning that value allows you to do more with it and gives you something to return early.</p>\n\n<p>The final thing I changed was incorporating <code>compact()</code>. This function accepts variables, via their name as a string, and pushes them into an array with the given name as the key. You don't have to use this function, some people find it confusing because the IDE does not register that those variables are being used, but I find it useful.</p>\n\n<p>What is the point of injecting the <code>$post_username</code> and <code>$post_password</code> if all you are going to do is just reset its value? Just a reminder, this method doesn't need to know where everything is coming from. That's the whole point of injecting the values.</p>\n\n<p>Instead of using a counter to determine if any errors occurred, why not just save those errors to an array and then check the array?</p>\n\n<pre><code>$errors = array();\n\n//etc...\n\n$error = compact( 'output_status', 'output_title', 'output_message' );\n$errors[] = $error;\n\n//etc...\n\nif( ! empty( $errors ) ) {\n</code></pre>\n\n<p>As Michel mentioned, you might consider using a switch statement if you are planning on comparing the same value against multiple conditions. Additionally, this is violating the \"Don't Repeat Yourself\" (DRY) Principle. As the name implies, your code should not repeat itself. In this case, each of these statements starts off by redefining the <code>$output_status</code> variable to \"Error\", which is redundant. Set it as that by default and then use the <code>default</code> switch statement to change it if necessary. At this point I have stopped keeping track of what the last value of these variables were, but that is something you should be able to use to your advantage.</p>\n\n<pre><code>$output_status = 'Error';\n\nswitch( $user_data-&gt;user_status_id ) {\n case 1 :\n $output_title = 'Account Unverified';\n $output_message = 'Sorry you must verify your account before logging in!';\n break;\n\n //etc...\n\n default :\n $output_status = etc...;\n break;\n}\n</code></pre>\n\n<p>Alternatively you could also create an array with these comparisons as the key and the values as an array containing the necessary output information. This is probably the ideal method.</p>\n\n<pre><code>$status = $user_data-&gt;user_status_id;\nif( isset( $error_messages[ $status ] ) ) {\n $error = $error_messages[ $status ];\n $output_title = $error[ 'title' ];\n $output_message = $error[ 'message' ];\n}\n</code></pre>\n\n<p>I'm going to stop here. For the most part it looks like more of the same. I would focus on the principles I mentioned and try to apply them to your code. Those are the biggest issues that I can see.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T12:44:47.773", "Id": "31919", "Score": "0", "body": "+1 \"My reviews tend to be more text than code.\", True story. But good answer anyway. =D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-28T19:21:55.353", "Id": "31961", "Score": "0", "body": "http://pastebin.com/2H3k6jR1 Update" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-01T18:37:10.070", "Id": "32086", "Score": "0", "body": "Any ideas on improvements?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-02T17:16:42.493", "Id": "32105", "Score": "0", "body": "@KevinSmith: Sorry for the delay, I was away for new years. I didn't read the whole thing, but I did scan and compare it to the old. It looks like the only change you made was the switch statement. The biggest improvement you can make would be to downsize your function into multiple smaller functions, then there is the arrow anti-pattern, and the internal comments. Each of these will immediately show improvement. There is still a lot to be gleaned from the original post, so make sure to look over it again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-02T19:16:38.617", "Id": "32107", "Score": "0", "body": "I'm going to try and post in a few minutes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T20:16:57.073", "Id": "32170", "Score": "0", "body": "I've updated my response. This is just the submit button I have no included the other functions at this time. Using the logic from my original post am I on the right path or do I have any order of logic wrong." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T23:26:18.713", "Id": "19955", "ParentId": "19951", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T20:04:55.050", "Id": "19951", "Score": "0", "Tags": [ "php", "codeigniter" ], "Title": "Submit function For Login" }
19951