body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Using the eclipse formatting on a class with some <code>@NamedQueries</code> created concatenations.</p> <p>While I have been doing this for years without paying attention I just realised that may be it is not a good usage.</p> <p>So basically Which one of these <code>String</code>s inside the <code>query</code>is better ? Is the second one creating too many <code>String</code>s? Should I be bothered at all?</p> <p>My answer would be yes second one is creating extra Strings but I am not sure I should be concerned.</p> <p><strong>First Query</strong></p> <pre><code> @NamedQuery( name = SomeConstant, query="SELECT person FROM Person person Where person.name = :name ") </code></pre> <p><strong>Second Query</strong></p> <pre><code> @NamedQuery( name = SomeConstant, query="SELECT person FROM Person person"+" "+ "Where person.name = :name ") </code></pre>
[]
[ { "body": "<p>Enter the mad world of optimization!</p>\n\n<p>The Java compiler and HotSpot just-in-time compiler are programmed with a great many rules for optimizing performance of Java code.</p>\n\n<p>In general, it is NOT worth your time to fret about the performance impact of these kinds of details as they are often taken care of. Rather, just try to write clean readable code that solves the problem. If performance is an issue, profile the code and then optimize the bottlenecks.</p>\n\n<p>Now, to address this specific issue, I am virtually certain that constant expressions are resolved by the Java compiler at compile time. I would be very surprised if the byte code for your two queries wasn't identical.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T06:14:55.680", "Id": "19201", "Score": "0", "body": "Good call I will check the byte code. I should have done that first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T00:47:26.377", "Id": "19221", "Score": "0", "body": "Byte code editor confirms that `String`s are exactly the same." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T06:12:01.210", "Id": "11964", "ParentId": "11963", "Score": "10" } } ]
{ "AcceptedAnswerId": "11964", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T05:49:02.673", "Id": "11963", "Score": "2", "Tags": [ "java", "strings" ], "Title": "Is this String concatenation creating extra String?" }
11963
<p>I want to realize an object cache which holds objects loaded from database, file or other slow access source, to make them available quickly with high performance. There will be a lot of accesses to get these objects from the dictionary!</p> <p>It's not supposed to be Singleton/Static; multiple different object holders are possible, with multiple threads running on each.</p> <p>Access is usually read-only, the objects themselves (in the dictionary) shall not be changed after being created. </p> <p>For some special Admin functions, a Reload method exists, where thread safety can be ignored (not to be used by the main, multi-threaded program).</p> <p>If I am right, the .NET Dictionary is thread-safe, as long as it is used only in read access, thus not requiring locks in reading methods. The dictionary will not be changed after being assigned to the <code>_progObjects</code> variable (do I need to make it volatile?). But time consuming volatile (alternatively Interlocked) access on the <code>_areProgObjectsInitialized</code> variable seems to be necessary, to make first accesses (with initialization) thread-safe.</p> <p>Is the following a good and performant solution, can it still be improved, or are there safety risks?</p> <pre><code>/// &lt;summary&gt; /// Not Singleton, but each instance multi-threaded! /// Holds objects loaded from an external source (database, file, whatever...) /// &lt;/summary&gt; public class ProgObjectsThreadSafeRead : IProgObjectsThreadSafeRead { private IDictionary&lt;ObjectKey, object&gt; _progObjects = null; private object _progObjectsSyncObj = new object(); private volatile bool _areProgObjectsInitialized = false; private void InitializeProgObjectsIfNeeded() { if (!_areProgObjectsInitialized) { lock(_progObjectsSyncObj) { if (!_areProgObjectsInitialized) { IDictionary&lt;ObjectKey, object&gt; localProgObj = LoadProgObjects(); // do something more _progObjects = localProgObj; _areProgObjectsInitialized = true; } } } } public object GetProgObject(ObjectKey key) { InitializeProgObjectsIfNeeded(); return _progObjects[key]; } /// &lt;summary&gt; /// Not thread safe, don't use in multi-thread environments! /// Specific editing tools only! Not in interface. /// &lt;/summary&gt; public void ReloadProgObjects() { lock (_progObjectsSyncObj) { _areProgObjectsInitialized = false; InitializeProgObjectsIfNeeded(); } } // others removed } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T18:43:26.057", "Id": "62791", "Score": "0", "body": "If you want to test the performance of the ReaderWriterLockSlim, here is a small caching class that I did a while ago that uses it : [Tiny ThreadSafe Cache C#](http://tinythreadsafecache.codeplex.com)" } ]
[ { "body": "<p>You were right about the dictionary, the only thing i would change (i don't know if it is relevant for you, but it is a classic usage in your case) is using ReaderWriterLockSlim - <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim(v=vs.100).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim(v=vs.100).aspx</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T14:30:28.460", "Id": "19213", "Score": "0", "body": "As I read, even the new ReaderWriterLockSlim is still by factor 1.7 slower than a classic lock (aka Monitor) block, when entering in read mode. My goal was to avoid locks for reading, in best case to abandon all synchronization after the object is initialized, but it seems to be impossible or dangerous - so I resort to primitive sync access (volatile, interlocked). ReaderWriterLocks may be good for more complex accesses where multiple readers outweight the ReaderWriterLock penalty, but probably not for getting values from a dictionary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T14:55:22.060", "Id": "19214", "Score": "0", "body": "It depends on your usage: http://stackoverflow.com/questions/407238/readerwriterlockslim-vs-monitor\nAnyway, i was wrong because i meant ReaderWriterLockSlim and not ReaderWriterLock" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T14:06:44.613", "Id": "11968", "ParentId": "11967", "Score": "1" } }, { "body": "<blockquote>\n <p>the .NET Dictionary is thread-safe, as long as it is used only in read access, thus not requiring locks in reading methods. </p>\n</blockquote>\n\n<p>You are playing with fire here. Your statement is only true iff <em>no</em> thread will modify the dictionary. If any of them do, which is about impossible to avoid in a cache, then a lock on <em>both</em> the reading and the writing code is required. A natural consequence of not being able to reliably read a data structure while it is in the process of being modified.</p>\n\n<p>The ReaderWriterLock/Slim classes were designed to provide you this kind of locking. You must acquire a reader lock when you read, a writer lock when you write. Multiple threads can acquire a reader lock so you won't have any serious overhead as long as the cache is productive. The Slim version uses a low cost locking primitive which can reduce the lock cost somewhat. But it is no cure when there's a lot of write contention, no magic formula exists for that. If you do have a lot of write contention then double-check if the old ReaderWriterLock may give better throughput.</p>\n\n<p>And be sure to checkout the .NET 4 <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx\">MemoryCache class</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T16:10:31.033", "Id": "19215", "Score": "0", "body": "In fact, the cache is designed to read once, provide \"for all time\". The ReloadProgObjects() is only for specific tools not running multi-threaded (I could also mark it \"internal\") - it is NOT a refreshing method running from time to time again! So my idea was I have only the initialization to synchronize and make sure no thread accesses an uninitialized dictionary. I don't know of any risk that hidden changes to the dictionary might occur from various threads." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T16:13:02.890", "Id": "19216", "Score": "0", "body": "Sorry, I can't envision the usefulness of a \"read once cache\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-28T14:59:52.157", "Id": "386007", "Score": "0", "body": "His solution looks fine to me. He is saying that he \"reads\" in the data once and initializes the dictionary and then makes no further changes afterwards." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T15:25:21.477", "Id": "11969", "ParentId": "11967", "Score": "7" } }, { "body": "<p>If you want a name-value collection that supports concurrent access take a look at <a href=\"http://msdn.microsoft.com/en-us/library/dd287191.aspx\" rel=\"nofollow\"><code>System.Collections.Concurrent.ConcurrentDictionary</code></a>. This does its own internal light weight locking.</p>\n\n<p>NB. it is not suitable if you need to work with multiple data structures together or where multiple operations need to be performed on the dictionary (a different thread might get access between operations that should always happen together). For independent operations (separate reads and writes/updates) a <code>ConcurrentDictionary</code> is thread safe.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T16:25:38.197", "Id": "11970", "ParentId": "11967", "Score": "3" } }, { "body": "<p>I know this is late but your solution looks fine. You are creating the dictionary once and then never changing it afterwards so you can safely read from it from as many threads as you like. You don't need the volatile keyword - it will cause calls to your <code>GetProgObject</code> method to be slower under normal circumstances with no benefit since the lock will ensure that the latest value is read within your lock statement. Even if the old value is cached on another processor core, it will very quickly update to the latest correct value within the lock statement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-28T15:03:36.040", "Id": "200486", "ParentId": "11967", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T13:35:19.207", "Id": "11967", "Score": "5", "Tags": [ "c#", "performance", ".net", "thread-safety" ], "Title": "Thread-safe object cache, for read, high performance in .NET" }
11967
<p>It's been a long while since I've done any Python programming so I thought I'd start with a simple Blackjack game. Any comments on how I can make this more readable? Use more methods perhaps?</p> <pre><code>from sys import exit from random import randint class Game(object): def __init__(self, start): self.quips = [ " you kinda suck at this.", "don't quit your day job.", "Such a loser." ] self.start = start #main method to start playing def play(self): next = self.start action = "y" #start playing while True: print "\n-------" print "Beginning blkjk" print "Dealing.. \n" #deal user's cards unum1 = randint(1,10) unum2 = randint(1,10) utotal = unum1 + unum2 print "Ur cards are: %d &amp; %d totalling %d \n" % (unum1, unum2,utotal) #hit until user says stop while action == "y": action = raw_input("Hit? &gt; ") if action == "y": utotal = utotal + self.hit() print "ur new total is %d" % utotal print "Ur total is %d " % utotal #deal dealer's cards dnum1 = randint(1,10) dnum2 = randint(1,10) dtotal = dnum1 + dnum2 print "Dealer's cards are %d &amp; %d totalling %d \n" % (dnum1, dnum2, dtotal) #dealer keeps hitting until close/more than 21 while dtotal &lt; 21: print" Dealer hits\n" dtotal = dtotal + self.hit() if dtotal &lt;= 21: print "Dealer's total is %d " % dtotal if utotal &gt; dtotal: print "you win!" exit(1) else: print "dealer wins" self.death() else: print "Dealer busts, u win!" exit(1) def death(self): print self.quips[randint(0, len(self.quips)-1)] exit(1) def hit(self): nextcard = randint(1,9) print "ok, next card is %d " % nextcard return nextcard a_game = Game("deal") a_game.play() </code></pre>
[]
[ { "body": "<p>One problem I see is that your dealing may result in card repetition, which would be illegal. You are going to need to track which card has already been played and not to use them again.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T14:39:11.823", "Id": "11973", "ParentId": "11972", "Score": "3" } }, { "body": "<p>I don't think that having a huge \"Game\" class that contains the flow of the entire game is the way you want to do it. Why don't you break the game into some manageable chunks? Here's what I came up with after a little thinking:</p>\n\n<pre><code>import random\nDEFAULT_CHIPS = 20\n\nclass Card(object):\n card_to_name = {1:\"Ace\", 2:\"Two\", 3:\"Three\", 4:\"Four\", 5:\"Five\", 6:\"Six\", 7:\"Seven\",\n 8:\"Eight\", 9:\"Nine\", 10:\"Ten\", 11:\"Jack\", 12:\"Queen\", 13:\"King\"}\n\n def __init__(self, value, suit):\n self.name = self.card_to_name[value]\n self.suit = suit\n self.title = \"%s of %s\" % (self.name, self.suit)\n self.score = min(value, 10)\n\n def __repr__(self):\n return self.title\n\nclass Hand(object):\n def __init__(self, cards):\n self.hand = cards\n\n def get_scores(self):\n num_aces = sum(card.name == \"Ace\" for card in self.hand)\n score = sum(card.score for card in self.hand)\n return [score + i*10 for i in range(num_aces+1)]\n\n def possible_scores(self):\n return [s for s in self.get_scores() if s &lt;= 21]\n\n def __repr__(self):\n return str(self.hand)\n\nclass Deck(object):\n unshuffled_deck = [Card(card, suit) for card in range(1, 14) for suit in [\"Clubs\", \"Diamonds\", \"Hearts\", \"Spades\"]]\n def __init__(self, num_decks=1):\n self.deck = self.unshuffled_deck * num_decks\n random.shuffle(self.deck)\n\n def deal_card(self):\n return self.deck.pop()\n\n def deal_hand(self):\n return Hand([self.deal_card(), self.deal_card()])\n\nclass Player(object):\n def __init__(self, name=\"Player 1\", chips=DEFAULT_CHIPS):\n self.name = name\n self.chips = chips\n self.current_bet = 0\n\n def new_hand(self, hand):\n self.hand = hand\n\n def hit(self, card):\n self.hand.hand.append(card)\n\n def is_busted(self):\n return len(self.hand.possible_scores()) == 0\n\n def scores(self):\n return self.hand.get_scores() if self.is_busted() else self.hand.possible_scores()\n\n def __repr__(self):\n player_str = self.name + \"(BUSTED)\" if self.is_busted() else self.name\n return \"Player: {}\\nChips: {}\\nCurrent Bet: {}\\nCards: {}\\nScore: {}\".format(\n player_str, self.chips, self.current_bet, self.hand, self.scores())\n\nif __name__ == \"__main__\":\n d = Deck()\n print d.deck\n h = d.deal_hand()\n p = Player()\n p.new_hand(h)\n print p\n p.hit(d.deal_card())\n print p\n</code></pre>\n\n<p>Here is some test output:</p>\n\n<blockquote>\n <p>[Two of Spades, Two of Diamonds, Three of Clubs, Ten of Hearts, Ace of<br>\n Diamonds, Eight of Diamonds, Seven of Diamonds, King of Hearts, Seven<br>\n of Hearts, Queen of Diamonds, Six of Clubs, Nine of Diamonds, Seven of<br>\n Spades, Four of Spades, Four of Diamonds, Ten of Clubs, Four of Clubs,<br>\n Jack of Hearts, Ace of Clubs, Six of Spades, Eight of Spades, Seven of<br>\n Clubs, Eight of Hearts, Three of Diamonds, Jack of Clubs, King of<br>\n Diamonds, Five of Clubs, King of Clubs, Ace of Spades, King of Spades,<br>\n Six of Diamonds, Ten of Diamonds, Queen of Clubs, Two of Hearts, Eight<br>\n of Clubs, Nine of Hearts, Ace of Hearts, Five of Spades, Jack of<br>\n Diamonds, Nine of Spades, Four of Hearts, Six of Hearts, Two of Clubs,<br>\n Three of Spades, Jack of Spades, Five of Diamonds, Three of Hearts, Ten<br>\n of Spades, Five of Hearts, Queen of Hearts, Nine of Clubs, Queen of<br>\n Spades]<br>\n Player: Player 1<br>\n Chips: 20<br>\n Current Bet: 0<br>\n Cards: [Queen of Spades, Nine of Clubs]<br>\n Score: [19]<br>\n Player: Player 1(BUSTED)<br>\n Chips: 20<br>\n Current Bet: 0<br>\n Cards: [Queen of Spades, Nine of Clubs, Queen of Hearts]<br>\n Score: [29]</p>\n</blockquote>\n\n<p>From there, implementing the game in a clean fashion wouldn't be too tough.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T15:27:30.790", "Id": "11975", "ParentId": "11972", "Score": "6" } }, { "body": "<p>Nolen Royalty has an excellent example of a well-structured version. Here are some comments on your version.</p>\n\n<pre><code>from sys import exit \nfrom random import randint \n\nclass Game(object): \n\n def __init__(self, start):\n self.quips = [\n \" you kinda suck at this.\",\n</code></pre>\n\n<p>Why the space?</p>\n\n<pre><code> \"don't quit your day job.\",\n \"Such a loser.\"\n</code></pre>\n\n<p>Why is only this one capitalized?</p>\n\n<pre><code> ]\n</code></pre>\n\n<p>This seems to be a constant list, as such its better as a global constant or a class attribute then a object attribute.</p>\n\n<pre><code> self.start = start \n\n #main method to start playing \n def play(self):\n next = self.start \n action = \"y\" \n</code></pre>\n\n<p>assign this closer to where you actually use it</p>\n\n<pre><code> #start playing \n while True:\n print \"\\n-------\"\n</code></pre>\n\n<p>I suggest using an empty print to produce new lines for consistency</p>\n\n<pre><code> print \"Beginning blkjk\"\n print \"Dealing.. \\n\" \n\n #deal user's cards \n unum1 = randint(1,10) \n unum2 = randint(1,10)\n</code></pre>\n\n<p>Give variables names that hint at their usage, <code>unum1</code> doesn't really.</p>\n\n<pre><code> utotal = unum1 + unum2 \n\n\n print \"Ur cards are: %d &amp; %d totalling %d \\n\" % (unum1, unum2,utotal)\n\n #hit until user says stop \n while action == \"y\": \n action = raw_input(\"Hit? &gt; \")\n if action == \"y\": \n utotal = utotal + self.hit() \n print \"ur new total is %d\" % utotal \n</code></pre>\n\n<p>You should put this block after the loop as it'll do the same thing.</p>\n\n<pre><code> print \"Ur total is %d \" % utotal\n\n #deal dealer's cards \n dnum1 = randint(1,10) \n dnum2 = randint(1,10)\n</code></pre>\n\n<p>With all this different instances of getting a card, perhaps you should have a function to do it.</p>\n\n<pre><code> dtotal = dnum1 + dnum2 \n print \"Dealer's cards are %d &amp; %d totalling %d \\n\" % (dnum1, dnum2, dtotal)\n</code></pre>\n\n<p>The same logic is being repeated again for the dealer as there was for the player. This suggest a class to represent a Hand of cards might be in order</p>\n\n<pre><code> #dealer keeps hitting until close/more than 21\n while dtotal &lt; 21: \n print\" Dealer hits\\n\"\n dtotal = dtotal + self.hit()\n\n if dtotal &lt;= 21:\n print \"Dealer's total is %d \" % dtotal\n if utotal &gt; dtotal: \n print \"you win!\"\n exit(1)\n</code></pre>\n\n<p>Don't use exit to close your programs. Just break out of any loops</p>\n\n<pre><code> else:\n print \"dealer wins\"\n</code></pre>\n\n<p>What if you tied?</p>\n\n<pre><code> self.death()\n else:\n print \"Dealer busts, u win!\" \n exit(1) \n\n\n\n\n def death(self):\n print self.quips[randint(0, len(self.quips)-1)]\n</code></pre>\n\n<p>use <code>random.choice</code> to select a random element from a list</p>\n\n<pre><code> exit(1)\n\n def hit(self):\n nextcard = randint(1,9)\n</code></pre>\n\n<p>Why 9 when the rest were 10?</p>\n\n<pre><code> print \"ok, next card is %d \" % nextcard \n return nextcard \n\n\na_game = Game(\"deal\")\n</code></pre>\n\n<p>You seem to be ignoring the parameter</p>\n\n<pre><code>a_game.play() \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T03:49:37.353", "Id": "11983", "ParentId": "11972", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T14:36:52.973", "Id": "11972", "Score": "6", "Tags": [ "python", "game", "playing-cards" ], "Title": "Blackjack card game" }
11972
<p>Recently I started working with TinyMVC, wrote a simple menu model and I have few questions for those who are using it... or used before. </p> <ol> <li>For the following code should I keep it as Model or as a Plugin? </li> <li>How should I implement it in the view and use it on every page that is required without breaking the ideea of MVC and without rewriting again and again for each controller? </li> <li>Any improvements to the code? </li> <li>Need the MySQL tables?</li> </ol> <pre><code>&lt;?php class Menu_Model extends TinyMVC_Model { public function __construct() { parent::__construct(); } public function listMenu() { return $this-&gt;db-&gt;query_all("SELECT * FROM menu_links WHERE is_deleted = 0 ORDER BY position"); } public function listCategorys($menuLinkId) { return $this-&gt;db-&gt;query_all("SELECT * FROM menu_subcategorys WHERE menuLinkId = ? AND is_deleted = 0 ORDER BY position", array($menuLinkId)); } public function buildMenu() { $this-&gt;listMenu = $this-&gt;listMenu(); foreach($this-&gt;listMenu as $this-&gt;listMenuKey =&gt; $this-&gt;listMenuValue) { $this-&gt;listCategorys = $this-&gt;listCategorys($this-&gt;listMenuValue['menuLinkId']); if(!empty($this-&gt;listCategorys)) $this-&gt;listMenu[$this-&gt;listMenuKey]['child'] = $this-&gt;listCategorys; } return $this-&gt;listMenu; } } </code></pre>
[]
[ { "body": "<p>Sorry you had to wait so long, answers here tend to take some time and I've been on vacation the last week, so I wasn't keeping up with this site the way I usually do. So, here we go...</p>\n\n<p><strong>Q: \"Any improvements to the code?\"</strong></p>\n\n<p>First off, I don't think you quite understand inheritance. If you are extending one class from another it automagically inherits all properties and methods of the parent class. Therefore, there is no need for you to recreate a <code>__construct()</code> method if all you are going to do with it is call the parent one. The only reason to do it the way you have is if you had called additional code in the new constructor before or after calling the parent one. Example:</p>\n\n<pre><code>public function __construct() {\n $changedParentVar = 'new value';\n parent::__construct();\n echo 'we changed the \"changedParentVar\" inside the parent constructor method before running it';\n}\n</code></pre>\n\n<p><strong>Clarification:</strong> I'll be honest, I'm not quite sure if this stands true for deep inheritance. Say I have three classes, each inherits from the previous, and only the first has a constructor. I don't know if the third will still have the original constructor. I know it will still have all the other methods, but for some reason I want to say that magical methods are different, yet I can't find anything at the moment to prove this one way or another. So this statement is here to cover my ass :)</p>\n\n<p>I'd find some way of combining your \"list\" methods, something like...</p>\n\n<pre><code>public function list($from, $where, $and = '') {\n if( ! empty($and)) { $and = \"AND $and\"; }\n\n return $this-&gt;db_query_all(\"\n SELECT *\n FROM $from\n WHERE $where\n $and\n ORDER BY position\n \");\n}\n</code></pre>\n\n<p>If you are not going to be reusing a variable (<code>$this-&gt;listMenu</code> or <code>$this-&gt;listCategorys</code> or a foreach variable) there is no need to make them properties. The only reason you should make a variable a property is so that it can be used outside the current method. That being said, take a look at that foreach loop... There is no need to set the key/value pair as a class property as they will not be reused before they are reset, and I doubt you will reuse just the last one. This also stands true for those other two properties I mentioned, they should be variables, not properties. So the <code>buildMenu()</code> method should be rewritten like so.</p>\n\n<pre><code>public function buildMenu() {\n $listMenu = $this-&gt;listMenu(); //Keep this line how you have it if you are using listMenu in another method you did not include here...\n foreach($listMenu as $key =&gt; $value) {\n $listCategorys = $this-&gt;listCategorys($value['menuLinkId']);//BTW its categories not categorys... been bothering me...\n if( ! empty($listCategorys)) { $listMenu[$key]['child'] = $listCategorys; }\n }\n\n return $listMenu;\n}\n</code></pre>\n\n<p>By the way, please, for everyone's sanity, always use braces <code>{}</code> around any statements, even if they are only one line. Its so much easier to read.</p>\n\n<p><strong>Q: How should I implement it in the view and use it on every page that is required without breaking the ideea of MVC and without rewriting again and again for each controller?</strong></p>\n\n<p>You should not implement it in the view, only in the controller. Views should only contain minimal PHP that helps output data.</p>\n\n<p>I'm not sure what you mean about having to rewrite it, please clarify. In the mean time here are a few examples of how I would implement it.</p>\n\n<p>If my controller is a class:</p>\n\n<pre><code>class Controller extends Menu_Model { }\n//OR\nclass Controller {\n public function __construct() {\n include 'path/to/Menu_Model.php';\n $this-&gt;Menu_Model = new Menu_Model();\n }\n}\n</code></pre>\n\n<p>If my controller is just a list of PHP functions or procedural:</p>\n\n<pre><code>include 'path/to/Menu_Model.php';\n$Menu_Model = new Menu_Model();\n</code></pre>\n\n<p>Since you are using MVC, I would also suggest that you take a look at autoloading.</p>\n\n<p><strong>Q: For the following code should I keep it as Model or as a Plugin?</strong></p>\n\n<p>Not sure what you mean by plugin. Model should be fine though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T15:13:01.360", "Id": "12144", "ParentId": "11974", "Score": "3" } } ]
{ "AcceptedAnswerId": "12144", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T15:10:11.653", "Id": "11974", "Score": "2", "Tags": [ "php", "mysql" ], "Title": "TinyMVC Model / Plugin how to implement?" }
11974
<p>I have to implement WMSAuth in C#: <a href="http://wmsauth.org/examples" rel="nofollow noreferrer">http://wmsauth.org/examples</a></p> <pre><code>// The following function was copied from http://wmsauth.org/examples public static string BuildProtectedURLWithValidity(string password, string media_url, string ip, int valid) { string result = null; DateTime cur_date = DateTime.Now; TimeZone localzone = TimeZone.CurrentTimeZone; DateTime localTime = localzone.ToUniversalTime(cur_date); string date_time = localTime.ToString(new CultureInfo("en-us")); Int32 Valid = valid; string to_be_hashed = ip + password + date_time + Valid.ToString(); byte[] to_be_hashed_byte_array = new byte[to_be_hashed.Length]; int i = 0; foreach (char cur_char in to_be_hashed) { to_be_hashed_byte_array[i++] = (byte)cur_char; } byte[] hash = (new MD5CryptoServiceProvider()).ComputeHash(to_be_hashed_byte_array); string md5_signature = Convert.ToBase64String(hash); result = media_url + "?server_time=" + date_time + "&amp;hash_value=" + md5_signature + "&amp;validminutes=" + Valid.ToString(); return (result); } </code></pre> <p>The problem is that, although I believe the code above might work for every possible input, it seems to be done without much knowledge of C#, and I have a big concern with the <a href="https://stackoverflow.com/questions/10708548/encoding-used-in-cast-from-char-to-byte">Encoding in the byte to char casting</a>.</p> <p>So I changed the code to this:</p> <pre><code>private static string BuildProtectedURLWithValidity(string wmsAuthPassword, string mediaUrl, string clientIp, int validMinutes) { string dateTimeString = DateTime.UtcNow.ToString(new CultureInfo("en-us")); string validMinutesString = validMinutes.ToString(); string stringToBeHashed = clientIp + wmsAuthPassword + dateTimeString + validMinutesString; string hashValue; using (MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider()) { byte[] bytesToBeHashed = Encoding.UTF8.GetBytes(stringToBeHashed); byte[] hashBytes = md5Provider.ComputeHash(bytesToBeHashed); hashValue = Convert.ToBase64String(hashBytes); } string result = mediaUrl + "?server_time=" + dateTimeString + "&amp;hash_value=" + hashValue + "&amp;validminutes=" + validMinutesString; return result; } </code></pre> <p>But my real concern is that with my attempt to follow the company's naming standards and improve the code readability I might be introducing a bug in already tested code. Would you use the version posted in the the WMSAuth page?</p> <p>Note: It has to work with the .NET Framework 1.1</p>
[]
[ { "body": "<p>Well, the problem is that the example code provided effectively does a <code>% 256</code> on the input characters. So it's possible that your version and the example code yield two different values for the same input.</p>\n\n<p>However you said <em>I believe the code above might work for every possible input</em> - I take it then that <code>password</code> will never contain any characters where the wrap-around will play a role? If that's the case then your version should be equivalent.</p>\n\n<p>If you are paranoid then replace <code>Encoding.UTF8.GetBytes</code> in your code with the same loop as used in the example but leave your other refactorings intact.</p>\n\n<p>In fact I would refactor the <code>result</code> into:</p>\n\n<pre><code>string.Format(\"{0}?server_time={1}&amp;hash_value={2}&amp;validminutes={3}\", mediaUrl, dateTimeString, hashValue, validMinutes);\n</code></pre>\n\n<p>Which means you could also get rid of the <code>validMinutesString</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T11:03:47.890", "Id": "36406", "ParentId": "11977", "Score": "2" } } ]
{ "AcceptedAnswerId": "36406", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T19:17:52.623", "Id": "11977", "Score": "3", "Tags": [ "c#", "strings", "datetime", "cryptography" ], "Title": "WMSAuth implementation" }
11977
<p>I did this as an exercise just to practice/improve using generics.</p> <p>Independent of how useful this implementation of a Singleton is, how is my coding in terms of using generics and any other aspect of class design of code style?</p> <pre><code>void Main() { var a = Singleton&lt;MyClass&gt;.Value; var b = Singleton&lt;MyClass, MyClassFactory&gt;.Value; var c = Singleton&lt;MyClass&gt;.Value; var d = Singleton&lt;MyClass, MyClassFactory&gt;.Value; var e = Singleton&lt;MyOtherClass&gt;.Value; var f = Singleton&lt;MyOtherClass&gt;.Value; var g = Singleton&lt;MyOtherClass, MyOtherFactory&gt;.Value; var h = Singleton&lt;MyOtherClass, MyOtherFactory&gt;.Value; } class SingletonBase { protected static object Locker = new LockerObject(); } class Singleton&lt;T&gt; : SingletonBase where T : new() { static T StaticT; public static T Value { get { lock (Locker) { if(StaticT == null) { StaticT = Activator.CreateInstance&lt;Factory&lt;T&gt;&gt;().Create(); } else { Console.WriteLine ("Singleton&lt;T&gt;::Value" + typeof(T).Name + " is already created"); } } return StaticT; } } } class Singleton&lt;T, F&gt; : SingletonBase where T : new() where F : IFactory&lt;T&gt;, new() { static T StaticT; public static T Value { get { lock (Locker) { if(StaticT == null) { StaticT = new F().Create(); } else { Console.WriteLine ("Singleton&lt;T, F&gt;::Value" + typeof(T).Name + " is already created"); } } return StaticT; } } } class LockerObject { Guid myGUID; public LockerObject() { this.myGUID = Guid.NewGuid(); Console.WriteLine ("New LockerObject " + this.myGUID.ToString()); } } interface IFactory&lt;T&gt; { T Create(); } class Factory&lt;T&gt; : IFactory&lt;T&gt; where T : new() { public T Create() { Console.WriteLine ("Factory&lt;T&gt;::Create()"); return new T(); } } class MyClassFactory : IFactory&lt;MyClass&gt; { public MyClass Create() { Console.WriteLine ("MyClassFactory::Create()"); return new MyClass(); } } class MyClass { public MyClass() { Console.WriteLine ("MyClass created"); } } class MyOtherClass { public MyOtherClass() { Console.WriteLine ("MyOtherClass created"); } } class MyOtherFactory : IFactory&lt;MyOtherClass&gt; { public MyOtherClass Create() { Console.WriteLine ("MyOtherFactory::Create()"); return new MyOtherClass(); } } </code></pre> <p><strong>Output:</strong></p> <blockquote> <pre class="lang-none prettyprint-override"><code>New LockerObject 36aa2282-d745-43ca-84d2-998a78e39d51 Factory&lt;T&gt;::Create() MyClass created MyClassFactory::Create() MyClass created Singleton&lt;T&gt;::ValueMyClass is already created Singleton&lt;T, F&gt;::ValueMyClass is already created </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T07:47:49.373", "Id": "19225", "Score": "2", "body": "a little offtopic: those are *not* singletons. As long as class `T` is required to have a public parameterless constructor, anyone can create a new instance of it. Same problem with the version using `IFactory<T>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T15:34:35.770", "Id": "19244", "Score": "0", "body": "understood, good point. I was only designing it for code that makes the assumption that a DI container is able to control all object instantiation..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T04:45:53.577", "Id": "28075", "Score": "0", "body": "Does this design assure in multithreading case it creates only one object of this class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T20:33:52.417", "Id": "44131", "Score": "0", "body": "Have a read of http://csharpindepth.com/Articles/General/Singleton.aspx" } ]
[ { "body": "<p>About your locking strategy to create the singleton, I would use a double check to avoid too much locking:</p>\n\n<pre><code>if(x)\n{\n lock(Locker)\n if(x) //again once we got the lock\n DoStuff();\n} \nelse \n{\n FooBar();\n}\n</code></pre>\n\n<p>Like this, you will hopefully use the lock only once when you first call the instance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T04:56:50.693", "Id": "28076", "Score": "1", "body": "+1 for more details go through http://www.ibm.com/developerworks/java/library/j-dcl/index.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T14:47:46.997", "Id": "28228", "Score": "0", "body": "@PrasadSDeshpande I'm not sure your link is relevant. It shows that the double-locking behavior shouldn't be used with Java, but this question is about C#." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T09:17:00.130", "Id": "44087", "Score": "0", "body": "Double checked locking has visibility problems in Java. I guess @Zonko thought that the same could be true for C# too. http://stackoverflow.com/questions/394898/double-checked-locking-in-net" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T20:32:56.350", "Id": "44130", "Score": "1", "body": "I would stay away from this method as suggested by c# in Depth (Jon Skeet) - http://csharpindepth.com/Articles/General/Singleton.aspx" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T08:39:34.467", "Id": "11988", "ParentId": "11978", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T19:45:08.153", "Id": "11978", "Score": "4", "Tags": [ "c#", "generics", "singleton" ], "Title": "Singleton implementation using generics" }
11978
<p>I am trying to improve my skill in C, and this time by getting away from <code>strtok</code>. The following code splits the <code>input</code> string into a token_list, an array of strings.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define MAX_LINE_LEN 256 #define NULL_TERM '\0' /* A function that will print the content of the token_list */ int printcharlist(char **tok_list) { char **pptr = tok_list; while (*pptr) { printf ("++ %s\n", *pptr); pptr++; } return 0; } /* returns the string between 2 pointers (not forgetting to append NULL_TERM */ char *getStr(char *start, char *end) { int length=end-start; int i=0; char *result = (char *)malloc (sizeof (char) * (length+1)); while (i &lt; length) { result[i] = *start; start++; i++; } result[i] = NULL_TERM; return result; } int main (int argc, char ** argv) { char *input = "something;in;the;way;she;moves"; char reject = ';'; char *start = input; char *end = input; char *token_list[MAX_LINE_LEN] = {NULL}; int i=0; /* Is this predicate okay? I read that certain compiler might raise warnings here */ while (end=strchr(start, (int)reject)) { token_list[i]=getStr(start, end); i++; end++; start=end; } /* It feels awkward to add one more token after the while loop. Is it standard? Should/can I avoid this? */ token_list[i]=start; printcharlist(token_list); return EXIT_SUCCESS; } </code></pre> <p>I am interested in any kind of feedback I can get. But if I absolutely must ask questions it would be:</p> <ul> <li>Would something make you react badly if someone sent you this code in a patch/pull-request? If yes, what?</li> <li>Consider this code is going to production. What are the edge cases that I miss and how can I solve them?</li> </ul>
[]
[ { "body": "<p>I would consider changing the getStr() function a little, as follows:</p>\n\n<pre><code>char *getStr(char *start, char *end)\n{\n int length=end-start;\n if(length &lt;= 0) {\n /* Consider an error msg */\n return NULL;\n }\n\n char *result = (char *)malloc (sizeof (char) * (length+1));\n\n /* deliberately not using strcpy, since it checks for \\0 */\n memcpy(result, start, length);\n result[length] = NULL_TERM;\n\n return result;\n}\n</code></pre>\n\n<p>And a few minor aesthetic changes in main:</p>\n\n<pre><code>int main (int argc, char ** argv)\n{\n ...\n\n int i = 0;\n while (end=strchr(start, (int)reject)) {\n token_list[i++]=getStr(start, end++);\n start=end;\n }\n\n /* Nothing wrong assigning the last token here, as it avoids more\n * complex logic in the while loop and simplifies the code, just\n * add a comment, something like: Now for the last token...\n */\n token_list[i]=start;\n printcharlist(token_list);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>If you're worried about the while() loop syntax, you could consider a for loop instead, but the way you have it is clean.</p>\n\n<p>You may also consider a different implementation. Currently you are effectively duplicating the input string, which for relatively short strings, that shouldnt be problematic. But if the input strings become longer, you could implement an array of pointers to an intermediate struct defined as follows:</p>\n\n<pre><code>struct token {\n char *data;\n unsigned int length;\n};\n</code></pre>\n\n<p>Each data pointer would point to the beginning of a token, and the length would be the length of said token. This way you wont have to duplicate the input string, and you wouldnt have to modify the input string either.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T09:44:51.283", "Id": "19228", "Score": "0", "body": "Thank you for mentioning `memcpy`. On the other hand, your second piece of code seems a little odd. `token_list[0]` gets assigned the whole `input` string and the final token is never assigned to the `token_list` array..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T09:49:50.747", "Id": "19229", "Score": "0", "body": "@rahmu, Ok, I see your point. I think I originally mis-read your code. I was assuming the assignment after the while loop was to token_list[0], but now I see its actually to token_list[i]. I'll update the answer accordingly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T12:17:57.253", "Id": "19236", "Score": "0", "body": "Thanks! The `token` struct is pretty neat indeed (although for my practical use case, input will never be too long so I would mind duplication). Thank you also for confirming that the final assignement is not as awkward as it seemed to me :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T06:57:23.787", "Id": "19325", "Score": "0", "body": "@WilliamMorris, you're absolutely right! Oversight on my part :) I updated the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T00:28:47.147", "Id": "70539", "Score": "0", "body": "One thing wrong with the code is that you don't free the memory which you allocated in `getStr`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T08:22:24.740", "Id": "11987", "ParentId": "11981", "Score": "5" } }, { "body": "<h3>Module Design</h3>\n\n<p>The trouble with your design is that you need to know how it works before you can use it. This is not true for strtok (OK to a slight extent it is true for strtok).</p>\n\n<p>When designing a software system the user should not need to know how it operates, but rather the interface to the system. Doing it this way has two distict advantages.</p>\n\n<ol>\n<li>User does not need to learn how it works thus making it easier for them to use.<br>\nThis means it is easier to distribute in binary form if you want. </li>\n<li>User is less likely to break it by making assumptions that do not hold (as they have not read the code to understand it).</li>\n<li>You can change how it works without affecting the user code.</li>\n</ol>\n\n<p>Thus I would have provided this functionality with a couple of functions and some opaque data types that the user never needs to know or understand.</p>\n\n<h3>String Copying</h3>\n\n<pre><code>while (i &lt; length) {\nresult[i] = *start;\nstart++;\ni++;\n}\n</code></pre>\n\n<p>This is done in the std lib look up strncpy(). </p>\n\n<p>Also this can be written much more succinctly as:</p>\n\n<pre><code>for(loop = 0; loop &lt; length; ++loop)\n{\n result[loop] = start[loop];\n}\n</code></pre>\n\n<h3>Code Review</h3>\n\n<p>I don't think you need to define this.</p>\n\n<pre><code>#define NULL_TERM '\\0'\n</code></pre>\n\n<p>Putting the literal <code>'\\0'</code> into your code is very readable and people know what it means. The macro <code>NULL_TERM</code> may seem self explanatory but I would go look it up.</p>\n\n<p>The function <code>printcharlist</code> assumes the list is NULL terminated.</p>\n\n<pre><code>int printcharlist(char **tok_list)\n</code></pre>\n\n<p>This is asking for people to do it incorrectly (and forget the NULL terminator). You even mention yourself that this is akward:</p>\n\n<pre><code>/* It feels awkward to add one more token after the while loop. Is it standard? Should/can I avoid this? */\n</code></pre>\n\n<p>I would change the interface to pass the number of values in the list:</p>\n\n<pre><code>int printcharlist(char **tok_list, size_t count)\n</code></pre>\n\n<p>Then you make people explicitly fill in the length and they can not accidentally pass you an array that will cause problems.</p>\n\n<h3>Alternative design</h3>\n\n<p>One advantage of strtok() of your function is that it does not parse the whole string. It only fetches the next token. Thus in a situation where you only need the first couple of tokens it is much more efficient.</p>\n\n<p>I would change your algorithm so that it behaves in a similar manor. Retrieve one string (and store it in your data structure). Next call retrieves the next string etc (this would be a lot easier to change it you had made a modular design).</p>\n\n<h3>Questions</h3>\n\n<blockquote>\n <p>Would make you react badly if someone sent you this code in a patch/pull-request? If yes, what?</p>\n</blockquote>\n\n<p>No. But I would want to see the test cases the validate it.</p>\n\n<blockquote>\n <p>Consider this code is going to production. What are the edge cases that I miss and how can I solve them?</p>\n</blockquote>\n\n<p>I would set up some unit tests.</p>\n\n<ul>\n<li>\"\"</li>\n<li>\";\"</li>\n<li>\";;\"</li>\n<li>\";;;\"</li>\n<li>\"Some Text;\"</li>\n<li>\"Some Text;;\"</li>\n<li>\";;SomeText;;\"</li>\n<li>\"Some\\nText\"</li>\n<li>\"Some\\nText;\"</li>\n<li>\"Some\\nText;;\"</li>\n<li>\"Some\\n;Text\"</li>\n<li>\"Some\\n;;Text\"</li>\n<li>\"Some;\\n;Text\"</li>\n<li>\"Some;\\n;;Text\"</li>\n<li>\"Some;;\\n;Text\"</li>\n<li>\"Some;;\\n;;Text\"</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T23:59:00.130", "Id": "19316", "Score": "1", "body": "strncpy will check for \\0 as it copies and is inefficient. memcpy is best here, as we know the length." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T16:31:16.313", "Id": "12003", "ParentId": "11981", "Score": "7" } }, { "body": "<p>General comment:</p>\n\n<ul>\n<li>leave a space around operators ('-', '=', etc)</li>\n</ul>\n\n<p>printcharlist:</p>\n\n<ul>\n<li>pptr seems redundant - just use tok_list</li>\n<li>return void (ie nothing)</li>\n</ul>\n\n<p>getStr:</p>\n\n<ul>\n<li>inconsistent function naming (camel case, cf. <code>printcharlist</code>)</li>\n<li><code>start</code> and <code>end</code> should be const</li>\n<li>don't cast the return from malloc</li>\n<li>sizeof(char) is 1 by definition, so omit</li>\n<li>replace while loop with memset</li>\n<li>use '\\0' directly</li>\n</ul>\n\n<p>main</p>\n\n<ul>\n<li>the guts of this should be a function separate from main().</li>\n<li><code>input</code> should be const</li>\n<li><code>reject</code> should be const (and perhaps 'int')</li>\n<li>while() loop needs extra brackets as you hinted</li>\n<li>instead of <code>end++; start = end;</code> I would use just <code>start = end + 1;</code> as the value of <code>end</code> is reassigned next loop.</li>\n<li>you do not check for the list filling up</li>\n<li>your trailing assignment of <code>token_list[i]=start;</code> probably worries you because it leaves token_list holding one statically allocated string and the reset dynamic; use strdup() to allocate the last string. You could avoid this trailing assignment by rearraging the logic of the function, but why bother? It is fine as it is.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T03:53:22.923", "Id": "20235", "Score": "0", "body": "The standard only guarantees that 8 bits fit into a char. There are architectures where char is bigger than 8 bits. If you want something that is exactly 8 bits, use stdint's `uint8_t`. On an architecture where it's unavailable, it simply won't compile." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T00:59:01.810", "Id": "12049", "ParentId": "11981", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T01:03:04.007", "Id": "11981", "Score": "7", "Tags": [ "c", "strings", "reinventing-the-wheel" ], "Title": "Splitting a string into tokens in C" }
11981
<p>Please offer some advice for this code. It all works, but I know that its messy and I don't think the Exception catching is doing what I want it to. Thanks in advance for any and all advice...</p> <pre><code>def main(): # loop over this forever while True: print '--- Getting next job for Device: %s' % device['Name'] # get a job from the db try: job = db.JobQ.find_one({'DeviceName':device['Name'],'Status':u'ToDo'}) except Exception as e: print '!!! Error getting job for Device: %s' % device['Name'] if job: # if there's a job, get all the other jobs for the same file try: job_list = [ j for j in db.JobQ.find( {'Filename':job['Filename'],'Status':u'Todo'} ).sort('Created',ASCENDING) ] except Exception as e: print '!!! Error getting job list for Filename: %s' % job['Filename'] for job in job_list: # mark the job 'InProgress' job = db.JobQ.find_and_modify( {'_id':ObjectId(job['_id'])}, {'$set':{ 'Status':u'InProgress','Started':datetime.now() }},new=True ) print '--- Performing %s on %s' % (job['Type'], job['Filename']) # try to do the job.. each job raises its own exceptions try: perform_job(job) job['Status'] = u'Done' job['Finished'] = datetime.now() db.JobQ.save(job,safe=True) except Exception as e: # if any job fails, ditch the rest of the jobs and move on print '!!! Error performing job: %s' % e print 'Subsequent jobs for this filename will not run: %s'\ % job['Filename'] for job in job_list: job['Finished'] = datetime.now() job['Status'] = u'Failed' db.JobQ.save(job,safe=True) else: print '--- No more jobs for Device: %s' % device['Name'] sleep(device['CycleTime']) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T08:34:59.470", "Id": "19226", "Score": "0", "body": "what do you want the exception-catching to do then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T13:37:27.730", "Id": "19241", "Score": "0", "body": "see half way down `try: perform_job(job)`.. this is the section I'm not sure about. If `perform_job(job)` raises an Exception, the following 3 lines will not run, correct? Is this a normal way to do things?" } ]
[ { "body": "<p>Oh I see a problem. in </p>\n\n<pre><code> perform_job(job)\n job['Status'] = u'Done'\n job['Finished'] = datetime.now()\n db.JobQ.save(job,safe=True)\n</code></pre>\n\n<p>if anything goes wrong, an exception is caught by your <code>except</code> block. in this block, you set the status of all jobs to be <code>Failed</code> in another <code>for</code> loop. Why? It suffices to set the problematic job to be failed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T00:03:01.420", "Id": "19262", "Score": "0", "body": "My aim with setting all the other jobs `Failed` if any of them fail is in a case where the first job is a copy and the second job is a delete. If the copy fails, I don't want the delete to run. Does that make sense?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T13:52:11.403", "Id": "12000", "ParentId": "11986", "Score": "0" } }, { "body": "<p>A couple things:</p>\n\n<ul>\n<li><p>Instead of <code>if job:</code>, try <code>if not job: ... continue</code> . This will allow the entire (large) content of that if-block to be outdented a level, making it a little more readable.</p></li>\n<li><p>Instead of <code>job_list = [ j for j in ... ]</code>; use <code>job_list = list( ... )</code>.</p></li>\n</ul>\n\n<p>Also, the logic in your failure code looks a bit suspect - you set subsequent jobs as 'failed' but nothing keeps them from being attempted again by the enclosing <code>for</code> loop. I <em>think</em> you basically want a <code>break</code> at the end of the <code>except</code> block to exit the loop there, though that leaves the <code>for</code> loop still setting some potentially passed jobs as failed (consider the case when the first job passes but the second fails - the loop will set them all as failed). So you might instead add a <code>fail_the_rest = False</code> flag just before the <code>for job in joblist</code> loop and then as the first line of the loop do <code>if fail_the_rest: &lt;set failed&gt; continue</code> and then change the <code>except</code> block to just set failure on that one job and then set <code>fail_the_rest = True</code>. But that's all speculative due to a lack of understanding about how your job submission and pass/fails work.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T00:21:17.577", "Id": "19263", "Score": "0", "body": "Thanks for the first 2 hints. My code is looking better already! And you're right. I should only be marking the job that fails and subsequent jobs as Failed whereas I'm marking them all as failed atm. I learned a lot from you response, thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T00:55:21.387", "Id": "19267", "Score": "0", "body": "In thinking about it a bit more, I realised that in a fail situation, I can check to see if each job's status is not `Done` and then set it `Failed`. Thanks for setting me on the right track!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T15:45:02.710", "Id": "12001", "ParentId": "11986", "Score": "2" } }, { "body": "<p>I think your last exception-catch needs a <code>break</code> statement in it - it sets all the jobs in <code>job_list</code> to <code>'Failed'</code>, but then the surrounding <code>for job in job_list</code> loop will still keep repeating for all the jobs, won't it? I don't know whether having the jobs maked as 'Failed' will prevent them being run, but either way something is wrong - either the 'Failed' jobs will be run, in which case there's no point marking them 'Failed', or they will not, in which case there's no point in trying to run them and you should break out of the loop. </p>\n\n<p>Also, are you sure you want the jobs that have already been run to be marked 'Failed', even if they worked fine?</p>\n\n<p>Another question - why is it that when you're setting marking a job as 'InProgress', you use <code>db.JobQ.find_and_modify</code>, but when you're marking it as 'Failed' or 'Done', you just use <code>job['Status'] = u'Done'</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T00:25:55.543", "Id": "19264", "Score": "0", "body": "Thanks for your response. I think you're onto something (I'm just trying to get my head around it). With regards to your final question, in the first instance, I want to get and set the job and I find the job by using the only thing I have, `DeviceName`, but in the second instance, I only need to set it and because I have the job as it was in the db, I also have the job's `_id`. Pymongo allows a simple `save` when you have the object's `_id` which performs an upsert on any changed data. Hope that makes sense and thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T00:37:38.190", "Id": "19265", "Score": "0", "body": "@MFB Oh, okay, that makes sense. I've never used Pymongo, so I wasn't sure. Good luck with the rest of your code!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T15:51:37.440", "Id": "12002", "ParentId": "11986", "Score": "1" } } ]
{ "AcceptedAnswerId": "12001", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T07:44:06.783", "Id": "11986", "Score": "1", "Tags": [ "python", "exception-handling" ], "Title": "I think I'm not using Try Except properly in this Python code" }
11986
<p>I use jQuery and <code>underscore.js</code>, I have <code>title1-2</code> and I would like to have the action corresponding.</p> <pre><code>this.items = { menuItems: [ { title: 'title1', data: [ { title: 'title1-1', action: 'action1-1' }, { title: 'title1-2', action: 'action1-2' } ] }, { title: 'title2', data: [ { title: 'title2-1', action: 'action2-1' }, { title: 'title2-2', action: 'action2-2' } ] } ] }; </code></pre> <p>Currently, I have the following code to do this:</p> <pre><code>var item = _.find(_.flatten(_.pluck(this.items.menuItems, 'data')), function (item) { return item.title === 'title1-2'; }); console.log(item.action); </code></pre> <p>Is there a better way to find it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T11:22:51.523", "Id": "19232", "Score": "0", "body": "So I assume that you want to find the object that contains title1-2?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T12:37:24.017", "Id": "19237", "Score": "0", "body": "exactly, thx :)" } ]
[ { "body": "<p>Actually the only improvement I think you can make is that you use the chaining sugar, looks a lot better:</p>\n\n<pre><code>var item = _.chain(items.menuItems)\n .pluck('data')\n .flatten()\n .find(function(a){\n return a.title === 'title1-2'\n })\n .value()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T11:38:16.850", "Id": "11993", "ParentId": "11992", "Score": "1" } } ]
{ "AcceptedAnswerId": "11993", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T11:13:42.777", "Id": "11992", "Score": "2", "Tags": [ "javascript", "jquery", "performance", "array" ], "Title": "Find the object that contains title1-2" }
11992
<p>Consider the scenario below. It covers multiple methods of my unit under test.</p> <pre><code>public class OriginalSample { public bool Foo(ISomeEntity entity) { return entity.IsThatSo ? entity.IsThatSo : Bar(entity); } public bool Bar(ISomeEntity entity) { return entity.IsThatAsWell; } } [TestClass] public class OriginalSampleTest { [TestMethod] public void Foo_EntityWithSo_ReturnsTrue { // Arrange Mock&lt;ISomeEntity&gt; someEntityMock = new Mock&lt;ISomeEntity&gt;(); mock.SetupGet(m =&gt; m.IsThatSo).Returns( false ); mock.SetupGet(m =&gt; m.IsThatAsWell).Returns( true ); // Act private bool result = _OriginalSample.Foo( someEntityMock.Object ); // Assert Assert.IsTrue(result); } } </code></pre> <p>However, in my production code there is a lot that I need to Mock away that is then used in more method calls. I need to find a way to test the <code>Foo</code> method without hitting the <code>Bar</code> method.</p> <p>I came up with the scenario as below. However the disadvantage is that i need a interface and pass the instance in each method. I do not like this design. </p> <p>Any feedback?</p> <pre><code>public interface INewSample { bool Foo(ISomeEntity entity, INewSample sample); bool Bar(ISomeEntity entity); } public class NewSample : INewSample { public bool Foo(ISomeEntity entity, INewSample sample) { return entity.IsThatSo ? entity.IsThatSo : sample.Bar(entity); } public bool Bar(ISomeEntity entity) { return entity.IsThatAsWell; } } [TestClass] public class NewSampleTest { [TestMethod] public void Foo_EntityWithSo_ReturnsTrue { // Arrange Mock&lt;ISomeEntity&gt; someEntityMock = new Mock&lt;ISomeEntity&gt;(); mock.SetupGet(m =&gt; m.IsThatSo).Returns( false ); Mock&lt;INewSample&gt; sampleMock = new Mock&lt;INewSample&gt;(); sampleMock.Setup(m =&gt; m.Bar).Returns(false).Verify(); // Act private bool result = _OriginalSample.Foo( someEntityMock.Object, sampleMock.Object ); // Assert (that the logic tried to use the 'bar' method sampleMock.Verify(); } } </code></pre>
[]
[ { "body": "<p><strong>You can't.</strong></p>\n\n<p>You need to ask yourself <em>why</em> it is you want to prevent executing Bar during testing. If it is because you are worried about over-covering Bar during testing, stop worrying. If it is because your real Bar implementation is long-running, then you probably need to inject another dependency into your class, or re-factor some code into a separate helper class which can then be injected.</p>\n\n<p><strong>As long as your Foo implementation needs to call Bar, your unit tests for Foo ultimately need to as well.</strong> As long as Foo ultimately calls Bar, you cannot fully test Foo without executing Bar. You shouldn't rely on it calling Bar, but you cannot prevent it from calling Bar in your tests without intentionally crippling your test coverage.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T21:29:06.373", "Id": "19345", "Score": "0", "body": "+1 If `Bar()` takes too long to run, it's not even a unit test we're talking about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T06:44:09.780", "Id": "19407", "Score": "0", "body": "@DanLyons. In the actual production code, the `Foo()` method has some business logic, and then calls about 4 other `Bar()` methods. I have written tests for those other `Bar()` methods. I do not want to test whether the Bar methods are called. In that case, I think the best solution is to split the `Foo` method into a `FooLogic` that will be tested and a helper method that will call both the `FooLogic` and the other `Bar` methods. This method will contain no unit test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T18:13:40.867", "Id": "19428", "Score": "0", "body": "Well, as I stated above, your test for the code above shouldn't care whether you call other methods or not. Just test the output against expected inputs/outputs and ignore whether or not it calls the other methods. Once you do that, you can refactor out your logic into helpers to your heart's content, though I wouldn't do so just to prevent your unit tests from executing shared code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T19:09:18.227", "Id": "12074", "ParentId": "11995", "Score": "4" } }, { "body": "<p>How about make Bar virtual, and mock it.\nUsing _sampleMock.Verify(c => c.Bar(entity), Times.Once()); to assert.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-11T21:51:38.837", "Id": "184890", "ParentId": "11995", "Score": "0" } } ]
{ "AcceptedAnswerId": "12074", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T12:40:38.650", "Id": "11995", "Score": "6", "Tags": [ "c#", "unit-testing", "moq" ], "Title": "Mocking the class under test with private method calls" }
11995
<p>Question originally posted on Stack Overflow <a href="https://stackoverflow.com/questions/10720002/most-elegant-way-to-round-a-date-to-a-dynamic-unit-of-time-using-only-jdk-6">here</a>.</p> <p>I'm trying to do an elegant round method that only use the JDK methods and leverage the <code>TimeUnit</code> class of that JDK.</p> <pre><code>/** * Get the date rounded to the given unit * @param date * @param unit * @return the rounded value */ public static Date round(Date date,TimeUnit unit) { long dateInMillies = date.getTime(); long tzOffset = TimeZone.getDefault().getOffset(dateInMillies); long dateInMilliesWithoutOffset = dateInMillies + tzOffset; long dateInUnit = unit.convert(dateInMilliesWithoutOffset,TimeUnit.MILLISECONDS); long dateInMilliesRoundedWithoutOffset = unit.toMillis(dateInUnit); long dateInMilliesRoundedWithOffset = dateInMilliesRoundedWithoutOffset - tzOffset; return new Date(dateInMilliesRoundedWithOffset); } </code></pre> <p>And my unit test is:</p> <pre><code>@Test public void testRoundDate() { Date currentDayDate = new Date(); Date currentDayBegin = DateUtils.getDayBegin(currentDayDate); // returns 00h00:00 and 000 milliseconds Date currentDayEnd = DateUtils.getDayEnd(currentDayDate,TimeUnit.MILLISECONDS); // returns 23h59:59 and 999 milliseconds // final Calendar initialCalBegin = Calendar.getInstance(); initialCalBegin.setTime(currentDayBegin); final Calendar initialCalEnd = Calendar.getInstance(); initialCalEnd.setTime(currentDayEnd); // Calendar testedCalendar = Calendar.getInstance(); // testedCalendar.setTime( DateUtils.round(currentDayBegin, TimeUnit.DAYS) ); Assert.assertEquals( testedCalendar.get(Calendar.DAY_OF_YEAR), initialCalBegin.get(Calendar.DAY_OF_YEAR) ); Assert.assertEquals( testedCalendar.get(Calendar.HOUR_OF_DAY), 0 ); Assert.assertEquals( testedCalendar.get(Calendar.MINUTE), 0 ); Assert.assertEquals( testedCalendar.get(Calendar.SECOND), 0 ); Assert.assertEquals( testedCalendar.get(Calendar.MILLISECOND), 0 ); testedCalendar.setTime( DateUtils.round(currentDayEnd, TimeUnit.DAYS) ); Assert.assertEquals( testedCalendar.get(Calendar.DAY_OF_YEAR), initialCalEnd.get(Calendar.DAY_OF_YEAR) ); Assert.assertEquals( testedCalendar.get(Calendar.HOUR_OF_DAY), 0 ); Assert.assertEquals( testedCalendar.get(Calendar.MINUTE), 0 ); Assert.assertEquals( testedCalendar.get(Calendar.SECOND), 0 ); Assert.assertEquals( testedCalendar.get(Calendar.MILLISECOND), 0 ); // testedCalendar.setTime( DateUtils.round(currentDayBegin, TimeUnit.HOURS) ); Assert.assertEquals( testedCalendar.get(Calendar.DAY_OF_YEAR), initialCalBegin.get(Calendar.DAY_OF_YEAR) ); Assert.assertEquals( testedCalendar.get(Calendar.HOUR_OF_DAY), initialCalBegin.get(Calendar.HOUR_OF_DAY) ); Assert.assertEquals( testedCalendar.get(Calendar.MINUTE), 0 ); Assert.assertEquals( testedCalendar.get(Calendar.SECOND), 0 ); Assert.assertEquals( testedCalendar.get(Calendar.MILLISECOND), 0 ); testedCalendar.setTime( DateUtils.round(currentDayEnd, TimeUnit.HOURS) ); Assert.assertEquals( testedCalendar.get(Calendar.DAY_OF_YEAR), initialCalEnd.get(Calendar.DAY_OF_YEAR) ); Assert.assertEquals( testedCalendar.get(Calendar.HOUR_OF_DAY), initialCalEnd.get(Calendar.HOUR_OF_DAY) ); Assert.assertEquals( testedCalendar.get(Calendar.MINUTE), 0 ); Assert.assertEquals( testedCalendar.get(Calendar.SECOND), 0 ); Assert.assertEquals( testedCalendar.get(Calendar.MILLISECOND), 0 ); // testedCalendar.setTime( DateUtils.round(currentDayBegin, TimeUnit.MINUTES) ); Assert.assertEquals( testedCalendar.get(Calendar.DAY_OF_YEAR), initialCalBegin.get(Calendar.DAY_OF_YEAR) ); Assert.assertEquals( testedCalendar.get(Calendar.HOUR_OF_DAY), initialCalBegin.get(Calendar.HOUR_OF_DAY) ); Assert.assertEquals( testedCalendar.get(Calendar.MINUTE), initialCalBegin.get(Calendar.MINUTE) ); Assert.assertEquals( testedCalendar.get(Calendar.SECOND), 0 ); Assert.assertEquals( testedCalendar.get(Calendar.MILLISECOND), 0 ); testedCalendar.setTime( DateUtils.round(currentDayEnd, TimeUnit.MINUTES) ); Assert.assertEquals( testedCalendar.get(Calendar.DAY_OF_YEAR), initialCalEnd.get(Calendar.DAY_OF_YEAR) ); Assert.assertEquals( testedCalendar.get(Calendar.HOUR_OF_DAY), initialCalEnd.get(Calendar.HOUR_OF_DAY) ); Assert.assertEquals( testedCalendar.get(Calendar.MINUTE), initialCalEnd.get(Calendar.MINUTE) ); Assert.assertEquals( testedCalendar.get(Calendar.SECOND), 0 ); Assert.assertEquals( testedCalendar.get(Calendar.MILLISECOND), 0 ); // testedCalendar.setTime( DateUtils.round(currentDayBegin, TimeUnit.SECONDS) ); Assert.assertEquals( testedCalendar.get(Calendar.DAY_OF_YEAR), initialCalBegin.get(Calendar.DAY_OF_YEAR) ); Assert.assertEquals( testedCalendar.get(Calendar.HOUR_OF_DAY), initialCalBegin.get(Calendar.HOUR_OF_DAY) ); Assert.assertEquals( testedCalendar.get(Calendar.MINUTE), initialCalBegin.get(Calendar.MINUTE) ); Assert.assertEquals( testedCalendar.get(Calendar.SECOND), initialCalBegin.get(Calendar.SECOND) ); Assert.assertEquals( testedCalendar.get(Calendar.MILLISECOND), 0 ); testedCalendar.setTime( DateUtils.round(currentDayEnd, TimeUnit.SECONDS) ); Assert.assertEquals( testedCalendar.get(Calendar.DAY_OF_YEAR), initialCalEnd.get(Calendar.DAY_OF_YEAR) ); Assert.assertEquals( testedCalendar.get(Calendar.HOUR_OF_DAY), initialCalEnd.get(Calendar.HOUR_OF_DAY) ); Assert.assertEquals( testedCalendar.get(Calendar.MINUTE), initialCalEnd.get(Calendar.MINUTE) ); Assert.assertEquals( testedCalendar.get(Calendar.SECOND), initialCalEnd.get(Calendar.SECOND) ); Assert.assertEquals( testedCalendar.get(Calendar.MILLISECOND), 0 ); // testedCalendar.setTime( DateUtils.round(currentDayBegin, TimeUnit.MILLISECONDS) ); Assert.assertEquals( testedCalendar.get(Calendar.DAY_OF_YEAR), initialCalBegin.get(Calendar.DAY_OF_YEAR) ); Assert.assertEquals( testedCalendar.get(Calendar.HOUR_OF_DAY), initialCalBegin.get(Calendar.HOUR_OF_DAY) ); Assert.assertEquals( testedCalendar.get(Calendar.MINUTE), initialCalBegin.get(Calendar.MINUTE) ); Assert.assertEquals( testedCalendar.get(Calendar.SECOND), initialCalBegin.get(Calendar.SECOND) ); Assert.assertEquals( testedCalendar.get(Calendar.MILLISECOND), initialCalBegin.get(Calendar.MILLISECOND) ); testedCalendar.setTime( DateUtils.round(currentDayEnd, TimeUnit.MILLISECONDS) ); Assert.assertEquals( testedCalendar.get(Calendar.DAY_OF_YEAR), initialCalEnd.get(Calendar.DAY_OF_YEAR) ); Assert.assertEquals( testedCalendar.get(Calendar.HOUR_OF_DAY), initialCalEnd.get(Calendar.HOUR_OF_DAY) ); Assert.assertEquals( testedCalendar.get(Calendar.MINUTE), initialCalEnd.get(Calendar.MINUTE) ); Assert.assertEquals( testedCalendar.get(Calendar.SECOND), initialCalEnd.get(Calendar.SECOND) ); Assert.assertEquals( testedCalendar.get(Calendar.MILLISECOND), initialCalEnd.get(Calendar.MILLISECOND) ); //////////////////////////////////////////////////////////////////////////////////////////////////////////////// // The TimeUnits under the millisecond precision should not procude any change to the date Assert.assertEquals(DateUtils.round(currentDayBegin, TimeUnit.MICROSECONDS) , currentDayBegin); Assert.assertEquals(DateUtils.round(currentDayEnd, TimeUnit.MICROSECONDS) , currentDayEnd); Assert.assertEquals(DateUtils.round(currentDayDate, TimeUnit.MICROSECONDS) , currentDayDate); // Assert.assertEquals(DateUtils.round(currentDayBegin, TimeUnit.NANOSECONDS) , currentDayBegin); Assert.assertEquals(DateUtils.round(currentDayEnd, TimeUnit.NANOSECONDS) , currentDayEnd); Assert.assertEquals(DateUtils.round(currentDayDate, TimeUnit.NANOSECONDS) , currentDayDate); } </code></pre> <p>It seems what I've done works fine and is quite elegant. However, I'm not used to using time zones, and I wonder if this code works fine on very specific cases. For example, do you see something that could happen a given day, for a country that has an offset change in its timezone? Please tell me if you think something is wrong in my code.</p> <p>Can I safely create a new method that takes a <code>TimeZone</code> parameter and can thus round a date to a given unit on a given timezone?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T13:48:06.847", "Id": "19295", "Score": "1", "body": "Any special reason this has to done with the JDK only? The [Joda Time](http://joda-time.sourceforge.net/) library has rounding features and it's considered to be very reliable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T14:11:47.537", "Id": "19299", "Score": "0", "body": "I know.i'm not looking for an alternative solution but comments on my code. We have an existing code using TimeUnit and TimeZone and it would be a little pain to map all these stuff to joda." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T14:22:20.530", "Id": "19301", "Score": "0", "body": "I thought so, just wanted to mention it." } ]
[ { "body": "<p>One problem you might run into is that some timezone offsets aren't integral hours. For instance, the India timezone offset is UTC +5:30. It appears that your code will probably handle this case correctly, but you probably want to add a couple unit tests to verify this.</p>\n\n<p>You might also run into some problems with the Brazil time zone, since its transition between Daylight Savings Time and Standard Time happens at midnight (instead of at 2am like in most places). I've had problems trying to get the Date class to work correctly in this situation in the past. Again, I see no specific problems, but some unit tests to verify would probably be in order.</p>\n\n<p>I would also suggest steering clear of the built-in Date/Calendar implementation, as there are some bugs when dealing with time zones. In my project I eventually had to use Joda under the covers and convert to/from Java Date at the API boundary. You might eventually decide that's the best solution for you, too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T23:10:05.730", "Id": "39698", "ParentId": "11997", "Score": "2" } }, { "body": "<p>Just a few random notes:</p>\n\n<ol>\n<li><p>Comments like this are unnecessary:</p>\n\n<pre><code> * @param date\n * @param unit\n</code></pre>\n\n<p>It says nothing more than the code already does, it's rather noise. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>I'd split the unit test to smaller test methods. Too many assert in one test is a bad smell. It's <a href=\"http://xunitpatterns.com/Assertion%20Roulette.html\" rel=\"nofollow\">Assertion Roulette</a> and you lost <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow\">Defect Localization</a>. If the first <code>assertEquals</code> throws an exception you don't know anything about the results of the other assert calls which could be important because they could help debugging and defect localization.</p></li>\n<li><p>I'd consider a static import and use simply <code>assertEquals</code> instead of <code>Assert.assertEquals</code>.</p>\n\n<pre><code>import static org.junit.Assert.*;\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T23:22:42.520", "Id": "40064", "ParentId": "11997", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T12:57:07.343", "Id": "11997", "Score": "4", "Tags": [ "java", "unit-testing", "datetime", "reinventing-the-wheel" ], "Title": "Rounding a date to a dynamic unit of time, using only JDK 6" }
11997
<p>I am using this code for receiving log messages from my clients. I receive more than 1000 connections per minute and I want to increase my log handling, which I have done with java threading.</p> <p>What happens if it receive multiple client connections? Is this thread safe?</p> <pre><code>public class CentralizedLogging implements Runnable { /** * Field logDir - Where the plugin logs can be stored . */ public static String logDir; /** * Field server - Server Socket . */ ServerSocket server = null; /** * Field LOGGER. */ public static final Logger LOGGER = Logger.getLogger(CentralizedLogging.class.getName()); /** * @param port - Port which the server is binds . * @param logDir String */ public CentralizedLogging(String logDir, int port) { try { this.logDir = logDir; server = new ServerSocket(port); } catch (IOException e) { LOGGER.log(Level.SEVERE, "It may be due to given port already binds with another process , reason {0}", new Object[]{e}); } } /** * Extension point for central log server . To start receiving connections from remote end . */ public void run() { while (true) { try { new Thread(new LogWriter(server.accept())).start(); } catch (Exception e) { LogWriter.log("Interrupted exception " + e.getMessage()); } } } /** * args[0] - logging location . args[1] - which port the server can start. It must be a integer. * * @param args */ public static void main(String[] args) { try { CentralizedLogging logServer = new CentralizedLogging(args[0], Integer.parseInt(args[1])); new Thread(logServer).start(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Unable to start log server from this location : {0} , port : {1} , This may be due to given port is not a number or this port is not free exception trace {2}", new Object[]{args[0], args[1], e}); } } } /** * Used for writing client packets into logs Dir . */ class LogWriter implements Runnable { /** * Field client - Socket Client . */ Socket client; /** * Constructor for LogWriter. * * @param client Socket * @throws IOException */ public LogWriter(Socket client) { this.client = client; } public void run() { write(); try { this.client.close(); } catch (IOException io) { System.out.println("Error while closing connection , reason " + io); } } /** * Method write. */ public void write() { try { String date = new SimpleDateFormat("yyyy_MM_dd").format(new Date()); File file = new File(CentralizedLogging.logDir + client.getInetAddress().getHostName() + "_" + date + ".log"); write(client.getInputStream(), file); } catch (Exception e) { log("Error in writing logs :: Host Name " + client.getInetAddress().getHostName() + " , Occured Time " + System.currentTimeMillis() + ", Reason " + e.getMessage() + "\n\n"); } } /** * Method write. * * @param in InputStream * @param file File * @throws Exception */ public synchronized static void write(InputStream in, File file) throws Exception { RandomAccessFile writer = new RandomAccessFile(file, "rw"); writer.seek(file.length()); //append the file content to the existing file or creates a new one . writer.write(read(in)); writer.close(); } /** * This method is used for monitoring errors that will be occured on writing plugin logs . * * @param msg */ public static void log(String msg) { File file = new File(CentralizedLogging.logDir + "plugin_error_" + new SimpleDateFormat("yyyy_MM_dd"). format(new Date()) + ".log"); try { write(new ByteArrayInputStream(msg.getBytes()), file); } catch (Exception e) { } } /** * Method read. * * @param in InputStream * @return byte[] * @throws IOException */ public static byte[] read(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); int read = -1; byte[] buffer = new byte[1024]; while ((read = in.read(buffer)) &gt; -1) { out.write(buffer, 0, read); } return out.toByteArray(); } /** * Method close. * * @param stream Object */ public static void close(Object stream) { try { if (stream instanceof Writer) { ((Writer) stream).close(); } else if (stream instanceof Reader) { ((Reader) stream).close(); } } catch (Exception e) { } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T14:33:35.303", "Id": "19340", "Score": "0", "body": "Does this actually log anything? All you seem to be doing is creating a CentralizedLogging instance but then never running it as a thread. It looks like you have the same problem again with LogWriter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T07:55:11.957", "Id": "19362", "Score": "0", "body": "@pgraham\n\nThank you so much for indicating error in code . Sorry , I am missed to start the runnable instance in \nmy code . I changed my code ." } ]
[ { "body": "<p>From what i see, it looks like you got the threads started correctly. You said in your question that you are making 1000 connections per minute or something to that sort, which is 1000 threads every minute. If you want to make your program more memory efficient, you might want to set the threads to null when you're done using them.</p>\n\n<p>When i program, i defiantly try to stay away from calling threads on the fly, especially if I'm programming a device that has limited memory resources. Here is some code i came up with, that is similar to what i use:</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n\npublic class GameDev1 \n{\n public GameDev1()\n {\n handlers = new ArrayList&lt;ConnectionHandler&gt;();\n try\n {\n server = new ServerSocket(8080); // use whatever port you need\n }catch(Exception e){e.printStackTrace();}\n }\n\n public void run()\n {\n //This is the run() method for your server\n int connections = 0;\n\n while(true)\n {\n try {\n handlers.add(new ConnectionHandler(server.accept())); // adds the new ConnectionHandler to the list\n connections++;\n\n // this will clear unused memory every time 1000 people connect to your sever, you can set this to more\n // or less, whatever you want\n if(connections == 1000)\n {\n cleanHandlers();\n connections = 0;\n }\n }catch(Exception e){e.printStackTrace();}\n }\n }\n\n public void cleanHandlers()\n {\n Iterator&lt;ConnectionHandler&gt; it = handlers.iterator();// this is used to sort through the list\n\n while(it.hasNext())\n {\n ConnectionHandler next = it.next();\n if(next.finished)\n {\n // when a ConnectionsHandler is done, it sets finished to true, which means clean should be called\n next.clean();\n it.remove();\n }\n\n next = null;\n }\n }\n\n public ArrayList&lt;ConnectionHandler&gt; handlers; // this is a list of all of the ConnectionHandlers that exist in memory.\n public ServerSocket server; // your server socket.\n\n public class ConnectionHandler implements Runnable\n {\n public ConnectionHandler(Socket socket)\n {\n this.socket = socket;\n finished = false;\n\n thread = new Thread(this);\n thread.start();\n }\n\n public void run()\n {\n // Do your run method here, this is where you collect the log information from the client\n //...\n\n finished = true;\n }\n\n public void clean()\n {\n // this cleans up anything that the class is no longer using\n\n if(finished)\n {\n try\n {\n socket.close();\n }catch(Exception e){e.printStackTrace();}\n socket = null;\n\n if(thread != null)\n thread.interrupt();\n thread = null;\n }\n }\n\n public Socket socket;\n\n public Thread thread;\n public boolean finished;\n }\n}\n</code></pre>\n\n<p>When your computer runs low on memory, Java will tell the garbage collector to run, which should free up some memory. I never like to leave threads \"dangling.\" I always make sure to set a thread equal to null when its done with its cycle, especially when I'm creating a bunch of them. Your code looks good from what i could see, this is just a suggestion of course so i hope it helped!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T21:22:43.650", "Id": "19695", "Score": "0", "body": "I just started reading up on concurrent programming in java. Is there any reason you didn't use `java.util.concurrent.Executors.newCachedThreadPool()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T05:56:33.230", "Id": "19715", "Score": "0", "body": "Nope, you can use that if you want, I've never used it before. It'll basically do the same thing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T18:25:30.430", "Id": "12232", "ParentId": "11998", "Score": "1" } } ]
{ "AcceptedAnswerId": "12232", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T13:27:47.763", "Id": "11998", "Score": "4", "Tags": [ "java", "multithreading", "thread-safety" ], "Title": "Alter centralized logging code to be thread safe" }
11998
<p>In an effort to reduce code duplication, I often use and have used this style to capture handling of exceptions on a boundary of an application: Given the following extension methods:</p> <pre><code>public static class FuncExtenstion { [DebuggerStepThrough] public static Action&lt;A&gt; AsAction&lt;A, T&gt;(this Func&lt;A, T&gt; f) { return (a) =&gt; f(a); } [DebuggerStepThrough] public static Func&lt;bool&gt; AsFunc(this Action a) { return () =&gt; { a(); return true; }; } } public static class IlogExtensions { public static TResult TryCatchLogThrow&lt;TResult&gt;(this ILog logger, Func&lt;TResult&gt; f) { try { return f(); } catch (Exception ex) { logger.Error(ex.Message, ex); throw; } } public static void TryCatchLogThrow(this ILog logger, Action f) { logger.TryCatchLogThrow(f.AsFunc()); } public static TResult TryCatchLog&lt;TResult&gt;(this ILog logger, Func&lt;TResult&gt; f) { try { return f(); } catch (Exception ex) { logger.Error(ex.Message, ex); return default(TResult); } } public static void TryCatchLog(this ILog logger, Action f) { logger.TryCatchLog(f.AsFunc()); } } </code></pre> <p>In the code I will use these (e.g. in a Windows/WCF/Web Service) to either silently catch the error and let the code continue to run (used in a polling service) or to at least log the error locally on the server and then rethrow the full exception again. I have used several other variations where the exception gets wrapped in more 'user friendly' exceptions or in WCF <code>FaultExceptions</code></p> <p>So typically this code is used as follows:</p> <pre><code> Response ISomeService.SomeOperation(Request request) { return _logger.TryCatchLogThrow(() =&gt; _domainImplementation.SomeOperation(request)); } OtherResponse ISomeService.OtherOperation(OtherRequest request) { return _logger.TryCatchLogThrow(() =&gt; _domainImplementation.OtherOperation(request)); } </code></pre> <p>I have not seen this style of code anywhere else. So I was wondering if there is an other pattern I should be using, or if this is ok to use.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T14:22:04.020", "Id": "19242", "Score": "0", "body": "I don't know about this kind of pattern, but wouldn't it be more proper to extend the logger class and silence the exceptions you don't need?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:44:01.820", "Id": "19273", "Score": "0", "body": "@Laurent I am essentially extending the logger class (the ILog interface here is from the [http://netcommon.sourceforge.net/](Common.Logging) framework). Yet please focus on the use of the `TryCatchxxx` method; encapsulating common TryCatch logic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-14T23:46:03.090", "Id": "61842", "Score": "0", "body": "I like this pattern; this is pretty slick." } ]
[ { "body": "<p>This looks like the <a href=\"http://c2.com/cgi/wiki?ExecuteAroundMethod\" rel=\"nofollow\">Execute Around</a> pattern in its static syntax. A thunk is passed around, and then invoked at the appropriate moment.</p>\n\n<p>The intent is however a bit different. In true execute around, the is something done before and something done after a certain action/function/block. Catching exceptions \"feels\" a bit different.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T14:26:39.730", "Id": "12033", "ParentId": "11999", "Score": "2" } }, { "body": "<p>The general advice for years has been <a href=\"http://msdn.microsoft.com/en-us/library/ms182137%28v=vs.80%29.aspx\" rel=\"nofollow noreferrer\">\"Do not catch general exception types\"</a>. This has been debated in many places, including <a href=\"https://stackoverflow.com/questions/21938/is-it-really-that-bad-to-catch-a-general-exception\">on Stack&nbsp;Overflow</a>. Basically, the advice only holds true if you don't rethrow the exception. Since you are, at least in one instance, it's not a big deal. The <code>TryCatchLog</code> is a little more dangerous, since you're not rethrowing, but merely logging. That opens the potential for the application to be in a bad state.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-14T23:48:49.700", "Id": "61843", "Score": "1", "body": "While this is true most of the time -- there are always certain places where catching general exceptions is absolutely required -- as the poster indicates, those methods are being used in the top level of a polling service, which I think is a perfect place for them." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-05-25T14:34:47.890", "Id": "12067", "ParentId": "11999", "Score": "2" } }, { "body": "<p><strong>Aspect-Oriented Programming</strong></p>\n\n<p>Rather than wrapping methods (which still is kind of boiler-plate code, which you wanted to get rid of in the first place), use <a href=\"https://en.wikipedia.org/wiki/Aspect-oriented_programming\" rel=\"nofollow noreferrer\">AOP</a>. AOP allows you to write and configure the wrapper functionality at a single place. Known frameworks for AOP are:</p>\n\n<ul>\n<li><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.contextboundobject?view=netframework-4.8\" rel=\"nofollow noreferrer\">ContextBoundObject</a></li>\n<li><a href=\"https://autofaccn.readthedocs.io/en/latest/advanced/interceptors.html\" rel=\"nofollow noreferrer\">Autofac</a></li>\n<li><a href=\"https://stackoverflow.com/questions/633710/what-is-the-best-implementation-for-aop-in-net\">And many others..</a></li>\n</ul>\n\n<hr>\n\n<p><strong>Exception hiding</strong></p>\n\n<p>The problem with code like this..</p>\n\n<blockquote>\n<pre><code>try\n{\n return f();\n}\ncatch (Exception ex)\n{\n logger.Error(ex.Message, ex); // &lt;- could throw error that hides 'ex'\n throw;\n}\n</code></pre>\n</blockquote>\n\n<p>..is that it can hide the original exception <code>ex</code>. There are some situations that could invoke this unwanted behavior, for instance:</p>\n\n<ul>\n<li>if ex is <code>OutOfMemoryException</code>, chances are <code>logger.Error</code> would throw its own instance of <code>OutOfMemoryException</code>, hiding the original error and stack trace.</li>\n<li>if <code>logger</code> throws an error logging the original error (however, most logger frameworks tend to have fallback after fallback to try to mitigate an error propagating up)</li>\n</ul>\n\n<p>At least, make the code a bit more robust. This is one way. Another is to build an <code>AggregateException</code> containing both errors, but this introduces new potential issues (what if we fail building the error..) that need to be addressed.</p>\n\n<pre><code>try\n{\n return f();\n}\ncatch (Exception ex)\n{\n try\n {\n logger.Error(ex.Message, ex); // &lt;- you will not hide my error!\n }\n catch\n { \n // we did what we could..\n }\n throw;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T18:32:36.887", "Id": "223825", "ParentId": "11999", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T13:50:32.043", "Id": "11999", "Score": "10", "Tags": [ "c#", "error-handling", "extension-methods" ], "Title": "Encapsulating common Try-Catch code. Is this a known pattern? Is it good or bad?" }
11999
<pre><code>this.displayData = function () { var i; var $thead = $(thead); var $tbody = $(tbody); var numberOfFields = columnDataFields.length; var numberOfRows = data.length; // Variables to keep track of even and odd rows. var evenRowClass = 'EvenBar'; var oddRowClass = 'OddBar'; var t = false; $tbody.html(''); // Find the widths of the column headers and apply the same widths here. // However, only do this if the colWidths are thus far undefined. if (!colWidths) { colWidths = []; var headers = $thead.find('td'); var colWdith; for (i = 0; i &lt; headers.length; i++) { colwidth = $(headers[i]).outerWidth(); colWidths.push(colwidth); $(headers[i]).css('width', colwidth); // This statement is necessary for cross-browser compatibility. (The problem is with discrepencies in "computed" CSS.) } } for (x in data) { var entry = data[x]; var row = ['&lt;tr class="']; row.push(t ? evenRowClass : oddRowClass); row.push('"&gt;'); for (i = 0; i &lt; numberOfFields; i++) { row.push('&lt;td style="width:'); row.push(colWidths[i]); row.push(';"&gt;'); row.push(entry[columnDataFields[i]]); row.push('&lt;/td&gt;'); } row.push('&lt;/tr&gt;'); $tbody.append(row.join('')); t = !t; } // If a callback function was set, invoke it. if (typeof displayCallback === 'function') displayCallback(); } // end displayData </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T17:47:28.403", "Id": "19245", "Score": "0", "body": "Your first line on your code block is not indented. I tried to fix it, but it says it is not a valid edit. lol" } ]
[ { "body": "<p>Updating tables are one of the hardest things to do since they take a long time to render. That is why people say do not use them for layouts. 1000's of rows are also bad, it would be a lot better to paginate it and only show a smaller subset.</p>\n\n<p>The problem you have is you are adding rows one by one. That is bad. You need to bulk add. Multiple updates to the DOM means the table has to keep recalculating which results in slow redraws. Basic idea of doing a bulk add:</p>\n\n<pre><code> var rows = [];\n for (x in data) {\n var entry = data[x];\n rows.push('&lt;tr class=\"');\n rows.push(t ? evenRowClass : oddRowClass);\n rows.push('\"&gt;');\n for (i = 0; i &lt; numberOfFields; i++) {\n rows.push('&lt;td style=\"width:');\n rows.push(colWidths[i]);\n rows.push(';\"&gt;');\n rows.push(entry[columnDataFields[i]]);\n rows.push('&lt;/td&gt;');\n }\n rows.push('&lt;/tr&gt;');\n t = !t;\n } \n $tbody.append(rows.join('')); // add it once\n</code></pre>\n\n<p>Another thing you can do is append it to a tbody and than use replaceWith.</p>\n\n<pre><code>$tbody.replaceWith(\"&lt;tbody&gt;\" + rows.join('') + \"&lt;/tbody&gt;);\n</code></pre>\n\n<p>other option is remove and append</p>\n\n<pre><code>$tbody.remove();\nMY_TABLE_VARIAVLE.append(\"&lt;tbody&gt;\" + rows.join('') + \"&lt;/tbody&gt;);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T18:10:28.393", "Id": "19247", "Score": "0", "body": "Can you please clarify exactly what you mean by \"the table has to keep recalculating\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T20:54:03.223", "Id": "19252", "Score": "0", "body": "@epascarello The OP was inserting the HTML for the table at once, so there's no recalculating. It's a one time calculation accounting for all the rows." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T17:41:41.017", "Id": "12005", "ParentId": "12004", "Score": "0" } }, { "body": "<p>You don't need to redraw the entire table. Try just doing DOM manipulation to reorder the TRs. I see that you also want to stripe the rows, but you can still do it with DOM manipulation. You should be able to take it from there.</p>\n\n<p>I created a simple example with almost 1000 rows and it runs almost instantaneously. There's some jQuery just so I don't have to worry about cross-browser issues. If you don't use jQuery, most libraries have the functionality I used,or you can just implement <code>$.text</code> on your own <a href=\"http://jsfiddle.net/unffs/2\" rel=\"nofollow\">http://jsfiddle.net/unffs/2</a></p>\n\n<pre><code>var table = document.getElementById('tbl');\n// Can't call sort on an HTML collection, so copy the contents to an array\nvar rows = Array.prototype.slice.call(table.rows);\nrows.sort(function(a, b) {\n var aVal = $(a).text(), bVal = $(b).text(); \n return aVal &gt; bVal ? 1 : (bVal &gt; aVal ? -1 : 0);\n});\nvar tbody = document.getElementById('tbody');\nfor (var i=0; i &lt; rows.length; i++) {\n tbody.appendChild(rows[i]);\n} \n</code></pre>\n\n<p>That code works for a table like the following</p>\n\n<pre><code>&lt;table id='tbl'&gt;\n &lt;tbody id='tbody'&gt;\n &lt;tr&gt;&lt;td&gt;D&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;A&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;C&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;E&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;F&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;B&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;D&lt;/td&gt;&lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p><strong>Using data to sort instead of HTML</strong></p>\n\n<p>If you have some underlying data for the table, it will be even faster since you won't need to read the DOM (except for an id attribute)</p>\n\n<pre><code>var data = [\n {id: 1, value: 'C'},\n {id: 2, value: 'B'},\n {id: 3, value: 'D'},\n {id: 4, value: 'A'}\n];\n</code></pre>\n\n<p>And your HTML looks like</p>\n\n<pre><code>&lt;table id='tbl'&gt;\n &lt;tbody id='tbody'&gt;\n &lt;tr id='row-1'&gt;&lt;td&gt;C&lt;/td&gt;&lt;/tr&gt;\n &lt;tr id='row-2'&gt;&lt;td&gt;B&lt;/td&gt;&lt;/tr&gt;\n &lt;tr id='row-3'&gt;&lt;td&gt;D&lt;/td&gt;&lt;/tr&gt;\n &lt;tr id='row-4'&gt;&lt;td&gt;A&lt;/td&gt;&lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>Here's the code to sort the table</p>\n\n<pre><code>var table = document.getElementById('tbl');\n// Can't call sort on an HTML collection, so copy the contents to an array\ndata.sort(function(a, b) {\n return a.value &gt; b.value ? 1 : (b.value &gt; a.value ? -1 : 0);\n});\nvar tbody = document.getElementById('tbody');\nfor (var i=0; i &lt; data.length; i++) {\n tbody.appendChild(document.getElementById('row-' + data[i].id));\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T18:09:18.430", "Id": "19246", "Score": "0", "body": "So, what you're saying is that you call the sort function on the collection of rows itself, instead of sorting the underlying data and then redisplaying all the rows?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T20:53:18.217", "Id": "19251", "Score": "0", "body": "@RiceFlourCookies Your explanation is a simplification of what I wrote in the code but is not 100% accurate, so let me reiterate. You can sort just the rows (by copying to a new array as in my example), then re-inserting them in the sort order. You can use the underlying data in the comparison instead of the HTML contents, just associate each HTML row with your data. See my updated example" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T17:53:50.827", "Id": "12006", "ParentId": "12004", "Score": "1" } } ]
{ "AcceptedAnswerId": "12006", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T17:31:48.153", "Id": "12004", "Score": "1", "Tags": [ "javascript", "optimization", "dom" ], "Title": "Can I adjust this code which displays a table to run faster?" }
12004
<p>I'm using this way to load a combo box with branch names, but it's taking more time if there is more number of data.</p> <p>Is there a better way to do this, like binding in PHP?</p> <pre><code>&lt;select name="CmbBr" id="CmbBr"&gt; &lt;?php include ("dbcon_.php"); $sql = mysql_query("SELECT BranchName FROM TblBranch ORDER BY BranchName ASC"); if(!mysql_num_rows($sql) == 0) { while($row = mysql_fetch_array($sql)) { ?&gt; &lt;option value="&lt;?php echo $row["BranchName"];?&gt;"&gt;&lt;?php echo $row["BranchName"]; ?&gt;&lt;/option&gt; &lt;?php } } ?&gt; &lt;/select&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T12:09:21.843", "Id": "19253", "Score": "3", "body": "Separate your HTML and SQL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T12:11:54.147", "Id": "19254", "Score": "1", "body": "Separate html & sql? can you show me the code alex?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T12:12:26.783", "Id": "19255", "Score": "0", "body": "Unless you have a ridiculous number of options (in the 1000s) there should not be a noticeable execution time increase with this code dependent on the number of rows. If there is, you have a more serious underlying problem with you server setup." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T12:18:09.167", "Id": "19256", "Score": "0", "body": "@ArulKumar: How you heard something known as MVC? That enables you to separate presentation logic from the business logic??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T12:19:07.673", "Id": "19257", "Score": "1", "body": "@ArulKumar What alex means is that you should do all of you preparatory DB queries at the top of the code, and output all your HTML at the bottom, more like [this](http://codepad.org/v2fkytci). I personally prefer not to mix HTML and PHP at all, more like [this](http://codepad.org/0Go2mZiM)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T13:08:18.360", "Id": "19258", "Score": "0", "body": "the query is as simple as possible. Something stupid to ask but has your table a primary key? or you can make that \"BranchName\" a primary key. also tht \"taking time\" is not descriptive. What it takes in time and how many records?" } ]
[ { "body": "<p>Yes, there is a better way but it's micro optimization and not really worth it. In php you can unroll the loop like this:</p>\n\n<pre><code> &lt;?php\n $n = $ITERATIONS % 8;\n while ($n--) $val++;\n $n = (int)($ITERATIONS / 8);\n while ($n--) {\n $val++;\n $val++;\n $val++;\n $val++;\n $val++;\n $val++;\n $val++;\n $val++; \n }\n ?&gt; \n</code></pre>\n\n<p>See also my question here: <a href=\"https://stackoverflow.com/questions/8104958/duff-device-in-php-not-possible\">https://stackoverflow.com/questions/8104958/duff-device-in-php-not-possible</a>. But you need to fetch all rows first????</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T12:22:26.917", "Id": "12010", "ParentId": "12009", "Score": "0" } }, { "body": "<p>I'd just like to note that use of the mysql_* functions are going to be deprecated in the next version or the one after than(link at the end). You should start using mysqli or PDO. </p>\n\n<p><a href=\"http://news.php.net/php.internals/53799\" rel=\"nofollow\">http://news.php.net/php.internals/53799</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-27T10:55:28.477", "Id": "12104", "ParentId": "12009", "Score": "3" } }, { "body": "<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n include ('dbcon_.php');\n\n $branches = array();\n $branch_query = mysql_query(\"SELECT BranchName FROM TblBranch ORDER BY BranchName ASC\");\n while ( $row = mysql_fetch_array($branch_query) ) {\n $branches[] = $row['BranchName'];\n }\n?&gt;\n&lt;select name=\"CmbBr\" id=\"CmbBr\"&gt;\n&lt;?php\n foreach ( $branches as $branch ) {\n?&gt;\n &lt;option value=\"&lt;?php echo $branch; ?&gt;\"&gt;&lt;?php echo $branch; ?&gt;&lt;/option&gt;\n&lt;?php\n }\n?&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>This has some separation between HTML and SQL (as mentioned in the comments). It's obviously missing most of the page code (no html tag for instance) but hopefully gives you the idea. You should have all your data accesses (SQL queries) before you output any HTML. </p>\n\n<p>Some other changes that I made:</p>\n\n<ul>\n<li>Moved the db include to the very top of the page before any variable set up, etc.</li>\n<li>Removed the extra <code>if(!mysql_num_rows($sql) == 0)</code>. The while loop will handle that case. It's rare that you'll use <code>mysql_num_rows</code>. </li>\n<li>Harmonized the whitespace. I believe it's more consistent now. </li>\n<li>I always use single quotes rather than double quotes when I'm not doing variable interpolation. </li>\n<li>I renamed <code>$sql</code> to <code>$branch_query</code> because I'd only call a string <code>$sql</code>. What you have is a query handle. </li>\n</ul>\n\n<p>My only other thought was also mentioned in the comments: make sure that there is an index on <code>BranchName</code>. It does not have to be a PRIMARY key nor even a unique index. Any index will do. Without an index, it has to generate the query results in memory, sort them, and then send them to you. With the index, it can just read this query directly from the index in sorted order. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-24T06:23:42.770", "Id": "67766", "ParentId": "12009", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T12:08:03.553", "Id": "12009", "Score": "3", "Tags": [ "php" ], "Title": "Loading a combo box with branch names" }
12009
<p>I have this code:</p> <pre><code>var submit = document.getElementById('submit'); var error = document.getElementById('error'); var url; submit.onclick = function(){ url = document.getElementById('url').value; if(url == ''){ error.style.display = 'block'; return false; } }; </code></pre> <p>Now, it's very simple in functionality. But I'm wondering if caching the error selector, for example, is worth caching or not? is it a perf hit to cache a selector if its only accessed once?</p>
[]
[ { "body": "<p>No. It only adds up after about 10,000 iterations. That is when you will see a savings from caching it. For a single selection you will be fine without caching. In the case of your code, it is definitely more readable to have the definition of error in there though.</p>\n\n<p>Either way, caching or not, with a single selection there will be basically no difference, we are talking nanoseconds.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T22:07:46.987", "Id": "12012", "ParentId": "12011", "Score": "0" } }, { "body": "<p>My general rule of thumb is to cache a selector lookup within a given function so you only look it up once for each function invocation, but to not cache it globally.</p>\n\n<p>If something was being called hundreds or thousands of times in a loop, you would want to cache it outside the loop just for common sense efficiency.</p>\n\n<p>Caching things globally is pretty much never needed for user event types of things because the performance of looking up a few objects in the DOM is super fast when compared to any sort of user action time. In other words, you wouldn't be able to tell the difference so you might as well go with the most maintainable and reliable code which avoids unnecessary globals.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T23:10:46.263", "Id": "19259", "Score": "0", "body": "I agree about unnecessary globals. When coding I try to make use of closures to avoid having globals hanging around after variables are used if they are no longer required or accessed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T23:30:13.937", "Id": "19260", "Score": "0", "body": "@TravisJ - One can certainly use closures to avoid globals. Since I work on a lot of dynamic web pages (objects created and removed as the user interacts with the page), I find it cleaner and better not to persistently cache things (beyond the lifetime of the specific operation) that might be dynamic unless a performance issue specifically calls for a cached object." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T22:40:42.970", "Id": "12013", "ParentId": "12011", "Score": "2" } }, { "body": "<p>If you only access the element once, then yes, you have a real performance hit due to the added lookup time by keeping the variable out of local scope. However, you may improve perceived performance this way since the lookup is being done at some other time then when clicking the button (not good if done at load time). </p>\n\n<p>All in all though, the element access is so quick I doubt anyone will even notice. Save it for when you access the same element many times and can tell the effect of the cache.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T17:11:43.793", "Id": "12041", "ParentId": "12011", "Score": "0" } } ]
{ "AcceptedAnswerId": "12013", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T21:56:45.897", "Id": "12011", "Score": "1", "Tags": [ "javascript", "cache" ], "Title": "Caching a JS selector then only using it once" }
12011
<p>I am looking for opinions on this code. I have been experimenting with SASS the last few days and have come up with the following code. The idea was to enable the creation of a fluid grid without having non-semantic markup in the HTML. </p> <pre><code>$columns: 12; //total number of columns to use $gutter: 3%; // gutter width can be any unit $column_width: 5.3333%; // column width can be any unit // calculated total width $total_width: $columns * ($gutter + $column_width); // Sub-pixel fix for IE http://tylertate.com/blog/2012/01/05/subpixel-rounding.html // min width in pixels, do not append px to the number. $min_width: 480; $ie_correction: (.5 / $min_width) * 100 * 1%; // calculate width of a column based on it's span. @function width( $span ) { @return ( $span * $column_width ) + ( $gutter * ( $span - 1 ) ); } // micro clearfix hack // http://nicolasgallagher.com/micro-clearfix-hack/ @mixin clearfix { &amp;:before, &amp;:after { content: ""; display: table; } &amp;:after { clear: both; } *zoom:1; } // Sets up a container for individual columns @mixin row() { display: block; width: $total_width*(($gutter + width($columns))/width($columns)); margin: 0 $total_width*((($gutter*.5)/width($columns))*-1); *width: $total_width*(($gutter + width($columns))/width($columns)) - $ie_correction; *margin: 0 ($total_width*((($gutter*.5)/width($columns))*-1)) - $ie_correction; @include clearfix; } // Sets single column and determins the offset distance and direction. // // $span: default 1; Determins the width of the column; // $type: default none; has three available options // push: pushes column to the right by the specified amount of columns // pull: pulls a column to the left by a specified amount of columns // center: centers a column of the desired size in the container // // $offset: default 0; determines the amount by which push and pull offset the column // $last: default false; if true the column will be floated to the right; @mixin column( $span: 1, $type: none, $offset: 0, $last:false ) { @if $last == true { float: right; } @else { float: left; } width: width( $span ); *width: width($span) - $ie_correction; @if $type == none { margin: 0 $gutter / 2; *margin: 0 (( $gutter / 2 ) - $ie_correction ); } @else if $type == push { margin: 0 ( $gutter / 2 ) 0 ( width( $offset ) + ( $gutter * 1.5 ) ); *margin: 0 ( ( $gutter / 2 ) - $ie_correction ) 0 ( width( $offset ) + ( $gutter * 1.5 ) - $ie_correction ); } @else if $type == pull { margin: 0 ( width( $offset ) + ( $gutter * 1.5 ) ) 0 ( $gutter / 2 ); *margin: 0 ( width( $offset ) + ( $gutter * 1.5 ) - $ie_correction ) 0 ( ( $gutter / 2 ) - $ie_correction ); } @else if $type == center { diplay: block; width: width( $span ); margin: 0 auto; float: none !important; } } // Used to order columns right-to-left. Sets single column and determins the offset distance and direction. // // $span: default 1; Determins the width of the column; // $type: default none; has three available options // push: pushes column to the right by the specified amount of columns // pull: pulls a column to the left by a specified amount of columns // center: centers a column of the desired size in the container // // $offset: default 0; determines the amount by which push and pull offset the column // $last: default false; if true the column will be floated to the right; @mixin column_right( $span: 1, $type: none, $offset: 0, $last:false ) { @if $last == true { float: left; } @else { float: right; } width: width( $span ); *width: width($span) - $ie_correction; @if $type == none { margin: 0 $gutter / 2; *margin: 0 (( $gutter / 2 ) - $ie_correction ) 0 (( $gutter / 2 ) - $ie_correction ); } @else if $type == push { margin: 0 ( width( $offset ) + ( $gutter * 1.5 ) ) 0 ( $gutter / 2 ) ; *margin: 0 ( width( $offset ) + ( $gutter * 1.5 ) - $ie_correction ) 0 ( $gutter / 2 ); } @else if $type == pull { margin: 0 ( $gutter / 2 ) 0 ( width( $offset ) + ( $gutter * 1.5 ) ); *margin: 0 ( ( $gutter / 2 ) - $ie_correction ) 0 ( width( $offset ) + ( $gutter * 1.5 ) - $ie_correction ); } @else if $type == center { diplay: block; width: width( $span ); margin: 0 auto; float: none !important; } } // Creates a grid from an elements children. By default it is designed to work // on a unordered list, but it can work with any element type chosed by the // $element variable. // // $width: default 4; defines with amount of elemeents per row // $margin: default $gutter variable; sets margin between each item // $element: default li; defines the type element to target @mixin grid( $width:4, $margin:$gutter, $element:li ) { @include clearfix; overflow: hidden; margin-left: -#{$margin}; clear: both; &amp; &gt; #{$element} { float: left; display: block; width: ( $total_width / $width ) - $margin; margin: 0 0 $margin $margin; *width: ( $total_width / $width ) - $margin - $ie_correction; *margin: 0 0 ( $margin - $ie_correction ) ( $margin - $ie_correction ); &amp;:nth-child( #{$width}n + #{$width}) { float: right; } } } </code></pre> <p>Implementation is pretty straight forward.</p> <pre><code>column(5); // 5 column width ordered left to right column(3, push, 3); //3 column width, pushing 3 columns from left column(3, pull, 3); // 3 column width, pulling 3 columns from right column(3, push, 2, true); // 3 columns, pushing 2 from left, and floated right as last column in row column_right(5); // 5 columns ordered right to left column_right(4, push, 3); //5 columns, right-to-left, pushing 3column widths from right grid(4); // creates for a four up grid when applied to a ul, applies default margin grid(5, 1%, div) // creates a five up grid with a 1% margin, which is applied to all child div elements. </code></pre> <p>I'm looking for opinions on what I can do better, and whether you think I'm overcomplicating the whole thing.</p>
[]
[ { "body": "<p>I think you are overcomplicating the whole thing. I have been building responsive design layouts for years, and there are really just not that many scenarios when a robust 'grid-system' isn't more work than it's worth. There isn't ever a 1 column area in a 12 column grid for example.</p>\n\n<p>In my experience, there are big areas (almost like mini layouts) in your larger layout. Within those, you can stack things, and then with @media queries, float them into columns when it suites you. Then when at it's largest break-point, you can start using absolute positioning and stuff if you want to lock into a really specific layout.</p>\n\n<p>Then the other situation is an actual grid of items or photos etc. That is a good time to have a little solution to split the chunks up, but really... how many do you have? 1, 2, 3, 4, 5 columns of things? Splitting them with percentages is the way to go, but depending on your markup, the gutters can be a challenge.</p>\n\n<p>I have taken a few stabs at a simple grid, but they all have their own caveats. Using min and max widths for break-points can alleviate the need to overwrite nth-of-type rules. My latest favorite way to deal is to margin-right all list-items, then the actual item is usually a link - so a display block link... then the trick is to translate the whole list over to the left a little... anyways - </p>\n\n<p>I think you'll find more cases where your 'grid' doesn't work than where is works perfectly and my suggestion is to break your ideas into a few different pieces.</p>\n\n<p>This is my most recent build: <a href=\"http://codepen.io/sheriffderek/pen/azRpRM\" rel=\"nofollow\">http://codepen.io/sheriffderek/pen/azRpRM</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-07T19:13:41.737", "Id": "104069", "ParentId": "12015", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T03:21:33.663", "Id": "12015", "Score": "4", "Tags": [ "css", "sass" ], "Title": "SASS based semantic fluid grid" }
12015
<p>I threw together this C program today to handle a bioinformatics data processing task. The program seems to work correctly, but I wanted to know if anyone has suggestions regarding how the input data are parsed and how I've used control structures in the main processing loop.</p> <pre><code>#include &lt;assert.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define BUFFERSIZE 1024 FILE *fileopen(const char *filename, const char *mode) { FILE *fh = fopen(filename, mode); if(fh == NULL) { fprintf(stderr, "error: unable to open file '%s'\n", filename); exit(1); } return fh; } void *memalloc(size_t size) { void *memory = malloc(size); if(memory == NULL) { fprintf(stderr, "error: unable to allocate memory\n"); exit(1); } return memory; } int main(int argc, const char **argv) { // Parse command line arguments char seqbuffer1[BUFFERSIZE]; char seqbuffer2[BUFFERSIZE]; char qualbuffer1[BUFFERSIZE]; char qualbuffer2[BUFFERSIZE]; char *seqbufferout; FILE *seqinfile; FILE *seqoutfile; FILE *qualinfile; FILE *qualoutfile; int seqlength; if(argc != 6) { fprintf(stderr, "error: 5 arguments required, %d provided\n", argc - 1); exit(1); } seqinfile = fileopen(argv[1], "r"); qualinfile = fileopen(argv[2], "r"); seqoutfile = fileopen(argv[3], "w"); qualoutfile = fileopen(argv[4], "w"); seqlength = atoi(argv[5]); assert(seqlength &gt; 0); // Process reads seqbufferout = (char *)memalloc( sizeof(char) * (seqlength + 1) ); seqbufferout[seqlength] = '\0'; while(fgets(seqbuffer1, BUFFERSIZE, seqinfile)) { if(strlen(seqbuffer1) &gt; 0) { int ambiguous; int i; assert(strncmp(seqbuffer1, "&gt;", 1) == 0); if(fgets(seqbuffer2, BUFFERSIZE, seqinfile) == NULL) { fprintf(stderr, "error: file ends with a fasta header\n"); exit(1); } if( fgets(qualbuffer1, BUFFERSIZE, qualinfile) == NULL || fgets(qualbuffer2, BUFFERSIZE, qualinfile) == NULL ) { fprintf(stderr, "error: no quality entry corresponding to sequence '%s'\n", seqbuffer1); exit(1); } ambiguous = 0; for(i = 0; i &lt; seqlength; i++) { if(seqbuffer2[i] == '.') { ambiguous = 1; break; } seqbufferout[i] = seqbuffer2[i]; } if(!ambiguous) { fprintf(seqoutfile, "%s%s\n", seqbuffer1, seqbufferout); fputs(qualbuffer1, qualoutfile); i = 0; char *tok = strtok(qualbuffer2, " "); while(tok != NULL &amp;&amp; i &lt; seqlength - 1) { if(i &gt; 0) fputs(" ", qualoutfile); fputs(tok, qualoutfile); tok = strtok(NULL, " "); i++; } fputs("\n", qualoutfile); } } } fclose(seqinfile); fclose(qualinfile); fclose(seqoutfile); fclose(qualoutfile); free(seqbufferout); return 0; } </code></pre>
[]
[ { "body": "<p>Instead of the big indent block you make by doing <code>if(strlen(seqbuffer1) &gt; 0)</code>, do: <code>if (strlen(seqbuffer1) &lt;1) continue;</code>, so the entire rest of the loop can be outdented a level, making it more readable. </p>\n\n<p>Similarly, you can turn the <code>if(!ambiguous)</code> into <code>if (ambiguous) continue;</code> and outdent that block as well.</p>\n\n<p>Depending on what version of C you're using, ambiguous could be a <code>boolean</code> instead of an <code>int</code>.</p>\n\n<p>You could be a little more consistent with your NULL comparisons to the result of fgets() - the one in the while() condition is implicitly <code>!= NULL</code> but the ones in the if() statements are explicitly <code>== NULL</code>. IMO you should be either explicit everywhere or implicit everywhere - either choice is fine, but mixing styles makes your code a bit more unclear.</p>\n\n<p><code>assert(strncmp(seqbuffer1, \"&gt;\", 1) == 0);</code> is the same as the more-easily-understood <code>assert(seqbuffer1[0] == '&gt;')</code>, right?</p>\n\n<p>Also, you've got at least one potential bug: What if BUFFERSIZE is smaller than input line length and then seqlength > BUFFERSIZE?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T06:24:13.493", "Id": "19405", "Score": "0", "body": "While I agree that large statements are hard to read, I think continue is even worse, it leads to spaghetti and is generally considered bad practice (it is banned by MISRA-C for example). Instead, use functions. `if(strlen(seqbuffer1) > 0)) parse_string(seqbuffer);` This is how you make programs clearer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T18:47:03.777", "Id": "19434", "Score": "0", "body": "`continue` can really only exacerbate spaghetti code, not cause it: it's only unclear if it's in the middle of a large block... but I'd argue that's a problem with having a large block, not with `continue`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T14:11:39.020", "Id": "19534", "Score": "0", "body": "Here is an example of spaghetti caused solely by the continue keyword: `for(i=0; i<condition; i++)\n{\n if(something)\n { continue; }\n\n a[count] = b[i];\n count++;\n}` The code is hard to read, because it is not obvious to the reader when `i` and `count` are increased respectively." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T14:16:14.580", "Id": "19535", "Score": "0", "body": "Apart from that, the general definition of spaghetti no matter programming language, is usually \"code that jumps both upwards and downwards\". Code that only jumps downwards is usually considered acceptable, even if it is using goto. C language `continue` does not fit in anywhere, except in code jumping upwards." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T19:13:37.840", "Id": "19621", "Score": "0", "body": "I think that can be argued both ways; http://www.virtualdub.org/blog/pivot/entry.php?id=238 argues opposite to you." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T14:29:46.637", "Id": "12034", "ParentId": "12016", "Score": "2" } }, { "body": "<p>General comments:</p>\n\n<ul>\n<li>use <code>perror</code> instead of <code>fprintf</code> on error</li>\n<li>use EXIT_FAILURE as an exit code on failure</li>\n</ul>\n\n<p>main()</p>\n\n<ul>\n<li><code>seqbufferout</code> and hence <code>memalloc()</code> are redundant</li>\n<li>but as it is, the call to <code>memalloc</code> should omit <code>sizeof(char)</code>, which is 1 by default and should omit the cast.</li>\n<li>fgets calls maybe use <code>sizeof buf</code> instead of BUFFERSIZE</li>\n<li>is <code>fgets(seqbuffer1...) != NULL</code> and <code>strlen(seqbuffer1) == 0</code> a possible combination? I don't think so - in which case the strlen is redundant</li>\n<li>assert on <code>seqbuffer1[0] == '&gt;'</code>, not on a strcmp</li>\n<li>for-loops like this that do a well-defined task should be extracted into a function</li>\n<li>but this for loops seems just to look for a '.'; <code>strchr</code> would be better</li>\n<li>copying <code>seqbuffer2</code> to <code>seqbufferout</code> seems redundant as you just print the contents of <code>seqbufferout</code></li>\n<li><p>the while loop should be extracted into a separate function; it looks as if the loop just strips leading and trailing spaces and multiple spaces from the <code>qualbuffer2</code> string - is that right?</p></li>\n<li><p>so (unless I misunderstood the purpose of the code) the stuff from and including <code>ambiguous = 0</code> becomes:</p>\n\n<pre><code>if (!strchr(seqbuffer2, '.'))\n{\n fprintf(seqoutfile, \"%s%s\\n\", seqbuffer1, seqbuffer2);\n fputs(qualbuffer1, qualoutfile);\n fputs(strip_spaces(qualbuffer2), qualoutfile);\n fputs(\"\\n\", qualoutfile);\n}\n</code></pre></li>\n<li><p>no checks for error in writing to the output files</p></li>\n<li><p>no check for error in seqinfile on exit from the main loop. You need to append the following before closing the files </p>\n\n<pre><code>if (ferror(seqinfile)) \n{\n perror(...); \n ...\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T14:22:32.383", "Id": "12066", "ParentId": "12016", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T03:39:17.667", "Id": "12016", "Score": "2", "Tags": [ "c", "parsing", "bioinformatics" ], "Title": "Data processing task for bioinformatics" }
12016
<p>I just got through writing a bash script so my friend and I can share snippets of code to a central file via rsync and ssh. What it does is this;</p> <ol> <li>Sets up ssh public key auth if not already working.</li> <li>Makes a local "snippet file" using rsync to copy an exiting file from remote server.</li> <li>Allows the user to edit the snippet file.</li> <li>If user chooses, sync snippet file to remote host.</li> </ol> <p>I put the project on github at <a href="https://github.com/shakabra/snippetShare" rel="nofollow">https://github.com/shakabra/snippetShare</a></p> <p>It's a pretty straight-forward script, but I wonder what could be done better.</p> <p>I am really new at programming and was hoping you guys might spot some obvious mistakes that I just over-looked or don't understand.</p> <pre><code>#!/bin/bash SERVER="dakinewebs.com" UN="" PORT="22" TIME=$(date +"%c") localSnippetFile=$HOME/snippetFile.html remoteSnippetFile=/home/shakabra/dakinewebs.com/snippetShare/snippetFile.html checkSsh () { ssh -o BatchMode=yes "$UN"@"$SERVER" 'exit' if [[ $? = 255 ]]; then echo "Local key doesn't exits" echo "creating local key" ssh-keygen -t rsa ssh-add uploadKey fi } sshConfig () { if [[ -z $SERVER ]]; then echo -e "SERVER NAME:\n" read SERVER fi if [[ -z $UN ]]; then echo -e "USERNAME:\n" read UN fi if [[ -z $PORT ]]; then echo -e "PORT:\n" read PORT fi } makeLocalSnippet () { echo "syncing with remote snippet" rsync -avz --progress -e ssh "$UN"@"$SERVER":"$remoteSnippetFile" "$localSnippetFile" } editSnippet () { echo -e "What's the title of the snippet?\n" read snippetTitle echo -e "&lt;time&gt;"$TIME"&lt;/time&gt;\n" &gt;&gt; "$localSnippetFile" echo -e "&lt;header&gt;"$snippetTitle"&lt;/header&gt;" &gt;&gt; "$localSnippetFile" echo "&lt;pre&gt;&lt;/pre&gt;" &gt;&gt; "$localSnippetFile" nano "$localSnippetFile" syncSnippet while [[ $? = 1 ]]; do syncSnippet done } syncSnippet () { read -p "Sync snippet file now [y/n]: " syncNow case $syncNow in y|Y|yes|YES|Yes) rsync -av --delete -e ssh "$localSnippetFile" "$UN"@"$SERVER":"$remoteSnippetFile" ;; n|N|no|No|NO) echo "Guess we'll sync next time. Hope it wasn't too important!" ;; *) echo "not an answer" return 1 ;; esac } uploadKey () { ssh-copy-id "$UN"@"$SERVER" ssh "$UN"@"$SERVER" 'exit' echo "Key uploaded" } sshConfig checkSsh makeLocalSnippet editSnippet </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T10:47:36.057", "Id": "19270", "Score": "4", "body": "You should show your code in the question, rather than giving a link to the code, as per [faq]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T22:33:43.597", "Id": "19313", "Score": "0", "body": "I have not looked at the code, but it just seems to me that you would be better off just using a version control system." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T08:34:44.247", "Id": "19408", "Score": "0", "body": "If you are satisfied with one of the answer, it is nice to \"accept\" the answer :)." } ]
[ { "body": "<p>Don't hardcode the editor. I happen to prefer vi, so don't force me to use nano.</p>\n\n<pre><code>editor=${VISUAL:-${EDITOR:-nano}}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T10:12:25.493", "Id": "12019", "ParentId": "12017", "Score": "3" } }, { "body": "<p>Your <code>read</code> calls perform <code>\\</code> expansion: if the line ends with <code>\\</code>, the shell continues reading the next line and returns the text without the backslash-newline sequence; any other backslash quotes the next character (i.e. the backslash is ignored, except that <code>\\\\</code> yields <code>\\</code>). This is probably not desirable; use <code>read -r</code> to avoid this behavior. Also, for future reference, note that whitespace at the beginning and end of the input is stripped (you need to set <code>IFS</code> to the empty string to avoid this, but here stripping whitespace is desirable); see <a href=\"https://unix.stackexchange.com/questions/26784/understanding-ifs\">Understanding IFS</a> and the linked posts.</p>\n\n<p>Furthermore, since this script is designed for interactive use, you should use <code>read -e</code> to enable editing of the input line (with readline). It would also be nicer to have the prompt together with the input line: use <code>read -p 'Server name: '</code> and so on instead of calling <code>echo</code> (and don't SHOUT). For example:</p>\n\n<pre><code>if [[ -z $SERVER ]]; then\n read -rep 'Server name: ' SERVER\nfi\n\nrsync -avz --progress -e ssh \"$UN\"@\"$SERVER\":\"$remoteSnippetFile\" \"$localSnippetFile\"\n</code></pre>\n\n<p>This looks a little more complicated than it needs to be, you can write <code>\"$UN@$SERVER:$remoteSnippetFile\"</code>.</p>\n\n<p>The following part has a bug and is not as readable as it could be:</p>\n\n<blockquote>\n<pre><code>echo -e \"&lt;time&gt;\"$TIME\"&lt;/time&gt;\\n\" &gt;&gt; \"$localSnippetFile\"\necho -e \"&lt;header&gt;\"$snippetTitle\"&lt;/header&gt;\" &gt;&gt; \"$localSnippetFile\"\necho \"&lt;pre&gt;&lt;/pre&gt;\" &gt;&gt; \"$localSnippetFile\"\n</code></pre>\n</blockquote>\n\n<p>The bug is that <code>$TIME</code> and <code>$snippetTitle</code> undergo word splitting and filename generation (i.e. globbing). For example, if <code>$snippetTitle</code> is <code>The A* algorithm</code> and the current directory contains the files <code>Astar.tex</code>, <code>Astar.pdf</code> and <code>test.c</code>, then you're writing <code>&lt;header&gt;The Astar.pdf Astar.tex algorithm&lt;/header&gt;</code> to the file. <strong>Always use double quotes around variable and command substitutions</strong>, unless you know why you must leave them off and why it's safe to do so. (Exception: you may leave off the double quotes in contexts where they are explicitly not needed, such as inside <code>[[ … ]]</code>.)</p>\n\n<p>The readability improvement is to use a <a href=\"http://en.wikipedia.org/wiki/Here_document\" rel=\"nofollow noreferrer\">here document</a>.</p>\n\n<pre><code>cat &lt;&lt;EOF &gt;&gt;\"$localSnippetFile\"\n&lt;time&gt;$TIME&lt;/time&gt;\n&lt;header&gt;$snippetTitle&lt;/header&gt;\n&lt;pre&gt;&lt;/pre&gt;\nEOF\n</code></pre>\n\n<blockquote>\n<pre><code>nano \"$localSnippetFile\"\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://codereview.stackexchange.com/a/12019\">glenn jackman</a> has already mentioned this: it's rude to impose your editor on the user. There is a standard for letting the user choose an editor: use the <code>VISUAL</code> environment variable, falling back to <code>EDITOR</code>. Use a sensible fallback if neither variable is set.</p>\n\n<pre><code>if [[ -z ${VISUAL=$EDITOR} ]]; then\n for VISUAL in sensible-editor nano vi; do\n if type \"$VISUAL\" &gt;/dev/null 2&gt;/dev/null; then break; fi\n done\nfi\n\nDrop this …\n</code></pre>\n\n<blockquote>\n<pre><code> while [[ $? = 1 ]]; do\n syncSnippet\n done\n</code></pre>\n</blockquote>\n\n<p>… and instead change <code>syncSnippet</code> to first call <code>read</code> until the user enters an accepted input, and then perform the actions based on this input.</p>\n\n<pre><code>while\n read -p \"Sync snippet file now [y/n]: \" -rN1 yn\n [[ $yn != [YNyn] ]]\ndo :; done\nif [[ $yn = [Yy] ]]; then\n rsync …\nfi\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T23:27:07.133", "Id": "19349", "Score": "0", "body": "Wow! thanks Giles and glen. I have got a lot of homework to do now. In particular thanks for the help with that syncSnippet logic. I appreciate the time you guys put in to school me." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T23:12:39.930", "Id": "12046", "ParentId": "12017", "Score": "4" } } ]
{ "AcceptedAnswerId": "12046", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T04:18:16.737", "Id": "12017", "Score": "3", "Tags": [ "bash" ], "Title": "Bash script to share snippets of code using rsync" }
12017
<p>The following is a little JavaScript project to display quotes on a web page. Since I want to use it in a number of different web sites, I read up on good practices for making portable JavaScript code, e.g.:</p> <ul> <li>use no global variables</li> <li>use namespaces</li> <li>make it easy to plugin</li> <li>use default values which can be overridden</li> </ul> <p>For those of you who have experience writing JavaScript libraries and portable JavaScript code, what could be improved on this code to</p> <ol> <li>make it more portable?</li> <li>avoid any unforeseen problems or conflicts?</li> <li>improve the naming conventions, etc.?</li> </ol> <p><strong>index.htm:</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;smart quotes&lt;/title&gt; &lt;script type="text/javascript" src="js/jquery-1.7.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/smartquotes.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; window.onload = function() { SMARTQUOTES.init(); SMARTQUOTES.quotes = new Array( 'It\'s tempting to augment prototypes of built-in constructors such as Object(), Array(), or Function(), but it can seriously hurt maintainability.', 'We come from XHTML backgrounds, so we will close all tags, use lowercase, and use quotation marks around attributes.', 'Checking to see if a value exists inside an array is always a bore in JavaScript.', 'JavaScript classes have the same effect on some people that garlic has on Dracula.', 'Mixins are not supported natively by CoffeeScript, for the good reason that they can be trivially implemented yourself.', 'Using a single var statement at the top of your functions is a useful pattern to adopt.', 'Using the Function() constructor is as bad as eval()', 'Any obstacle that I\'ve encountered during my development by placing JavaScript at the bottom of the page has been easily overcome and well worth the optimization gains.' ); SMARTQUOTES.duration = 8000; SMARTQUOTES.start(); }; &lt;/script&gt; &lt;style type="text/css"&gt; div#quoteWrapper { border: 1px solid #999; padding: 10px; background: #eee; color: navy; width: 300px; border-radius: 5px; font-style: italic; font-family: arial; font-size: 12pt; text-align: center; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="quoteWrapper"&gt; &lt;div id="SMARTQUOTE"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p><strong>smartquotes.js:</strong></p> <pre><code>(function(global) { var SMARTQUOTES = {}; if(global.SMARTQUOTES) { throw new Error('SMARTQUOTES has already been defined'); } else { global.SMARTQUOTES = SMARTQUOTES; } })(typeof window === 'undefined' ? this : window); SMARTQUOTES.init = function() { SMARTQUOTES.quoteIndex = 0; SMARTQUOTES.duration = 3000; SMARTQUOTES.quotes = new Array(); SMARTQUOTES.quotes[0] = 'test quote #1'; SMARTQUOTES.quotes[1] = 'this is the second quote'; SMARTQUOTES.quotes[2] = 'and now the third and last quote'; SMARTQUOTES.element = $('div#SMARTQUOTE').hide(); SMARTQUOTES.incrementQuote = function() { SMARTQUOTES.quoteIndex++; if(SMARTQUOTES.quoteIndex &gt;= SMARTQUOTES.quotes.length) { SMARTQUOTES.quoteIndex = 0; } } SMARTQUOTES.displayQuote = function () { var quote = SMARTQUOTES.quotes[SMARTQUOTES.quoteIndex]; SMARTQUOTES.element.fadeOut('slow', function() { SMARTQUOTES.element.html(quote); }); SMARTQUOTES.element.fadeIn(); SMARTQUOTES.incrementQuote(); SMARTQUOTES.startTimer(); } SMARTQUOTES.startTimer = function () { var t = setTimeout('SMARTQUOTES.displayQuote()', SMARTQUOTES.duration); } SMARTQUOTES.start = function() { SMARTQUOTES.displayQuote(); } } </code></pre>
[]
[ { "body": "<ul>\n<li><p>Take advantage of jQuery's <code>.ready()</code>. It's an abstraction that includes <code>window.onload</code>. Here's <a href=\"http://api.jquery.com/jQuery/#jQuery3\" rel=\"nofollow\">a shorthand version</a>:</p>\n\n<pre><code>$(function(){\n //DOM ready\n});\n</code></pre></li>\n<li><p>Build a plugin instead. That way, you get the benefits of having to be \"chained\" to jQuery. Here's <a href=\"http://jqueryboilerplate.com/\" rel=\"nofollow\">a boilerplate</a> to get you started. It has the necessary explanations as well as some prepared set-up for a plugin.</p></li>\n<li><p>If portability is key to this code, I'd rather not hardcode the element that it will be attached to. If it were a plugin, it would look like this:</p>\n\n<pre><code>$(function(){\n\n //DOM ready, attach plugin to div\n\n $('div#SMARTQUOTE').smartQuotes({\n duration : 8000,\n quotes : [\n 'quote1',\n 'quote2',\n ...\n ]\n });\n\n});\n</code></pre>\n\n<p>everything looks \"smart\" this way (no pun intended);</p></li>\n<li><p>Now i will dive into your code. First I notice, you are using <code>new Array()</code>. That's old school. Use literals intead:</p>\n\n<pre><code>SMARTQUOTES.quotes = [];\n</code></pre></li>\n<li><p>in the boilerplate, you will only have one exposed function, and that is the <code>smartQuotes</code> function (the one that is attached to jQuery). Everything else is hidden in \"private\" so everything else is not touched. This way, there is no conflict at all. The only conflict you will get is when the user actually has a plugin of the same name as you have.</p></li>\n<li><p>If you need to expose some functions/events for \"hooking\", hand them over as callbacks:</p>\n\n<pre><code> $('div#SMARTQUOTE').smartQuotes(\n duration : 8000,\n quotes : [\n 'quote1',\n 'quote2',\n ...\n ],\n onStart : function(){\n //executed on start\n }\n );\n\n //in the plugin boilerplate\n this.options.onStart()\n</code></pre></li>\n<li><p>additionally, here are common naming conventions. They do not work as they are described but just signify their purpose:</p>\n\n<ul>\n<li><code>UNDERSCORE_SPACED_ALL_CAPS</code> - means a contstant</li>\n<li><code>camelCased</code> - public variables and functions</li>\n<li><code>_underscoredPrefixedCamelCase</code> - private properties and methods</li>\n</ul>\n\n<p>But you do have to be wary since there is a library named underscoreJS that uses an underscore namespace <code>_.method</code>. It may get confusing when you use <code>_</code>. Likewise with <code>$</code>, where not only jQuery uses it (I think Zepto and MooTools uses them)</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:14:50.483", "Id": "12021", "ParentId": "12020", "Score": "4" } } ]
{ "AcceptedAnswerId": "12021", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T10:56:50.477", "Id": "12020", "Score": "2", "Tags": [ "javascript", "portability" ], "Title": "Display quotes on a web page" }
12020
<p>Alright so this isn't an issue with my program not working, it's more of a fact that I wanna learn to code better. </p> <p>This is one of 6 if else statements that I use inside of my program. What I'm trying to do is make it shorter (easier) to do. I am learning AS3 with Flex 4.6 (started with Flex 4). </p> <p>If I left something out that is important let me know I'll get it for you. All the <code>.text</code>'s can be changed at any time the user wants.</p> <p>Thanks In advance for any help! </p> <pre><code> if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "10"){ bap.text = String(Number(1147)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "11"){ bap.text = String(Number(1217)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "12"){ bap.text = String(Number(1297)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "13"){ bap.text = String(Number(1343)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "14"){ bap.text = String(Number(1407)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "15"){ bap.text = String(Number(1467)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "16"){ bap.text = String(Number(1530)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "17"){ bap.text = String(Number(1587)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "18"){ bap.text = String(Number(1632)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "19"){ bap.text = String(Number(1709)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "20"){ bap.text = String(Number(1754)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized XL" &amp;&amp; asf.text == "14"){ bap.text = String(Number(1490)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized XL" &amp;&amp; asf.text == "15"){ bap.text = String(Number(1560)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized XL" &amp;&amp; asf.text == "16"){ bap.text = String(Number(1636)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized XL" &amp;&amp; asf.text == "17"){ bap.text = String(Number(1703)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized XL" &amp;&amp; asf.text == "18"){ bap.text = String(Number(1758)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized XL" &amp;&amp; asf.text == "19"){ bap.text = String(Number(1848)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized XL" &amp;&amp; asf.text == "20"){ bap.text = String(Number(1903)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "10"){ bap.text = String(Number(1247)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "11"){ bap.text = String(Number(1317)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "12"){ bap.text = String(Number(1397)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "13"){ bap.text = String(Number(1443)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "14"){ bap.text = String(Number(1507)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "15"){ bap.text = String(Number(1567)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "16"){ bap.text = String(Number(1603)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "17"){ bap.text = String(Number(1687)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "18"){ bap.text = String(Number(1732)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "19"){ bap.text = String(Number(1823)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "20"){ bap.text = String(Number(1878)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro XL" &amp;&amp; asf.text == "14"){ bap.text = String(Number(1509)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro XL" &amp;&amp; asf.text == "15"){ bap.text = String(Number(1660)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro XL" &amp;&amp; asf.text == "16"){ bap.text = String(Number(1736)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro XL" &amp;&amp; asf.text == "17"){ bap.text = String(Number(1803)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro XL" &amp;&amp; asf.text == "18"){ bap.text = String(Number(1858)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro XL" &amp;&amp; asf.text == "19"){ bap.text = String(Number(1962)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Motorized Pro XL" &amp;&amp; asf.text == "20"){ bap.text = String(Number(2027)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Oasis" &amp;&amp; asf.text == "10 x 16"){ bap.text = String(Number(1305)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "10"){ bap.text = String(Number(927)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "11"){ bap.text = String(Number(997)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "12"){ bap.text = String(Number(1077)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "13"){ bap.text = String(Number(1123)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "14"){ bap.text = String(Number(1187)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "15"){ bap.text = String(Number(1247)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "16"){ bap.text = String(Number(1310)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "17"){ bap.text = String(Number(1367)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Woven Acrylic" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "18"){ bap.text = String(Number(1412)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "10"){ bap.text = String(Number(1047)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "11"){ bap.text = String(Number(1107)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "12"){ bap.text = String(Number(1167)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "13"){ bap.text = String(Number(1213)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "14"){ bap.text = String(Number(1257)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "15"){ bap.text = String(Number(1307)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "16"){ bap.text = String(Number(1360)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "17"){ bap.text = String(Number(1407)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized" &amp;&amp; asf.text == "18"){ bap.text = String(Number(1452)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "10"){ bap.text = String(Number(1147)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "11"){ bap.text = String(Number(1207)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "12"){ bap.text = String(Number(1267)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "13"){ bap.text = String(Number(1313)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "14"){ bap.text = String(Number(1357)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "15"){ bap.text = String(Number(1407)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "16"){ bap.text = String(Number(1460)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "17"){ bap.text = String(Number(1507)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Motorized Pro" &amp;&amp; asf.text == "18"){ bap.text = String(Number(1552)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "10"){ bap.text = String(Number(827)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "11"){ bap.text = String(Number(887)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "12"){ bap.text = String(Number(947)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "13"){ bap.text = String(Number(993)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "14"){ bap.text = String(Number(1037)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "15"){ bap.text = String(Number(1087)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "16"){ bap.text = String(Number(1140)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "17"){ bap.text = String(Number(1187)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else if (ft.text == "Traditonal Laminated" &amp;&amp; at.text == "Vista" &amp;&amp; asf.text == "18"){ bap.text = String(Number(1232)) tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)) } else (bap.text = "0"); // TODO Auto-generated method stub tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text)); } </code></pre>
[]
[ { "body": "<p>Maybe this will help</p>\n\n<pre><code>if (ft.text == \"Woven Acrylic\" &amp;&amp; at.text == \"Motorized\"){\n switch (asf.text) {\n case \"10\":\n bap.text = String(Number(1147))\n break ;\n case \"11\":\n bap.text = String(Number(1217))\n break ;\n ...\n }\n tc_v.text = '$' + String(Number(bap.text) + Number(ac_.text))\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:01:32.293", "Id": "19274", "Score": "0", "body": "I think this is still not better, it is just the same, but formatted in a different way. You still need lots of conditions in this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T14:18:59.330", "Id": "21865", "Score": "0", "body": "@MarkKnol I think this is an acceptable answer to the OP's question. It's not great since it only removes some of the extraneous conditionals, but it does help the OP see other ways to write logic. Based on the OP's code, he's seems very new to programming. He needs practice simplifying if-blocks. I think he has a while before he'll be able to appreciate the data driven answers people are giving." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T06:52:23.283", "Id": "12023", "ParentId": "12022", "Score": "4" } }, { "body": "<p>This should be done with a function that gets values for \"ft\", \"at\" and \"asf\" based on each consecutive selections starting from \"ft\". If your code explained the logic behind the numbers \"1217\", \"1418\" being assigned to \"bap.text\", it would be way much better than what I'm writing below:</p>\n\n<pre><code>public function generateText(ft:String, at:String, asf:String):void\n{\n var concatenated:String = ft +\"_\" + at + \"_\" + asf;\n switch(concatenated)\n {\n case \"Woven Acrylic_Motorized_10\":\n bap.text = String(1147);\n tc_v.text = '$' + bap.text + parseFloat(ac_.text);\n break;\n case \"Woven Acrylic_Motorized_11\":\n bap.text = String(1217);\n tc_v.text = '$' + bap.text + parseFloat(ac_.text);\n break;\n default:\n bap.text = 0;\n break; \n\n }\n}\n</code></pre>\n\n<p>You also do not need to cast numbers into strings to assign them to a textfield. You can remove much of the explicit casting you're doing in your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T07:34:21.933", "Id": "19275", "Score": "1", "body": "You do need to cast numbers to strings before assigning them to `TextField.text` or you'll get an implicit coercion error - luckily appending a string to a number does this for you. Your `default:` will break though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:04:14.290", "Id": "19276", "Score": "0", "body": "I think this isn't better, i don't see why you merge all text into one. What if an extra parameter is required? What if you miss and underscore in the case (like you already did). It's less readable and not maintainable on long term and with lots of data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T12:04:15.393", "Id": "19277", "Score": "0", "body": "The approach requires concatenating strings to build associative keys. I didn't say the switch statement is good, there's no need for that. Interestingly weltraumpirat down below this page has given a better solution to what I tried to envision here." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T07:17:57.233", "Id": "12024", "ParentId": "12022", "Score": "1" } }, { "body": "<p>Put your numbers in an array. Then your code could look like:</p>\n\n<pre><code>if (ft.text == \"Woven Acrylic\" &amp;&amp; at.text == \"Motorized\"){\n bap.text = String(array[Number(asf.text)])\n tc_v.text = '$' + String(array[Number(asf.text)]) + Number(ac_.text))\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T07:24:06.310", "Id": "12025", "ParentId": "12022", "Score": "2" } }, { "body": "<p>You can use if-else or switch-case statement but switch case method is faster than if-else. But if-else which i would specify is faster than the code u have written here as it optimizes the code\nlike</p>\n\n<pre><code>if(ft.text == \"Woven Acrylic\") {\n if(at.text == \"Motorized\") {\n if(asf.text == \"10\") {\n // Statement\n }\n // More If Statements\n }\n // More If Statements each containing if statements\n} else if(ft.text == \"Laminated\") {\n // More If Statements each containing if statements that contain if statements\n}\n// More If Statements Et Cetera\n</code></pre>\n\n<p>second method taking switch for woven acrylic and laminated and invoke a function which includes another switch case that will be faster</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T08:16:15.167", "Id": "19278", "Score": "0", "body": "dude, please format your code. This is painful to look at. http://stackoverflow.com/editing-help" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:05:19.687", "Id": "19279", "Score": "0", "body": "I think this is still not better, it is just the same, but formatted in a different way. You still need lots of conditions in this case." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T07:33:37.697", "Id": "12026", "ParentId": "12022", "Score": "1" } }, { "body": "<p>Might be this may help you: -</p>\n\n<p>As you know all values you can do it by other way as below: - as all values are static: - or some thing like below....</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;s:Application xmlns:fx=\"http://ns.adobe.com/mxml/2009\" \n xmlns:s=\"library://ns.adobe.com/flex/spark\" \n xmlns:mx=\"library://ns.adobe.com/flex/mx\" minWidth=\"955\" minHeight=\"600\"&gt;\n &lt;fx:Declarations&gt;\n &lt;!-- Place non-visual elements (e.g., services, value objects) here --&gt;\n &lt;/fx:Declarations&gt;\n &lt;fx:Script&gt;\n &lt;![CDATA[\n import mx.collections.ArrayCollection;\n\n //ft.text == \"Woven Acrylic\" &amp;&amp; at.text == \"Motorized\" &amp;&amp; asf.text == \"10\"\n //ft.text == \"Traditonal Laminated\" &amp;&amp; at.text == \"Motorized\" &amp;&amp; asf.text == \"13\"\n private var oneOf6:ArrayCollection = new ArrayCollection\n (\n [{ftValue:\"Woven Acrylic\",atValue:\"Motorized\",asfValue:\"10\", bapValue:1147},\n {ftValue:\"Woven Acrylic\",atValue:\"Motorized\",asfValue:\"11\", bapValue:1217},\n {ftValue:\"Woven Acrylic\",atValue:\"Motorized\",asfValue:\"12\", bapValue:1297},\n {ftValue:\"Woven Acrylic\",atValue:\"Motorized\",asfValue:\"13\", bapValue:1343},\n {ftValue:\"Woven Acrylic\",atValue:\"Motorized\",asfValue:\"14\", bapValue:1407},\n {ftValue:\"Woven Acrylic\",atValue:\"Motorized\",asfValue:\"15\", bapValue:1467},\n {ftValue:\"Traditonal Laminated\",atValue:\"Motorized\",asfValue:\"13\", bapValue:1213}\n .\n .\n\n ]);\n\n private function getValueDisplay():void\n {\n for(var i:int; i&lt;oneOf6.length;i++)\n {\n if(oneOf6[i].ftValue == ft.text &amp;&amp; oneOf6[i].atValue == at.text &amp;&amp; oneOf6[i].asfValue == asf.text)\n {\n tc_v.text = '$' +oneOf6[i].bapValue + Number(ac_.text))\n break;\n }\n }\n }\n\n ]]&gt;\n &lt;/fx:Script&gt;\n &lt;mx:VBox&gt;\n &lt;s:TextInput id=\"ft\" text=\"Woven Acrylic\"/&gt;\n &lt;s:TextInput id=\"at\" text=\"Motorized\"/&gt;\n &lt;s:TextInput id=\"asf\" text=\"10\"/&gt;\n &lt;s:TextInput id=\"tc_v\"/&gt;\n &lt;s:TextInput id=\"bap\"/&gt;\n &lt;s:TextInput id=\"ac_\"/&gt;\n &lt;s:Button label=\"click\" click=\"getValueDisplay()\"/&gt;\n &lt;/mx:VBox&gt;\n\n&lt;/s:Application&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T07:42:18.580", "Id": "12027", "ParentId": "12022", "Score": "0" } }, { "body": "<p>Since you want to learn to code properly, my advice would be to create a model for your application (read up on the <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">model-view-controller pattern</a> if you haven't already). I'll try to get you started with this example.</p>\n\n<p>For starters, your variable names don't speak for themselves, which leaves me (or any other developer) guessing as to what their value is. I'll guess a bit and I seem to see a combination of 3 properties that make up one unique ID. We'll create a model class for that item; let's call it <code>ShopItem</code>.</p>\n\n<pre><code>[Bindable]\npublic class ShopItem {\n\n public var id:int;\n public var material:Material;\n public var type:Type;\n public var mysteriousId:int;\n\n}\n</code></pre>\n\n<p>As you see it has an ID property, plus the three other properties that make up a unique combination. The last property is just an <code>int</code> as I have no more information about it than that, but it could be a class just as the others. Also, I have made the class Bindable, so we can use it for data binding later on. Now lets create the other two classes.</p>\n\n<pre><code>[Bindable]\npublic class Material {\n\n public var id:int;\n public var label:String;\n\n}\n\n[Bindable]\npublic class Type {\n\n public var id:int;\n public var label:String;\n\n}\n</code></pre>\n\n<p>We give these an ID and a label. This has two main advantages:</p>\n\n<ul>\n<li>if you want to change the labels, or translate your application, the logic doesn't break (as it would with your code)</li>\n<li>you can now use this class to store this data in a database</li>\n</ul>\n\n<p>Now we can create a collection of ShopItems:</p>\n\n<pre><code> var items:IList = new ArrayCollection();\n\n var material:Material = new Material();\n material.id = 123;\n material.label = 'Woven Acrylic';\n\n var type:Type = new Type();\n type.id = 456;\n type.label = 'Motorized Pro';\n\n var item:ShopItem = new ShopItem();\n item.id = 1;\n item.material = material;\n item.type = type;\n item.mysteriousId = 789;\n\n items.addItem(item);\n</code></pre>\n\n<p>We can now create the following method to replace your code:</p>\n\n<pre><code>private function findShopItem(material:Material, type:Type, mysteriousId:int):ShopItem {\n for each (var item:ShopItem in items) {\n if (item.material == material &amp;&amp;\n item.type == type &amp;&amp;\n item.mysteriousId == mysteriousId)\n return item;\n }\n\n return null;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Edit:</strong> I understand that this is the most difficult answer for you to get your head around, because it has a certain level of abstraction you're not accustomed to yet. It is also just meant to confront you with the concept of a data model and get you started. I think from here on you can do a few things:</p>\n\n<ul>\n<li>A data model and data binding between the view and the model is at the core of every Flex application. You should be able to find some decent tutorials on this concept.</li>\n<li>Or just read an entry-level book on Flex development; the first chapters usually cover data binding.</li>\n<li>Take a step back and think about your application only in terms of what it's supposed to do; then functionally design the views you will need to accomplish that functionality; create a data model; create the views (usually pure MXML); try to bind the data model to your views; feel free to ask questions as you go either here on StackOverflow</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T07:58:38.517", "Id": "19280", "Score": "1", "body": "I just noticed that Mark's and Maheshes answers are fairly similar in approach, except mine takes the abstraction one step further. Consider this situtation: you want to change the name 'Woven Acrylic' into something else at some point. With my approach you'll have to change that value once. With theirs, you may have to replace hundreds of values, which is more time consuming and more prone to errors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T02:19:55.210", "Id": "19321", "Score": "0", "body": "Hi thanks, I am going to read the link you posted, so you can understand a bit better, its an awning, the type is for the motor the awning uses the material is the fabric, and the mysteriousId is actually the size of the awning. The text boxs are were the user inputs what there looking for and then when they hit the button to get a price it runs that if statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T02:42:02.943", "Id": "19322", "Score": "0", "body": "I guess my issue with your code is I have no idea how to make that work, for each and every combination, am i typing more code and its just making it more stable? I really dont understand at all but it def sounds like the best way to go" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T09:00:54.683", "Id": "19328", "Score": "0", "body": "@JoshuaMiller I've added some \"where to go from here?\" info to my answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T07:44:36.907", "Id": "12028", "ParentId": "12022", "Score": "6" } }, { "body": "<p>I would create an XML or other file to look into, instead of writing all those content related conditions yourself. I think its better to separate content and logic in this case.</p>\n\n<pre><code>var xml:XML = \n &lt;items&gt;\n &lt;item&gt;\n &lt;ft&gt;Woven Acrylic&lt;/ft&gt;\n &lt;at&gt;Motorized Pro XL&lt;/at&gt;\n &lt;asf&gt;20&lt;/asf&gt;\n &lt;bap&gt;1509&lt;/bap&gt;\n &lt;/item&gt;\n &lt;item&gt;\n &lt;ft&gt;Traditonal Laminated&lt;/ft&gt;\n &lt;at&gt;Motorized&lt;/at&gt;\n &lt;asf&gt;10&lt;/asf&gt;\n &lt;bap&gt;1509&lt;/bap&gt;\n &lt;/item&gt;\n &lt;item&gt;\n &lt;ft&gt;Woven Acrylic&lt;/ft&gt;\n &lt;at&gt;Motorized Pro XL&lt;/at&gt;\n &lt;asf&gt;10&lt;/asf&gt;\n &lt;bap&gt;1047&lt;/bap&gt;\n &lt;/item&gt;\n &lt;item&gt;\n &lt;ft&gt;a&lt;/ft&gt;\n &lt;at&gt;b&lt;/at&gt;\n &lt;asf&gt;c&lt;/asf&gt;\n &lt;bap&gt;1047&lt;/bap&gt;\n &lt;/item&gt;\n &lt;/items&gt;;\n// etc..\n</code></pre>\n\n<p>Then I would find a node matching all content using a E4X expression. Basically there is one condition; just match 3 fields in the XML.</p>\n\n<pre><code>// convert to variables \nvar ftText:String = ft.text;\nvar atText:String = at.text;\nvar asfText:String = asf.text;\n\n// filter/find nodes\nvar resultNodes:XMLList = xml.item.(ft == ftText &amp;&amp; at == atText &amp;&amp; asf == asfText);\nif (resultNodes.length() == 1)\n{\n\n bap.text = resultNodes.bap.text();\n trace(\"Match found: \" + resultNodes.toXMLString());\n}\nelse if (resultNodes.length() &gt; 1)\n{\n trace(\"Multiple matches found: \" + resultNodes.toXMLString());\n}\nelse\n{\n trace(\"No matching node found\");\n}\n</code></pre>\n\n<p>In lot of cases it would be better to load the XML external, but for the example this will work too.</p>\n\n<p>Side note: you should refine the variable names.</p>\n\n<p><strong>More on E4X:</strong><br>\n<a href=\"http://joshblog.net/2007/05/08/methods-to-filter-data-with-e4x-in-flash-9/\" rel=\"nofollow\">http://joshblog.net/2007/05/08/methods-to-filter-data-with-e4x-in-flash-9/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T08:17:02.073", "Id": "19281", "Score": "0", "body": "spend few minutes to write an answer like yours but i wasn't fast enough : (" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T07:51:52.307", "Id": "12029", "ParentId": "12022", "Score": "4" } }, { "body": "<p>You need to <strong>store</strong> data properly to be able to use it efficiently. What you're doing there is storing all the data within an endless amount of <code>if()</code> statements.</p>\n\n<p>I would suggest storing everything as XML, but not knowing your experience level I'll avoid that solution.</p>\n\n<p>Something purely ActionScript that you can do is store your data in objects which are listed in an array, example:</p>\n\n<pre><code>// Define the array containing all data.\nvar dataArray:Array = [];\n\n// Add some objects to the array.\ndataArray.push({ ft: \"Woven Acrylic\", at: \"Motorized\", asf: \"14\", bap: \"1047\", ac: \"more data\" });\ndataArray.push({ ft: \"Traditonal Laminated\", at: \"Motorized\", asf: \"15\", bap: \"1307\", ac: \"more data\" });\n</code></pre>\n\n<p>Now you can create a function that finds and uses objects with relevant data:</p>\n\n<pre><code>function find(ft:String, at:String, asf:String):Object\n{\n for each(var i:Object in dataArray)\n {\n if(i.ft == ft &amp;&amp; i.at == at &amp;&amp; i.asf == asf)\n {\n return i;\n }\n }\n\n return null;\n}\n</code></pre>\n\n<p>And another function that will set the text fields like you're doing:</p>\n\n<pre><code>function setText(basedOn:Object):void\n{\n bap.text = basedOn.bap;\n tc_v.text = '$' + bap.text + basedOn.ac;\n}\n</code></pre>\n\n<p>Now you can simply do this for example:</p>\n\n<pre><code>setText(find(\"Traditonal Laminated\", \"Motorized\", \"15\"));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T08:48:44.313", "Id": "19282", "Score": "0", "body": "+1 Yeah, this works, too. But I still think this is too complicated. Check my answer - it can be done with a simple two-dimensional array, if you concatenate the strings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T10:52:23.687", "Id": "19283", "Score": "0", "body": "Side note: This could give a null reference error if no text is found, so an extra condition would be nice." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T08:05:56.247", "Id": "12030", "ParentId": "12022", "Score": "2" } }, { "body": "<p>Store your data in a XML, then query for a result.</p>\n\n<pre><code>var data:XML = &lt;data&gt;\n &lt;item attr=\"Woven Acrylic\"&gt;\n &lt;item attr=\"Motorized\"&gt;\n &lt;item attr=\"10\" value=\"1147\" /&gt;\n &lt;item attr=\"11\" value=\"1148\" /&gt;\n &lt;item attr=\"12\" value=\"1149\" /&gt;\n &lt;/item&gt;\n &lt;item attr=\"Motorized XL\"&gt;\n &lt;item attr=\"16\" value=\"1140\"/&gt;\n &lt;item attr=\"17\" value=\"1141\"/&gt;\n &lt;item attr=\"18\" value=\"1142\"/&gt;\n &lt;/item&gt;\n &lt;/item&gt;\n &lt;item attr=\"Traditonal Laminated\"&gt;\n &lt;item attr=\"Motorized\"&gt;\n &lt;item attr=\"17\" value=\"1143\"/&gt;\n &lt;item attr=\"18\" value=\"1144\"/&gt;\n &lt;item attr=\"19\" value=\"1145\"/&gt;\n &lt;/item&gt;\n &lt;/item&gt;\n &lt;/data&gt;;\n\n\nfunction extractValue(a:String, b:String, c:String):String {\n var queryRes:XMLList = data.item.(@attr == a).item.(@attr == b).item.(@attr == c).@value;\n if (queryRes.length() == 1) {\n return queryRes.toString();\n }\n return null;\n}\n\ntrace(extractValue(\"Woven Acrylic\", \"Motorized\", \"10\")); //1147\ntrace(extractValue(\"Woven Acrylic\", \"\", \"10\")); //null\ntrace(extractValue(\"Woven Acrylic\", \"Motorized XL\", \"18\")); //1142\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T08:07:45.230", "Id": "12031", "ParentId": "12022", "Score": "1" } }, { "body": "<p>Since your if-else statements follow a simple logic (ALL the strings are expected EQUAL to something you know), you can simply concatenate the values and use them as keys in a lookup table (for convenience, I created one for you, but this can and should be done at runtime):</p>\n\n<pre><code> private var items:Object = {\"Woven AcrylicMotorized10\": 1147, \"Woven AcrylicMotorized11\": 1217, \"Woven AcrylicMotorized12\": 1297, \"Woven AcrylicMotorized13\": 1343, \"Woven AcrylicMotorized14\": 1407, \"Woven AcrylicMotorized15\": 1467, \"Woven AcrylicMotorized16\": 1530, \"Woven AcrylicMotorized17\": 1587, \"Woven AcrylicMotorized18\": 1632, \"Woven AcrylicMotorized19\": 1709, \"Woven AcrylicMotorized20\": 1754, \"Woven AcrylicMotorized XL14\": 1490, \"Woven AcrylicMotorized XL15\": 1560, \"Woven AcrylicMotorized XL16\": 1636, \"Woven AcrylicMotorized XL17\": 1703, \"Woven AcrylicMotorized XL18\": 1758, \"Woven AcrylicMotorized XL19\": 1848, \"Woven AcrylicMotorized XL20\": 1903, \"Woven AcrylicMotorized Pro10\": 1247, \"Woven AcrylicMotorized Pro11\": 1317, \"Woven AcrylicMotorized Pro12\": 1397, \"Woven AcrylicMotorized Pro13\": 1443, \"Woven AcrylicMotorized Pro14\": 1507, \"Woven AcrylicMotorized Pro15\": 1567, \"Woven AcrylicMotorized Pro16\": 1603, \"Woven AcrylicMotorized Pro17\": 1687, \"Woven AcrylicMotorized Pro18\": 1732, \"Woven AcrylicMotorized Pro19\": 1823, \"Woven AcrylicMotorized Pro20\": 1878, \"Woven AcrylicMotorized Pro XL14\": 1509, \"Woven AcrylicMotorized Pro XL15\": 1660, \"Woven AcrylicMotorized Pro XL16\": 1736, \"Woven AcrylicMotorized Pro XL17\": 1803, \"Woven AcrylicMotorized Pro XL18\": 1858, \"Woven AcrylicMotorized Pro XL19\": 1962, \"Woven AcrylicMotorized Pro XL20\": 2027, \"Woven AcrylicOasis10 x 16\": 1305, \"Woven AcrylicVista10\": 927, \"Woven AcrylicVista11\": 997, \"Woven AcrylicVista12\": 1077, \"Woven AcrylicVista13\": 1123, \"Woven AcrylicVista14\": 1187, \"Woven AcrylicVista15\": 1247, \"Woven AcrylicVista16\": 1310, \"Woven AcrylicVista17\": 1367, \"Woven AcrylicVista18\": 1412, \"Traditonal LaminatedMotorized10\": 1047, \"Traditonal LaminatedMotorized11\": 1107, \"Traditonal LaminatedMotorized12\": 1167, \"Traditonal LaminatedMotorized13\": 1213, \"Traditonal LaminatedMotorized14\": 1257, \"Traditonal LaminatedMotorized15\": 1307, \"Traditonal LaminatedMotorized16\": 1360, \"Traditonal LaminatedMotorized17\": 1407, \"Traditonal LaminatedMotorized18\": 1452, \"Traditonal LaminatedMotorized Pro10\": 1147, \"Traditonal LaminatedMotorized Pro11\": 1207, \"Traditonal LaminatedMotorized Pro12\": 1267, \"Traditonal LaminatedMotorized Pro13\": 1313, \"Traditonal LaminatedMotorized Pro14\": 1357, \"Traditonal LaminatedMotorized Pro15\": 1407, \"Traditonal LaminatedMotorized Pro16\": 1460, \"Traditonal LaminatedMotorized Pro17\": 1507, \"Traditonal LaminatedMotorized Pro18\": 1552, \"Traditonal LaminatedVista10\": 827, \"Traditonal LaminatedVista11\": 887, \"Traditonal LaminatedVista12\": 947, \"Traditonal LaminatedVista13\": 993, \"Traditonal LaminatedVista14\": 1037, \"Traditonal LaminatedVista15\": 1087, \"Traditonal LaminatedVista16\": 1140, \"Traditonal LaminatedVista17\": 1187, \"Traditonal LaminatedVista18\": 1232};\n\n public function getUniqueId( ft:String, at:String, asf:String ):String {\n var searchString:String = ft+\"\"+at+\"\"+asf;\n return items.hasOwnProperty(searchString)? items[searchString] : \"0\";\n } \n</code></pre>\n\n<p>Just apply like this:</p>\n\n<pre><code>tc_v.text = '$' + getUniqueId( ft.text, at.text, asf.text) + Number(ac_.text)) \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T10:57:30.503", "Id": "19284", "Score": "0", "body": "I agree this is very concise, but I don't think it teaches good coding practice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:01:01.183", "Id": "19285", "Score": "0", "body": "What do you consider good coding practice? It works, it's very fast and short, and it doesn't require any additional class compilation. You should not overdo abstractions, unless they are useful - in this case, the problem is simple enough to just work with primitive values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:02:35.507", "Id": "19286", "Score": "0", "body": "I agree with you, though, that the variables names should speak for themselves - I only used OP's names to show how the solution relates to the original code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:04:00.343", "Id": "19287", "Score": "0", "body": "To make a point: http://en.wikipedia.org/wiki/YAGNI" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:16:04.153", "Id": "19288", "Score": "0", "body": "I understand your YAGNI point. Whether you're going to need it depends on the requirements of the application though. If we limit ourselves to just this example it is indeed a good solution. However if we imagine this is going to be part of a shopping application (which we could assume, because you wouldn't use Flex to make a simple form), then you _are_ going to need the abstraction." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:20:54.873", "Id": "19289", "Score": "0", "body": "It does not matter how the data got in there - OP asked about simplifying the if/else statement, and that's what I did. You can generate the search data *from* your data structures before you apply the search. But that wasn't part of the question, was it? Anyway, while thinking about this, I came up with an even better solution - using a lookup table." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:21:06.627", "Id": "19290", "Score": "0", "body": "Come to think of it, if fast and short is what you're after, you may as well create a Dictionary with `ft+\"\"+at+\"\"+asf` as the keys. No need to loop anymore." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:22:25.607", "Id": "19291", "Score": "0", "body": "@RIAstar Looks like we both thought about that at the same time ;)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T08:45:21.720", "Id": "12032", "ParentId": "12022", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T06:41:02.650", "Id": "12022", "Score": "3", "Tags": [ "actionscript-3", "actionscript" ], "Title": "How to simplify my else if statement" }
12022
<p>Here's an example of a logic structure I've refactored into something more complex on many occasions because I feel like it's wrong to have a side effect in a function that determines a yes/no answer to a question.</p> <p>If I were to break this into multiple functions I would add to the main logic to call another function that handles the found conflict.</p> <p>What is you opinion of logic like this? Should it be refactored?</p> <p>(also I welcome any/all code critiques)</p> <pre><code>namespace DirectAgents.SynchService.Commands { public class CreateCampaign : Command&lt;Campaign, bool&gt; { private IFactory&lt;DADatabase&gt; eom; public CreateCampaign(IFactory&lt;DADatabase&gt; eomDatabase) { this.eom = eomDatabase; } public override bool Execute(Campaign input) { bool result = false; using (var db = eom.Create()) { if (this.CanAdd(input)) { db.Campaigns.AddObject(input); Log("Saving new {0} [{1}].", input.GetType().Name, input.campaign_name); db.SaveChanges(); result = true; } } return result; } private bool CanAdd(Campaign campaign) { using (var db = eom.Create()) { var conflictingID = from c in db.Campaigns where (c.pid == campaign.pid) &amp;&amp; (c.campaign_name == campaign.campaign_name) select c.pid; bool conflictExists = (conflictingID.FirstOrDefault() == default(int)); if (conflictExists) { this.CampaignConflicts.Add(new CampaignConflict { Campaign = campaign, ConflictingId = conflictingID.First() }); } return (!conflictExists); } } [Dependency("CampaignConflicts")] public ICollection&lt;CampaignConflict&gt; CampaignConflicts { get; set; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T22:48:57.807", "Id": "19314", "Score": "0", "body": "Yes, I agree in that I think a side effect in a Yes/No method is not desirable." } ]
[ { "body": "<p>The method name <code>CanAdd</code> implies that it won't have side effects. Therefore you could mistake the method in the future as a read-only method, while it isn't. Also because the relationship between checking whether it can be added to list A and adding it to another list is not strongly related, I would advice to make CanAdd a method that doesn't make any changes.</p>\n\n<p>A better place to add the <code>campaign</code> to the conflicting list would be in <code>execute</code> or in a separate method called from <code>execute</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T20:40:30.410", "Id": "12043", "ParentId": "12036", "Score": "2" } }, { "body": "<p>I would personally separate the method as like Mark said it's having side effects as well as doing more than one thing.</p>\n\n<p>Based on your code provided maybe something like this. Each method hopefully does one thing and the Execute uses these as required:</p>\n\n<pre><code>namespace DirectAgents.SynchService.Commands\n{\n public class CreateCampaign : Command&lt;Campaign, bool&gt;\n {\n private IFactory&lt;DADatabase&gt; eom;\n public CreateCampaign(IFactory&lt;DADatabase&gt; eomDatabase)\n {\n this.eom = eomDatabase;\n }\n public override bool Execute(Campaign campaign)\n {\n bool result = true; // works unless told otherwise \n int conflictingID = GetConflictingID(campaign);\n\n if(ConflictExists(conflictingID))\n {\n AddConflict(campaign, conflictingID);\n\n // a conflict exists so we failed to execute this operation\n result = false;\n }\n else\n {\n CommitChanges(campaign); \n }\n\n return result;\n }\n\n private void CommitChanges(Campaign campaign)\n {\n using (var db = eom.Create())\n {\n db.Campaigns.AddObject(campaign);\n Log(\"Saving new {0} [{1}].\", campaign.GetType().Name, campaign.campaign_name);\n db.SaveChanges(); \n }\n }\n\n private void AddConflict(Campaign campaign,int conflictingID)\n {\n this.CampaignConflicts.Add(new CampaignConflict\n {\n Campaign = campaign,\n ConflictingId = conflictingID\n });\n }\n\n private bool ConflictExists(int conflictID)\n {\n return conflictID == default(int);\n }\n\n private int GetConflictingID(Campaign campaign)\n {\n using (var db = eom.Create())\n {\n var conflictingID = from c in db.Campaigns\n where (c.pid == campaign.pid) &amp;&amp; (c.campaign_name == campaign.campaign_name)\n select c.pid;\n\n return conflictingID.FirstOrDefault();\n }\n }\n\n [Dependency(\"CampaignConflicts\")]\n public ICollection&lt;CampaignConflict&gt; CampaignConflicts { get; set; }\n }\n} \n</code></pre>\n\n<p>One thing I was tossing up was whether to switch the order of the if statements in the Execute method to have the normal flow go though the commitchanges method. Not really sure though. </p>\n\n<p>Something like:</p>\n\n<pre><code>public override bool Execute(Campaign campaign)\n {\n bool result = true; // works unless told otherwise \n int conflictingID = GetConflictingID(campaign);\n\n if(ConflictDoesNotExist(conflictingID))\n {\n CommitChanges(campaign); \n }\n else\n {\n AddConflict(campaign, conflictingID);\n\n // a conflict exists so we failed to execute this operation\n result = false; \n }\n\n return result;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T22:25:08.700", "Id": "19347", "Score": "0", "body": "what do you think about `bool ConflictExists(out int conflictingID)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T22:36:57.933", "Id": "19348", "Score": "0", "body": "@AaronAnodide I personally probably wouldn't do do that, doesn't mean it's not an ok idea. My main reason is it's conveying that the method is doing more than one thing. Checking a conflict exists and getting that conflicting ID? Others might have an opinion on this though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T22:45:23.820", "Id": "12045", "ParentId": "12036", "Score": "2" } } ]
{ "AcceptedAnswerId": "12045", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T16:03:40.340", "Id": "12036", "Score": "3", "Tags": [ "c#" ], "Title": "Side effects in functions that find boolean conditions" }
12036
<p>I want to optimize the performance of this SQL query. If I populate this hashtable with one million keys the query will take around minute. How I can optimize this Java method for faster execution?</p> <pre><code>private HashMap&lt;String, Boolean&gt; selectedIds = new HashMap&lt;&gt;(); public void deleteSelectedIDs() throws SQLException { if (ds == null) { throw new SQLException(); } Connection conn = ds.getConnection(); if (conn == null) { throw new SQLException(); } PreparedStatement ps = null; ResultSet resultSet = null; try { conn.setAutoCommit(false); boolean committed = false; try { String sqlDeleteQuery = "DELETE FROM ACTIVESESSIONSLOG WHERE ASESSIONID = ?"; Set&lt;String&gt; keySet = selectedIds.keySet(); String[] keys = new String[]{}; keys = selectedIds.keySet().toArray(keys); ps = conn.prepareStatement(sqlDeleteQuery); for (int i = 0; i &lt; keys.length; i++) { if (selectedIds.get(keys[i]).booleanValue()) { ps.setString(1, keys[i]); ps.executeUpdate(); ps.clearParameters(); selectedIds.put(keys[i], false); //get(keys[i]) = false; } } conn.commit(); committed = true; //selectedIds.clear(); } finally { if (!committed) { conn.rollback(); } } } finally { ps.close(); conn.close(); } } private HashMap&lt;String, Boolean&gt; selectedIds = new HashMap&lt;&gt;(); public void deleteSelectedIDs() throws SQLException { if (ds == null) { throw new SQLException(); } Connection conn = ds.getConnection(); if (conn == null) { throw new SQLException(); } PreparedStatement ps = null; ResultSet resultSet = null; try { conn.setAutoCommit(false); boolean committed = false; try { String sqlDeleteQuery = "DELETE FROM ACTIVESESSIONSLOG WHERE ASESSIONID = ?"; Set&lt;String&gt; keySet = selectedIds.keySet(); String[] keys = new String[]{}; keys = selectedIds.keySet().toArray(keys); ps = conn.prepareStatement(sqlDeleteQuery); for (int i = 0; i &lt; keys.length; i++) { if (selectedIds.get(keys[i]).booleanValue()) { ps.setString(1, keys[i]); ps.executeUpdate(); ps.clearParameters(); selectedIds.put(keys[i], false); //get(keys[i]) = false; } } conn.commit(); committed = true; //selectedIds.clear(); } finally { if (!committed) { conn.rollback(); } } } finally { ps.close(); conn.close(); } } </code></pre>
[]
[ { "body": "<p>If you look at this in a profiler, I will bet that the most time is being used at this line:</p>\n\n<pre><code>ps.executeUpdate();\n</code></pre>\n\n<p>I would gather all strings to be deleted into one statement like:</p>\n\n<pre><code>DELETE FROM ACTIVESESSIONSLOG WHERE ASESSIONID IN ('A','B','C')\n</code></pre>\n\n<p>and send that 1 SQL statement instead of 1,000,000 statements.</p>\n\n<p>Second:</p>\n\n<p>instead of:</p>\n\n<pre><code> Set&lt;String&gt; keySet = selectedIds.keySet();\n String[] keys = new String[]{};\n keys = selectedIds.keySet().toArray(keys);\n</code></pre>\n\n<p>I would use an iterator:</p>\n\n<pre><code> Set&lt;String&gt; keySet = selectedIds.keySet();\n Iterator&lt;String&gt; iter = keySet.iterator();\n while(!iter.hasNext()) {\n String key = iter.next();\n //.. revise substituting key for keys[i]\n }\n</code></pre>\n\n<p>This avoids the need to copy all of those string references around. It might be worth it to simply operate on a <code>Set</code> of strings that only possesses members that are true if selectedIds is not used for other purposes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T17:23:12.010", "Id": "19303", "Score": "0", "body": "Thank you for the reply! The big problem is that I don't have exact number of the rows that I have to delete every time. Sometimes I might delete only 10 rows. How I can use one statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T17:24:14.740", "Id": "19304", "Score": "0", "body": "I tried to implement the iterator but I failed - something is missing. Would you show me the complete edited source code, please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T16:50:08.853", "Id": "19342", "Score": "2", "body": "Some databases (like oracle) have a maximum query length and I am pretty sure that sending one delete with 1.000.000 values in the `in` statement will hit that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T17:07:19.527", "Id": "12040", "ParentId": "12038", "Score": "1" } }, { "body": "<p>Per the other example - step 1 should be to get out your profiler.</p>\n\n<p>In any case - \nI suspect you would get significantly reduced round trip times by taking advantage of JDBC batching capability. Here's an example: <a href=\"http://www.tutorialspoint.com/jdbc/jdbc-batch-processing.htm\" rel=\"nofollow\">http://www.tutorialspoint.com/jdbc/jdbc-batch-processing.htm</a> (see the second one - using a prepared statement).</p>\n\n<p>In short - you create your DELETE prepared statement, drop the values into a batch, and then execute the batch in one go. Use a prepared statement to reduce parse time for the server.</p>\n\n<p>Depending on if you want to ramp up the complexity, you might want to split the rows into tasks and run them in parallel threads.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T22:13:13.437", "Id": "12044", "ParentId": "12038", "Score": "3" } } ]
{ "AcceptedAnswerId": "12044", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T16:41:34.977", "Id": "12038", "Score": "0", "Tags": [ "java", "optimization", "sql", "oracle", "jdbc" ], "Title": "How to optimize this SQL delete" }
12038
<p>I have this method inside a class that is responsible for setting up and executing a model:</p> <pre><code>public FlowJob PrepareAndScheduleFlowModelJob(string coordinates) { GeometryCoordinateString coordinateString = new GeometryCoordinateString(coordinates); DataSet intersectedWatershedsDataSet = FindIntersectingWatersheds(coordinateString); List&lt;string&gt; xCoords = new List&lt;string&gt;(); List&lt;string&gt; yCoords = new List&lt;string&gt;(); List&lt;string&gt; ascFiles = new List&lt;string&gt;(); string submitJobID = "fromServa" + new Random().Next().ToString(); ProcessWatershedResults(intersectedWatershedsDataSet, xCoords, yCoords, ascFiles); ScheduleFlowJob(xCoords, yCoords, ascFiles, submitJobID); return new FlowJob(submitJobID); } </code></pre> <p>It is a long running process so the client caller uses the <code>FlowJob</code> to poll status and get results. The client itself doesn't care about any of the intermediate data and only wants to specify the input location for the model to run. </p> <p>Every method that is called inside this method have their own unit tests already to ensure those work properly.</p> <p>I know I can write an integration test ensuring that the entire thing in fact works.</p> <p>I don't see anything here to unit test except that various methods are called. Any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T19:45:50.313", "Id": "19306", "Score": "0", "body": "This method seems small and clean. If you can write an integration test and it is easy to do, then do it. Otherwise, I would not over-test. You could be doing other productive things instead. If you discover a bug, then it would make sense to code a regression test against it. Otherwise, just assume that this will work until it breaks and move on." } ]
[ { "body": "<p>What is supposed to happen when the <code>coordinates</code> parameter is null? And when it is an empty string? And when it does not properly represent a coordinate? You can create unit tests that test for these kind of situations, for example.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T06:42:55.503", "Id": "12055", "ParentId": "12039", "Score": "1" } }, { "body": "<p>As far as testing the method itself:<br/>\nIn most testing frameworks, you would create parameterized tests that provide the inputs and expected outputs.</p>\n\n<p>NUnit example below (omitting setup code to build ObjectUnderTest):</p>\n\n<pre><code>[TestCaseSource (\"GetPrepTestData\")]\npublic void TestPrepareAndScheduleFlowJob (string inputCoords, FlowJob expectedJob)\n{\n var outputJob = ObjectUnderTest.PrepareAndScheduleFlowModelJob (inputCoords);\n Assert.That (outputJob, Is.EqualTo (expectedJob));\n}\n\nprivate static IEnumerable&lt;TestCaseData&gt; GetPrepTestData ()\n{\n yield return new TestCaseData (\"some coord string\", new FlowJob (expectedId)).SetName (\"first test\");\n yield break;\n}\n</code></pre>\n\n<p>The private method calls can largely be ignored unless they have external dependencies, in which case you should add some injection and mocking with your parent object. This will allow you to ensure your private method calls inside PrepareAndScheduleFlowJob execute quickly and return expected results.</p>\n\n<p><em>edit:<br/>\nThe above solution requires that you override Object.Equals. You could change the assert to a set of asserts for testing equality, but Object.Equals overrides are preferable, as it will cover FlowJob and any future/current subclasses in addition to providing equality check capability to anyone using the class. Additionally, in a framework like NUnit, overriding Object.ToString is highly recommended, as many test frameworks will call ToString when printing assert failures, and having something more than just the type name is useful when assessing why your tests may have failed.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T18:53:38.607", "Id": "12073", "ParentId": "12039", "Score": "3" } }, { "body": "<p>The tricky thing is that function has a lot of external dependencies, which makes testing that one very specific function very difficult. The test has to rely on GeometryCoordinateString, FindIntersectingWatersheds, ProcessWatershedResults, ScheduleFlowJob, and depending on your business logic, FlowJob working correctly. Changing the underlying logic in any of those objects/methods will cause the test for PrepareAndScheduleFlowModelJob to fail. Obviously, I am not familiar with your business rules, or what the methods/objects do, but here is my best stab at making the method more testable.</p>\n\n<pre><code>public interface IGeometryCoordinateString\n{\n GeometryCoordinateString GetCoordinateString(string coordinates);\n}\n\npublic interface IIntersectingWatersheds\n{\n DataSet FindIntersectingWatersheds(GeometryCoordinateString coordinateString); \n}\n\npublic interface IProcessWatershedResults\n{\n void ProcessWaterShedResults(DataSet intersectedWatershedDataSet, IList&lt;string&gt; xCoords, IList&lt;string&gt; yCoords, IList&lt;string&gt; ascFiles);\n}\n\npublic interface IScheduleFlowJob\n{\n void ScheduleFlowJob(IList&lt;string&gt; xCoords, IList&lt;string&gt; yCoords, IList&lt;string&gt; ascFiles, string submitJobId);\n}\n\npublic Class PrepareFlowJob\n{\n private readonly IGeometryCoordinateString m_CoordinateString;\n private readonly IIntersectingWatersheds m_IntersectingWatersheds;\n private readonly IProcessWatershedResults m_ProcessWatershedResults;\n private readonly IScheduleFlowJob m_ScheduleFlowJob;\n\n Public PrepareFlowJob(\n IGeometryCoordinateString coordinateString, \n IIntersectingWatersheds intersectingWaterSheds,\n IProcessWatershedResults processWatershedResults,\n IScheduleFlowJob scheduleFlowJob)\n {\n m_CoordinateString = coordinateString;\n m_IntersectingWatersheds = intersectingWaterSheds;\n m_ProcessWatershedResults = processWatershedResults;\n m_ScheduleFlowJob = scheduleFlowJob;\n }\n\n public FlowJob PrepareAndScheduleFlowModelJob(string coordinates)\n {\n GeometryCoordinateString coordinateString = m_CoordinateString.GetCoordinateString(coordinates); \n DataSet intersectedWatershedsDataSet = \n m_IntersectingWatersheds.FindIntersectingWatersheds(coordinateString);\n\n List&lt;string&gt; xCoords = new List&lt;string&gt;();\n List&lt;string&gt; yCoords = new List&lt;string&gt;();\n List&lt;string&gt; ascFiles = new List&lt;string&gt;();\n string submitJobID = \"fromServa\" + new Random().Next().ToString();\n\n m_ProcessWatershedResults.ProcessWatershedResults(intersectedWatershedsDataSet, xCoords, yCoords, ascFiles);\n m_ProcessWatershedResults.ScheduleFlowJob(xCoords, yCoords, ascFiles, submitJobID);\n\n return new FlowJob(submitJobID);\n }\n\n}\n</code></pre>\n\n<p>Then using a mocking framework like Moq you can some stubs.</p>\n\n<pre><code> [TestMethod]\n public void Test_PrepareAndScheduleFlowModelJob()\n {\n var mockCoordinateString = new Mock&lt;IGeometryCoordinateString&gt;();\n var mockIntesection = new Mock&lt;IIntersectingWatersheds&gt;();\n var mockWatershedResults = new Mock&lt;IProcessWatershedResults&gt;();\n var mockSchedule = new Mock&lt;IScheduleFlowJob&gt;();\n\n var itemUnderTest = new PrepareFlowJob(mockCoordinateString.Object, mockIntersection.Object, mockWatershedResults.Object, mockSchedule.Object);\n\n var expected = new FlowJob(string.empty);\n FlowJob actual = PrepareAndScheduleFlowModelJob(\"something\");\n\n Assert.AreEqual(expected, actual);\n}\n</code></pre>\n\n<p>In your production code you could use a factory to implement the necessary interfaces for the PrepareFlowJob object. The idea is to separate out everything into what it is responsible for, this way the sample test should never change, now no matter how you change logic for something like FindIntersectingWatersheds. Because all your passing in is the interface. The only reason the test should change is when the business logic for the method PrepareAndScheduleFlowModelJob changes. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T01:28:39.870", "Id": "12565", "ParentId": "12039", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T16:54:06.830", "Id": "12039", "Score": "2", "Tags": [ "c#", "unit-testing" ], "Title": "How to unit test this method?" }
12039
<p>What's the fastest (quality is important too, but a little less important) way to compare two strings?</p> <p>I'm looking for the most efficient way to compare two strings. Some of the strings I'm comparing can be over 5000 characters long. I'm comparing a list of about 80 strings with another list of about 200 strings. It takes forever, even when I'm threading it.</p> <p>I'm using the <a href="http://commons.apache.org/lang/api/org/apache/commons/lang3/StringUtils.html#getLevenshteinDistance%28java.lang.CharSequence,%20java.lang.CharSequence%29" rel="nofollow"><code>StringUtils.getLevenshteinDistance(String s, String t)</code></a> method from Apache Commons. My method follows. Is there a better way to do this?</p> <pre><code>private void compareMe() { List&lt;String&gt; compareStrings = MainController.getInstance().getCompareStrings(); for (String compare : compareStrings) { int levenshteinDistance = StringUtils.getLevenshteinDistance(me, compare, bestScore); //bestScore begins at 999999999 :) if (bestScore &gt; levenshteinDistance &amp;&amp; levenshteinDistance &gt; -1) { bestScore = levenshteinDistance; //global variable bestString = compare; //global variable } } } </code></pre> <p>Here's a sample of two strings which should have a good score:</p> <p>String 1:</p> <blockquote> <pre><code>SELECT CORP_VENDOR_NAME as "Corporate Vendor Name", CORP_VENDOR_REF_ID as "Reference ID", MERCHANT_ID as "Merchant ID", VENDOR_CITY as "City", VENDOR_STATE as "State", VENDOR_ZIP as "Zip", VENDOR_COUNTRY as "Country", REMIT_VENDOR_NAME as "Remit Name", REMIT_VENDOR_REF_ID as " Remit Reference ID", VENDOR_PRI_UNSPSC_CODE as "Primary UNSPSC" FROM DSS_FIN_USER.ACQ_VENDOR_DIM WHERE VENDOR_REFERENCE_ID in (SELECT distinct CORP_VENDOR_REF_ID FROM DSS_FIN_USER.ACQ_VENDOR_DIM WHERE CORP_VENDOR_REF_ID = '${request.corp_vendor_id};') </code></pre> </blockquote> <p>String 2:</p> <blockquote> <pre><code>SELECT CORP_VENDOR_NAME as "Corporate Vendor Name", CORP_VENDOR_REF_ID as "Reference ID", MERCHANT_ID as "Merchant ID", VENDOR_CITY as "City", VENDOR_STATE as "State", VENDOR_ZIP as "Zip", VENDOR_COUNTRY as "Country", REMIT_VENDOR_NAME as "Remit Name", REMIT_VENDOR_REF_ID as " Remit Reference ID", VENDOR_PRI_UNSPSC_CODE as "Primary UNSPSC" FROM DSS_FIN_USER.ACQ_VENDOR_DIM WHERE VENDOR_REFERENCE_ID in (SELECT distinct CORP_VENDOR_REF_ID FROM DSS_FIN_USER.ACQ_VENDOR_DIM WHERE CORP_VENDOR_REF_ID = 'ACQ-169013') </code></pre> </blockquote> <p>You'll notice the only difference is the <code>'${request.corp_vendor_id};'</code> at the end of the string. This would cause it to have a score of <code>26</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T20:03:20.917", "Id": "19307", "Score": "2", "body": "If you really need to compare 80 strings with 200 strings for a total of 80*200 = 10000 comparisons, I see no way around it (try to use C?). But are you sure you need to do that all in one go? What problem are you trying to solve?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T20:32:30.007", "Id": "19308", "Score": "0", "body": "Do you need to calculate the score or looking for exact match is enough?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T20:52:55.270", "Id": "19309", "Score": "0", "body": "I need the closest match." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T21:52:34.243", "Id": "19311", "Score": "0", "body": "Is Levenshtein the only algorithm you can use?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T21:56:36.453", "Id": "19312", "Score": "0", "body": "No, I'd be happy to use another one if it's faster" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T20:44:26.047", "Id": "19344", "Score": "1", "body": "Comparing two strings of 10 and 100 characters Levensthein does a full evaluation, but one can easily short cut the evaluation above some threshhold, say distance > 10, and do some heuristics like difference in string length." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-10T13:17:18.263", "Id": "361834", "Score": "0", "body": "I faced a similar problem and found out about Q-grams in the answer by Baxter on [this post](https://stackoverflow.com/questions/5859561/getting-the-closest-string-match). He has a link to a video by Prof. Dr Hannah Bast which is really good." } ]
[ { "body": "<p>A possible suggestions. By looking at your data, I see that the difference between the strings may be small.</p>\n\n<p>Since Levenshtein distance is a costly metric, it may be profitable to compute some other easy metric such that it is not too different from what may be obtained from Levenshtein metric, and use it to presort the arrays.</p>\n\n<p>Once you have presorted them, merge the arrays together, and find the neighbors with in a delta range. For these, you can compute the Levenshtein distance and verify.</p>\n\n<p>Possible metrics to use for pre-sorting include</p>\n\n<ul>\n<li>frequency count of letters,</li>\n<li>string length</li>\n<li>lexicographical ordering</li>\n</ul>\n\n<p>etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T23:49:14.003", "Id": "12047", "ParentId": "12042", "Score": "2" } }, { "body": "<p>The painless solutiuon is to use the fastest levenstein distance algorithm :) For example extracted from GWT! I've created two 5 KB strings using your example, load them and produce 16000 calculations. Done in <strong>3 seconds</strong> only. The source:</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\n\npublic class Main {\n\nprivate static String readString(String filename) throws IOException {\n StringBuilder result = new StringBuilder();\n String temp;\n BufferedReader in = new BufferedReader(new FileReader(filename));\n while ((temp = in.readLine()) != null) result.append(temp);\n return result.toString();\n}\n\npublic static void main(String[] args) throws IOException {\n\n String line1 = readString(args[0]);\n String line2 = readString(args[1]);\n GeneralEditDistance ed = GeneralEditDistances.getLevenshteinDistance(line1);\n\n long time = System.currentTimeMillis();\n int best = Integer.MAX_VALUE;\n for (int i = 0; i &lt; 80*200; i++) {\n best = Math.min(best, ed.getDistance(line2, best));\n }\n System.out.println(\"Best distance = \" + best + \" Total time (ms): \" + (System.currentTimeMillis() - time));\n}}\n\nabstract class CharIndex {\n\nstatic class FullHash extends CharIndex {\n\n static class Char {\n char c;\n\n @Override\n public boolean equals(Object x) {\n return (x != null) &amp;&amp; (((Char) x).c == this.c);\n }\n\n @Override\n public int hashCode() {\n return c;\n }\n\n @Override\n public String toString() {\n return \"'\" + c + \"'\";\n }\n }\n\n static final int NULL_ELEMENT = 0;\n protected int lastUsed = NULL_ELEMENT;\n final java.util.HashMap&lt;Char, Integer&gt; map;\n\n FullHash(CharSequence s) {\n int len = s.length();\n int power = Integer.highestOneBit(len);\n\n map = new java.util.HashMap&lt;Char, Integer&gt;(\n power &lt;&lt; ((power == len) ? 1 : 2));\n\n Char test = new Char(); /* (re)used for lookup */\n for (int i = 0; i &lt; s.length(); i++) {\n test.c = s.charAt(i);\n if (map.get(test) == null) {\n map.put(test, new Integer(++lastUsed));\n test = new Char();\n }\n }\n }\n\n @Override\n public int lookup(char c) {\n final Char lookupTest = new Char();\n lookupTest.c = c;\n Integer result = map.get(lookupTest);\n return (result != null) ? result.intValue() : 0;\n }\n\n @Override\n public int[] map(CharSequence s, int[] mapped) {\n /* Create one mutable Char, and reuse it for all lookups */\n final Char lookupTest = new Char();\n\n int len = s.length();\n if (mapped.length &lt; len) {\n mapped = new int[len];\n }\n\n for (int i = 0; i &lt; len; i++) {\n lookupTest.c = s.charAt(i);\n Integer result = map.get(lookupTest);\n mapped[i] = (result != null) ? result.intValue() : NULL_ELEMENT;\n }\n return mapped;\n }\n\n @Override\n public int nullElement() {\n return NULL_ELEMENT;\n }\n\n @Override\n public int size() {\n return lastUsed + 1;\n }\n}\n\nstatic class Masked extends CharIndex {\n static final int SIZE = 0x100;\n static final int MASK = (SIZE - 1);\n static final int NULL_ELEMENT = SIZE;\n\n static Masked generate(CharSequence s) {\n char[] contains = new char[SIZE];\n contains[0] = (char) 1;\n for (int i = 0; i &lt; s.length(); i++) {\n char c = s.charAt(i);\n int index = c &amp; MASK;\n if (contains[index] != c) {\n if ((contains[index] &amp; MASK) == index) {\n return null;\n }\n contains[index] = c;\n }\n }\n return new Masked(contains);\n }\n\n final char[] contains;\n\n private Masked(char[] contains) {\n this.contains = contains;\n }\n\n @Override\n public int lookup(char c) {\n int index = c &amp; MASK;\n return (c == contains[index]) ? index : NULL_ELEMENT;\n }\n\n @Override\n public int[] map(CharSequence s, int[] mapped) {\n int len = s.length();\n if (mapped.length &lt; len) {\n mapped = new int[len];\n }\n for (int i = 0; i &lt; len; i++) {\n char c = s.charAt(i);\n int index = c &amp; MASK;\n mapped[i] = (c == contains[index]) ? index : NULL_ELEMENT;\n }\n return mapped;\n }\n\n @Override\n public int nullElement() {\n return NULL_ELEMENT;\n }\n\n @Override\n public int size() {\n return NULL_ELEMENT + 1;\n }\n}\n\nstatic class Straight extends CharIndex {\n static final int MAX = 0x80;\n static final int MASK = ~(MAX - 1);\n static final int NULL_ELEMENT = MAX;\n\n static Straight generate(CharSequence s) {\n for (int i = 0; i &lt; s.length(); i++) {\n if ((s.charAt(i) &amp; MASK) != 0) {\n return null;\n }\n }\n\n return new Straight();\n }\n\n private Straight() {\n }\n\n @Override\n public int lookup(char c) {\n return ((c &amp; MASK) == 0) ? c : NULL_ELEMENT;\n }\n\n @Override\n public int[] map(CharSequence s, int[] mapped) {\n int len = s.length();\n if (mapped.length &lt; len) {\n mapped = new int[len];\n }\n for (int i = 0; i &lt; len; i++) {\n char c = s.charAt(i);\n mapped[i] = ((c &amp; MASK) == 0) ? c : NULL_ELEMENT;\n }\n return mapped;\n }\n\n @Override\n public int nullElement() {\n return NULL_ELEMENT;\n }\n\n @Override\n public int size() {\n return NULL_ELEMENT + 1;\n }\n}\n\npublic static CharIndex getInstance(CharSequence s) {\n CharIndex result;\n\n if ((result = Straight.generate(s)) != null) {\n return result;\n }\n\n if ((result = Masked.generate(s)) != null) {\n return result;\n }\n\n return new FullHash(s);\n}\n\npublic abstract int lookup(char c);\n\npublic abstract int[] map(CharSequence s, int[] mapped);\n\npublic abstract int nullElement();\n\npublic abstract int size();\n}\n\n\ninterface GeneralEditDistance {\n\nGeneralEditDistance duplicate();\n\nint getDistance(CharSequence target, int limit);\n\n}\n\n\nclass GeneralEditDistances {\n\nprivate static class Levenshtein implements GeneralEditDistance {\n private ModifiedBerghelRoachEditDistance berghel;\n private MyersBitParallelEditDistance myers;\n private final CharSequence pattern;\n private final int patternLength;\n\n private Levenshtein(CharSequence pattern) {\n this.pattern = pattern;\n this.patternLength = pattern.length();\n }\n\n public GeneralEditDistance duplicate() {\n Levenshtein dup = new Levenshtein(pattern);\n if (this.myers != null) {\n dup.myers = (MyersBitParallelEditDistance) this.myers.duplicate();\n }\n return dup;\n }\n\n public int getDistance(CharSequence target, int limit) {\n if (limit &lt;= 1) {\n return limit == 0 ?\n (pattern.equals(target) ? 0 : 1) :\n atMostOneError(pattern, target);\n }\n if ((patternLength &gt; 64)\n &amp;&amp; (limit &lt; (target.length() / 10))) {\n if (berghel == null) {\n berghel = ModifiedBerghelRoachEditDistance.getInstance(pattern);\n }\n return berghel.getDistance(target, limit);\n }\n\n if (myers == null) {\n myers = MyersBitParallelEditDistance.getInstance(pattern);\n }\n\n return myers.getDistance(target, limit);\n }\n}\n\npublic static int atMostOneError(CharSequence s1, CharSequence s2) {\n int s1Length = s1.length();\n int s2Length = s2.length();\n int errors = 0; /* running count of edits required */\n\n switch (s2Length - s1Length) {\n /*\n * Strings are the same length. No single insert/delete is possible;\n * at most one substitution can be present.\n */\n case 0:\n for (int i = 0; i &lt; s2Length; i++) {\n if ((s2.charAt(i) != s1.charAt(i)) &amp;&amp; (errors++ != 0)) {\n break;\n }\n }\n return errors;\n\n case 1: /* s2Length &gt; s1Length */\n for (int i = 0; i &lt; s1Length; i++) {\n if (s2.charAt(i) != s1.charAt(i)) {\n for (; i &lt; s1Length; i++) {\n if (s2.charAt(i + 1) != s1.charAt(i)) {\n return 2;\n }\n }\n return 1;\n }\n }\n return 1;\n\n /* Same as above case, with strings reversed */\n case -1: /* s1Length &gt; s2Length */\n for (int i = 0; i &lt; s2Length; i++) {\n if (s2.charAt(i) != s1.charAt(i)) {\n for (; i &lt; s2Length; i++) {\n if (s2.charAt(i) != s1.charAt(i + 1)) {\n return 2;\n }\n }\n return 1;\n }\n }\n return 1;\n\n /* Edit distance is at least difference in lengths; more than 1 here. */\n default:\n return 2;\n }\n}\n\npublic static GeneralEditDistance\ngetLevenshteinDistance(CharSequence pattern) {\n return new Levenshtein(pattern);\n}\n\nprivate GeneralEditDistances() {\n}\n}\n\nclass ModifiedBerghelRoachEditDistance implements GeneralEditDistance {\n\nprivate static final int[] EMPTY_INT_ARRAY = new int[0];\n\npublic static ModifiedBerghelRoachEditDistance\ngetInstance(CharSequence pattern) {\n return getInstance(pattern.toString());\n}\n\npublic static ModifiedBerghelRoachEditDistance\ngetInstance(String pattern) {\n return new ModifiedBerghelRoachEditDistance(pattern.toCharArray());\n}\n\nprivate int[] currentLeft = EMPTY_INT_ARRAY;\n\nprivate int[] currentRight = EMPTY_INT_ARRAY;\n\nprivate int[] lastLeft = EMPTY_INT_ARRAY;\n\nprivate int[] lastRight = EMPTY_INT_ARRAY;\n\nprivate final char[] pattern;\n\nprivate int[] priorLeft = EMPTY_INT_ARRAY;\n\nprivate int[] priorRight = EMPTY_INT_ARRAY;\n\nprivate ModifiedBerghelRoachEditDistance(char[] pattern) {\n this.pattern = pattern;\n}\n\npublic ModifiedBerghelRoachEditDistance duplicate() {\n return new ModifiedBerghelRoachEditDistance(pattern);\n}\n\npublic int getDistance(CharSequence targetSequence, int limit) {\n final int targetLength = targetSequence.length();\n\n final int main = pattern.length - targetLength;\n int distance = Math.abs(main);\n if (distance &gt; limit) {\n /* More than we wanted. Give up right away */\n return Integer.MAX_VALUE;\n }\n\n final char[] target = new char[targetLength];\n for (int i = 0; i &lt; targetLength; i++) {\n target[i] = targetSequence.charAt(i);\n }\n if (main &lt;= 0) {\n ensureCapacityRight(distance, false);\n for (int j = 0; j &lt;= distance; j++) {\n lastRight[j] = distance - j - 1; /* Make diagonal -k start in row k */\n priorRight[j] = -1;\n }\n } else {\n ensureCapacityLeft(distance, false);\n for (int j = 0; j &lt;= distance; j++) {\n lastLeft[j] = -1; /* Make diagonal +k start in row 0 */\n priorLeft[j] = -1;\n }\n }\n\n boolean even = true;\n\n while (true) {\n\n int offDiagonal = (distance - main) / 2;\n ensureCapacityRight(offDiagonal, true);\n\n if (even) {\n lastRight[offDiagonal] = -1;\n }\n\n int immediateRight = -1;\n for (; offDiagonal &gt; 0; offDiagonal--) {\n currentRight[offDiagonal] = immediateRight = computeRow(\n (main + offDiagonal),\n (distance - offDiagonal),\n pattern,\n target,\n priorRight[offDiagonal - 1],\n lastRight[offDiagonal],\n immediateRight);\n }\n\n offDiagonal = (distance + main) / 2;\n ensureCapacityLeft(offDiagonal, true);\n\n if (even) {\n lastLeft[offDiagonal] = (distance - main) / 2 - 1;\n }\n\n int immediateLeft = even ? -1 : (distance - main) / 2;\n\n for (; offDiagonal &gt; 0; offDiagonal--) {\n currentLeft[offDiagonal] = immediateLeft = computeRow(\n (main - offDiagonal),\n (distance - offDiagonal),\n pattern, target,\n immediateLeft,\n lastLeft[offDiagonal],\n priorLeft[offDiagonal - 1]);\n }\n\n int mainRow = computeRow(main, distance, pattern, target,\n immediateLeft, lastLeft[0], immediateRight);\n\n if ((mainRow == targetLength) || (++distance &gt; limit) || (distance &lt; 0)) {\n break;\n }\n\n /* The [0] element goes to both sides. */\n currentLeft[0] = currentRight[0] = mainRow;\n\n /* Rotate rows around for next round: current=&gt;last=&gt;prior (=&gt;current) */\n int[] tmp = priorLeft;\n priorLeft = lastLeft;\n lastLeft = currentLeft;\n currentLeft = priorLeft;\n\n tmp = priorRight;\n priorRight = lastRight;\n lastRight = currentRight;\n currentRight = tmp;\n\n /* Update evenness, too */\n even = !even;\n }\n\n return distance;\n}\n\nprivate int computeRow(int k, int p, char[] a, char[] b,\n int knownLeft, int knownAbove, int knownRight) {\n assert (Math.abs(k) &lt;= p);\n assert (p &gt;= 0);\n\n int t;\n if (p == 0) {\n t = 0;\n } else {\n t = Math.max(Math.max(knownAbove, knownRight) + 1, knownLeft);\n }\n\n int tmax = Math.min(b.length, (a.length - k));\n\n while ((t &lt; tmax) &amp;&amp; b[t] == a[t + k]) {\n t++;\n }\n\n return t;\n}\n\nprivate void ensureCapacityLeft(int index, boolean copy) {\n if (currentLeft.length &lt;= index) {\n index++;\n priorLeft = resize(priorLeft, index, copy);\n lastLeft = resize(lastLeft, index, copy);\n currentLeft = resize(currentLeft, index, false);\n }\n}\n\nprivate void ensureCapacityRight(int index, boolean copy) {\n if (currentRight.length &lt;= index) {\n index++;\n priorRight = resize(priorRight, index, copy);\n lastRight = resize(lastRight, index, copy);\n currentRight = resize(currentRight, index, false);\n }\n}\n\nprivate int[] resize(int[] array, int size, boolean copy) {\n int[] result = new int[size];\n if (copy) {\n System.arraycopy(array, 0, result, 0, array.length);\n }\n return result;\n}\n}\n\nabstract class MyersBitParallelEditDistance\n implements GeneralEditDistance, Cloneable {\n\nstatic class Empty extends MyersBitParallelEditDistance {\n Empty(CharSequence s) {\n super(s);\n }\n\n @Override\n public GeneralEditDistance duplicate() {\n return this; /* thread-safe */\n }\n\n @Override\n public int getDistance(CharSequence s, int k) {\n return s.length();\n }\n}\n\nstatic class Multi extends MyersBitParallelEditDistance {\n int count;\n final int lastBitPosition;\n final int[][] positions;\n int[] verticalNegativesReusable;\n int[] verticalPositivesReusable;\n final int wordMask = (-1 &gt;&gt;&gt; 1);\n final int wordSize = Integer.SIZE - 1;\n\n Multi(CharSequence s) {\n super(s);\n count = (m + wordSize - 1) / wordSize;\n positions = PatternBitmap.map(s, idx, new int[idx.size()][], wordSize);\n lastBitPosition = (1 &lt;&lt; ((m - 1) % wordSize));\n perThreadInit();\n }\n\n @Override\n public int getDistance(CharSequence s, int k) {\n indices = idx.map(s, indices);\n\n int[] verticalPositives = verticalPositivesReusable;\n java.util.Arrays.fill(verticalPositives, wordMask);\n int[] verticalNegatives = verticalNegativesReusable;\n java.util.Arrays.fill(verticalNegatives, 0);\n\n int distance = m;\n int len = s.length();\n\n int maxMisses = k + len - m;\n if (maxMisses &lt; 0) {\n maxMisses = Integer.MAX_VALUE;\n }\n\n outer:\n for (int j = 0; j &lt; len; j++) {\n int[] position = positions[indices[j]];\n\n int sum = 0;\n int horizontalPositiveShift = 1;\n int horizontalNegativeShift = 0;\n\n for (int i = 0; i &lt; count; i++) {\n int verticalNegative = verticalNegatives[i];\n int patternMatch = (position[i] | verticalNegative);\n int verticalPositive = verticalPositives[i];\n sum = (verticalPositive &amp; patternMatch)\n + (verticalPositive) + (sum &gt;&gt;&gt; wordSize);\n int diagonalZero = ((sum &amp; wordMask) ^ verticalPositive)\n | patternMatch;\n int horizontalPositive = (verticalNegative\n | ~(diagonalZero | verticalPositive));\n int horizontalNegative = diagonalZero &amp; verticalPositive;\n\n if (i == (count - 1)) { /* only last bit in last word */\n if ((horizontalNegative &amp; lastBitPosition) != 0) {\n distance--;\n } else if ((horizontalPositive &amp; lastBitPosition) != 0) {\n distance++;\n if ((maxMisses -= 2) &lt; 0) {\n break outer;\n }\n } else if (--maxMisses &lt; 0) {\n break outer;\n }\n }\n\n horizontalPositive = ((horizontalPositive &lt;&lt; 1)\n | horizontalPositiveShift);\n horizontalPositiveShift = (horizontalPositive &gt;&gt;&gt; wordSize);\n\n horizontalNegative = ((horizontalNegative &lt;&lt; 1)\n | horizontalNegativeShift);\n horizontalNegativeShift = (horizontalNegative &gt;&gt;&gt; wordSize);\n\n verticalPositives[i] = (horizontalNegative\n | ~(diagonalZero | horizontalPositive))\n &amp; wordMask;\n verticalNegatives[i] = (diagonalZero &amp; horizontalPositive) &amp; wordMask;\n }\n }\n return distance;\n }\n\n @Override\n protected void perThreadInit() {\n super.perThreadInit();\n verticalPositivesReusable = new int[count];\n verticalNegativesReusable = new int[count];\n }\n}\n\nstatic class TYPEint/*WORD*/ extends MyersBitParallelEditDistance {\n final int/*WORD*/ lastBitPosition;\n final int/*WORD*/[] map;\n\n @SuppressWarnings(\"cast\")\n TYPEint/*WORD*/(CharSequence s) {\n super(s);\n /* Precompute bitmaps for this pattern */\n map = PatternBitmap.map(s, idx, new int/*WORD*/[idx.size()]);\n /* Compute the bit that represents a change in the last row */\n lastBitPosition = (((int/*WORD*/) 1) &lt;&lt; (m - 1));\n }\n\n @Override\n public int getDistance(CharSequence s, int k) {\n int len = s.length();\n\n /* Quick check based on length */\n if (((len - m) &gt; k) || ((m - len) &gt; k)) {\n return k + 1;\n }\n\n /* Map characters to their integer positions in the bitmap array */\n indices = idx.map(s, indices);\n\n /* Initially, vertical change is all positive (none negative) */\n int/*WORD*/ verticalPositive = -1;\n int/*WORD*/ verticalNegative = 0;\n int distance = m;\n\n /* We can only miss the \"distance--\" below this many times: */\n int maxMisses = k + len - m;\n if (maxMisses &lt; 0) {\n maxMisses = Integer.MAX_VALUE;\n }\n\n for (int j = 0; j &lt; len; j++) {\n /* Where is diagonal zero: matches, or prior VN; plus recursion */\n int/*WORD*/ diagonalZero = map[indices[j]] | verticalNegative;\n diagonalZero |= (((diagonalZero &amp; verticalPositive) + verticalPositive)\n ^ verticalPositive);\n\n /* Compute horizontal changes */\n int/*WORD*/ horizontalPositive = verticalNegative\n | ~(diagonalZero | verticalPositive);\n int/*WORD*/ horizontalNegative = diagonalZero &amp; verticalPositive;\n\n /* Update final distance based on horizontal changes */\n if ((horizontalNegative &amp; lastBitPosition) != 0) {\n distance--;\n } else if ((horizontalPositive &amp; lastBitPosition) != 0) {\n distance++;\n if ((maxMisses -= 2) &lt; 0) {\n break;\n }\n } else if (--maxMisses &lt; 0) {\n break;\n }\n\n /* Shift Hs to next row, compute new Vs analagously to Hs above */\n horizontalPositive = (horizontalPositive &lt;&lt; 1) | 1;\n verticalPositive = (horizontalNegative &lt;&lt; 1)\n | ~(diagonalZero | horizontalPositive);\n verticalNegative = diagonalZero &amp; horizontalPositive;\n }\n return distance;\n }\n}\n\nstatic class TYPElong/*WORD*/ extends MyersBitParallelEditDistance {\n final long/*WORD*/ lastBitPosition;\n final long/*WORD*/[] map;\n\n TYPElong/*WORD*/(CharSequence s) {\n super(s);\n /* Precompute bitmaps for this pattern */\n map = PatternBitmap.map(s, idx, new long/*WORD*/[idx.size()]);\n /* Compute the bit that represents a change in the last row */\n lastBitPosition = (((long/*WORD*/) 1) &lt;&lt; (m - 1));\n }\n\n @Override\n public int getDistance(CharSequence s, int k) {\n int len = s.length();\n\n /* Quick check based on length */\n if (((len - m) &gt; k) || ((m - len) &gt; k)) {\n return k + 1;\n }\n\n /* Map characters to their integer positions in the bitmap array */\n indices = idx.map(s, indices);\n\n /* Initially, vertical change is all positive (none negative) */\n long/*WORD*/ verticalPositive = -1;\n long/*WORD*/ verticalNegative = 0;\n int distance = m;\n\n /* We can only miss the \"distance--\" below this many times: */\n int maxMisses = k + len - m;\n if (maxMisses &lt; 0) {\n maxMisses = Integer.MAX_VALUE;\n }\n\n for (int j = 0; j &lt; len; j++) {\n /* Where is diagonal zero: matches, or prior VN; plus recursion */\n long/*WORD*/ diagonalZero = map[indices[j]] | verticalNegative;\n diagonalZero |= (((diagonalZero &amp; verticalPositive) + verticalPositive)\n ^ verticalPositive);\n\n /* Compute horizontal changes */\n long/*WORD*/ horizontalPositive = verticalNegative\n | ~(diagonalZero | verticalPositive);\n long/*WORD*/ horizontalNegative = diagonalZero &amp; verticalPositive;\n\n /* Update final distance based on horizontal changes */\n if ((horizontalNegative &amp; lastBitPosition) != 0) {\n distance--;\n } else if ((horizontalPositive &amp; lastBitPosition) != 0) {\n distance++;\n if ((maxMisses -= 2) &lt; 0) {\n break;\n }\n } else if (--maxMisses &lt; 0) {\n break;\n }\n\n /* Shift Hs to next row, compute new Vs analagously to Hs above */\n horizontalPositive = (horizontalPositive &lt;&lt; 1) | 1;\n verticalPositive = (horizontalNegative &lt;&lt; 1)\n | ~(diagonalZero | horizontalPositive);\n verticalNegative = diagonalZero &amp; horizontalPositive;\n }\n return distance;\n }\n}\n\npublic static MyersBitParallelEditDistance getInstance(CharSequence s) {\n int m = s.length();\n return (m &lt;= Integer.SIZE) ?\n ((m == 0) ? new Empty(s) : new TYPEint(s)) :\n (s.length() &lt;= Long.SIZE) ?\n new TYPElong(s) :\n new Multi(s);\n}\n\nfinal CharIndex idx;\n\nint[] indices = new int[0];\n\nfinal int m;\n\nprotected MyersBitParallelEditDistance(CharSequence s) {\n m = s.length();\n idx = CharIndex.getInstance(s);\n}\n\npublic GeneralEditDistance duplicate() {\n try {\n return (MyersBitParallelEditDistance) clone();\n } catch (CloneNotSupportedException x) { /*IMPOSSIBLE */\n throw new IllegalStateException(\"Cloneable object would not clone\");\n }\n}\n\npublic abstract int getDistance(CharSequence s, int k);\n\n@Override\nprotected Object clone() throws CloneNotSupportedException {\n Object obj = super.clone();\n\n /* Re-initialize any non-thread-safe parts */\n ((MyersBitParallelEditDistance) obj).perThreadInit();\n\n return obj;\n}\n\nprotected void perThreadInit() {\n indices = new int[0];\n}\n}\n\nclass PatternBitmap {\n\npublic static int[] map(CharSequence s, CharIndex idx, int[] result) {\n int len = s.length();\n assert (len &lt;= Integer.SIZE);\n for (int i = 0; i &lt; len; i++) {\n result[idx.lookup(s.charAt(i))] |= (1 &lt;&lt; i);\n }\n return result;\n}\n\npublic static int[][] map(CharSequence s, CharIndex idx,\n int[][] result, int width) {\n assert (width &lt;= Integer.SIZE);\n int len = s.length();\n int rowSize = (len + width - 1) / width;\n\n /*\n * Use one zero-filled bitmap for alphabet characters not in the pattern\n */\n int[] nullElement = new int[rowSize];\n java.util.Arrays.fill(result, nullElement);\n\n int wordIndex = 0; /* Which word we are on now */\n int bitWithinWord = 0; /* Which bit within that word */\n\n for (int i = 0; i &lt; s.length(); i++) {\n int[] r = result[idx.lookup(s.charAt(i))];\n if (r == nullElement) {\n\n /* Create a separate zero-filled bitmap for this alphabet character */\n r = result[idx.lookup(s.charAt(i))] = new int[rowSize];\n }\n r[wordIndex] |= (1 &lt;&lt; bitWithinWord);\n\n /* Step to the next bit (and word if appropriate) */\n if (++bitWithinWord == width) {\n bitWithinWord = 0;\n wordIndex++;\n }\n }\n return result;\n}\n\npublic static long[] map(CharSequence s, CharIndex idx, long[] result) {\n int len = s.length();\n assert (len &lt;= Long.SIZE);\n for (int i = 0; i &lt; len; i++) {\n result[idx.lookup(s.charAt(i))] |= (1L &lt;&lt; i);\n }\n return result;\n}\n\nprivate PatternBitmap() { /* Prevent instantiation */ }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T13:09:34.037", "Id": "19527", "Score": "0", "body": "+1 for all that work. Haha, I ended up going a totally different route, but if I ever do this kind of thing again I imagine your code will be helpful (and will hopefully be helpful to someone in the future). I hope it was helpful for you too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T13:33:02.980", "Id": "19529", "Score": "0", "body": "Thanks. There are more interesting structures (trie) for comparing levenstein distance between few hundreds strings in milliseconds: http://stevehanov.ca/blog/index.php?id=114" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T13:00:08.937", "Id": "12193", "ParentId": "12042", "Score": "3" } } ]
{ "AcceptedAnswerId": "12047", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T18:44:30.313", "Id": "12042", "Score": "2", "Tags": [ "java", "performance", "strings", "edit-distance" ], "Title": "Comparing long lists of strings for the closest match" }
12042
<p>I had to write a SQL query recently to do a few joins and sums, and at the end of it I realized that I have nearly written a storybook. I know the tools to optimize it, but my trouble is the length of it. I am very sure, it can be shortened up, but my little brain refuses to strengthen this belief.</p> <p>Basically, I want a list of teams ordered by the total Distance + Bonus. The Bonus consists of the team bonus and the bonus of team members (Member Bonus). In order to calculate distance covered by the team, I have to sum up the distance covered by the team members.</p> <p>The relationship between the tables:</p> <p><img src="https://i.stack.imgur.com/Qv9XL.jpg" alt="enter image description here"></p> <pre><code> SELECT TeamID, Name, Country, Region, OfficeLocation AS [Office Location], Minutes As Steps, Distance, SUM(MemberBonus+TeamBonus) AS Bonus,TeamSize, ROW_NUMBER() OVER (ORDER BY SUM( ISNULL(Distance,0.0000000) +ISNULL(MemberBonus,0.0000000)+ISNULL(TeamBonus,0.0000000)) DESC) AS Place FROM ( -- Sum the Distance, Member Bonus and Team Bonus and assign them a rank based on the sum value. SELECT TeamID, Name, Country, Region, Minutes, Distance, ISNULL(MemberBonus,0.0000000) AS MemberBonus, SUM(ISNULL(teamBonusData.BonusPoints,0.0000000)) AS TeamBonus, OfficeLocation, TeamSize FROM ( SELECT Team.TeamID, Team.Name, Result.Country AS Country, Result.Region, Result.Minutes AS Minutes, SUM(ISNULL(Result.MemberBonus,0)) AS MemberBonus, Result.Distance AS Distance, TeamSize FROM ( SELECT Group1.TeamID, Group1.Name, Country, Region, Minutes, Distance, MemberBonus, TeamSize FROM ( --Get a sum of distance covered by the team's members. Only get the data for the active teams ( Status = 1) SELECT Team.TeamID, Team.Name, Country.Name AS Country, Region.Name AS Region, ISNULL(SUM(Activity.Minutes),0) AS Minutes, ISNULL(SUM(Activity.Distance),0) AS Distance FROM Team LEFT JOIN Country ON Team.fk_CountryID = Country.CountryID LEFT JOIN Region ON Team.fk_RegionID = Region.RegionID JOIN TeamMember LEFT JOIN Member LEFT JOIN Activity ON Activity.fk_MemberID = Member.MemberID ON Member.MemberID = TeamMember.MemberID ON Team.TeamID = TeamMember.TeamID WHERE Team.Status = 1 AND Member.Disabled = 0 GROUP BY TeamMember.TeamID, Team.TeamID, Team.Name, Country.Name, Region.Name )Group1 JOIN ( -- Get a sum of Bonus points given to the team's members. SELECT TeamMember.TeamID, Member.MemberID, SUM(ISNULL(MemberBonus.BonusPoints,0)) AS MemberBonus FROM Team JOIN TeamMember JOIN Member LEFT JOIN dbo.MemberBonus ON Member.MemberID = MemberBonus.fk_MemberID ON TeamMember.MemberID = Member.MemberID ON Team.TeamID = TeamMember.TeamID GROUP BY Member.MemberID, TeamMember.TeamID ) Group2 ON Group1.TeamID = Group2.TeamID JOIN ( -- Get the team size ( number of members in the team) SELECT COUNT(TeamMember.TeamID) AS TeamSize,TeamID FROM TeamMember GROUP BY TeamMember.TeamID )Group3 ON Group1.TeamID = Group3.TeamID )Result JOIN Team ON Result.TeamID = Team.TeamID GROUP BY Team.TeamID, Team.Name, Result.Country, Result.Minutes, Result.Distance, Result.Region, Result.TeamSize )teamRank LEFT JOIN ( --Get the Bonus points given to the team SELECT ISNULL(TeamBonus.BonusPoints,0)AS BonusPoints, fk_TeamID FROM TeamBonus )teamBonusData ON teamRank.TeamID = teamBonusData.fk_TeamID LEFT JOIN ( -- Get the office location value for the team's Captain SELECT TeamID AS CapTeamID, OfficeLocation FROM TeamMember JOIN Member on TeamMember.MemberID = Member.MemberID WHERE MemberType='Captain' )captainData ON teamRank.TeamID = captainData.CapTeamID GROUP BY teamRank.TeamID, teamRank.Name, teamRank.Country, teamRank.Minutes, teamRank.Distance, teamRank.Region, teamRank.MemberBonus, captainData.OfficeLocation, teamRank.TeamSize ) myTeamRank GROUP BY myTeamRank.TeamID, myTeamRank.Name, myTeamRank.Country, myTeamRank.Minutes, myTeamRank.Distance, myTeamRank.Region, myTeamRank.OfficeLocation,TeamSize ORDER BY Place </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T00:39:58.903", "Id": "19319", "Score": "1", "body": "Hm ... you could create, fill and update a temporary table or two to simplify things. I doubt that you have millions of teams and team members. You could also use several CTEs ... http://blog.sqlauthority.com/2009/08/08/sql-server-multiple-cte-in-one-select-statement-query/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T01:33:54.323", "Id": "19320", "Score": "0", "body": "Thanks for the tip, Leonid! Temp tables sound a good idea. However, is there also any way to shorten this query? Just want to polish my sql querying skills :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T03:45:35.540", "Id": "19324", "Score": "0", "body": "@Sonya, the query is large and intimidating. It feels like it is more complicated than it should be, but I cannot say for sure. I noticed that you are doing a lot of joining on sub-queries and intermediate group-bys - just seems like there is a simpler way if you think in terms of sets. Can you post the table definitions and the relationships between them? If you sit down with pen and paper, then can you write down some sort of formula in an easy way?" } ]
[ { "body": "<p>You really should be more consistent with your choice of line breaks and indentation, especially in a query as large as this. Improving the readability should also make it easier to spot areas for improvement. You didn't indicate which DBMS you're using, but if it's supported, the <code>WITH</code> clause (\"common table expressions\" or \"subquery factoring clause\") can help reduce the number of indentation levels you have to deal with.</p>\n\n<hr>\n\n<p>I feel like you're using <code>ISNULL</code> too much. Remember that aggregate functions like <code>SUM</code> ignore <code>NULL</code> values, so an expression like <code>SUM(ISNULL(Result.MemberBonus,0))</code> is equivalent to <code>SUM(Result.MemberBonus)</code>.</p>\n\n<hr>\n\n<p>A big problem I see is that you join some tables and subqueries too early. For example, <code>Country</code> and <code>Region</code> appear to be necessary only for information and don't actually affect any calculations. Furthermore, <code>Country</code> and <code>Region</code> only depend on the <code>TeamID</code>. Since that's the case, instead of joining them in the inner-most subquery, join them as part of the outer query. This will shorten up the <code>GROUP BY</code> clauses.</p>\n\n<p>The steps I would take to write this query:</p>\n\n<ol>\n<li>Write a query which calculates the distance by team. The only output columns should be <code>TeamID</code> and <code>TotalDistance</code>.</li>\n<li>Write a query which calculates the total Member bonus by team. The only output columns should be <code>TeamID</code> and <code>TotalMemberBonus</code>.</li>\n<li>Write a query which calculates the total team bonus by team. The only output columns should be <code>TeamID</code> and <code>TotalTeamBonus</code>.</li>\n<li>Join the first three queries on <code>TeamID</code>, along with any other information tables like <code>Country</code> and <code>Region</code>. Note that all the aggregation was done in the subqueries, so this final query should not need a <code>GROUP BY</code> clause.</li>\n</ol>\n\n<p>If you follow this outline, you shouldn't need to calculate a <code>ROW_NUMBER</code> to sort the results. Just <code>ORDER BY TotalDistance + TotalMemberBonus + TotalTeamBonus</code>.</p>\n\n<p>The advantage of this approach is that you can test each individual query separately to ensure that you are getting correct results at each step. It also should result in a shorter, easier-to-follow query.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T08:19:56.947", "Id": "12185", "ParentId": "12048", "Score": "8" } } ]
{ "AcceptedAnswerId": "12185", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T00:23:41.260", "Id": "12048", "Score": "7", "Tags": [ "sql", "sql-server" ], "Title": "Listing teams by total distance and bonus" }
12048
<p>I am in between to create JavaScript Boilerplate (collection of best practices around) for low/medium complex project and will host on GitHub in sometime once finalized it.</p> <p>Have divided the JavaScript modules in 3 parts</p> <ol> <li>project.config.js - Would have all the required configuration</li> <li>project.main.js - the JS Boilerplate</li> <li>project.helper.js - would have most commonly used functions, user may or may not want it</li> </ol> <p>project.config.js</p> <pre><code>/* MODULE (our namespace name) and undefined are passed here * to ensure 1. namespace can be modified locally and isn't * overwritten outside of our function context * 2. the value of undefined is guaranteed as being truly * undefined. This is to avoid issues with undefined being * mutable pre-ES5. */ (function (MODULE, undefined) { MODULE.config = { language: 'english', debug: true, etc... } }(window.MODULE = window.MODULE || {})) </code></pre> <p>project.main.js: </p> <pre><code>/* MODULE (our namespace name) and undefined are passed here * to ensure 1. namespace can be modified locally and isn't * overwritten outside of our function context * 2. the value of undefined is guaranteed as being truly * undefined. This is to avoid issues with undefined being * mutable pre-ES5. */ (function( MODULE, $, undefined ){ /** * Logging function, for debugging mode */ jQuery.log = function(message) { if( (typeof window.console != 'undefined' &amp;&amp; typeof window.console.log != 'undefined') &amp;&amp; console.debug ) { console.debug(message); } else { //alert(message); } }; /** * Private properties */ var foo = "foo", bar = "bar"; /** * Public methods and properties */ MODULE.foobar = "foobar"; MODULE.sayHello = function () { speak("hello world"); }; /** * Private method */ /* Benefits: * 1. Makes it easier to understand "functions as an object". * 2. It enforces good semicolon habits. * 3. Doesn't have much of the baggage traditionally associated with functions and scope. */ var getData = function () { }; /* Singleton with Privileged Methods */ MODULE.subModule = (function () { function _subModule() { /** * Init call */ var _this = this; /* Store this to avoid scope conflicts */ /** * facebookLogin - FB.login prompts the user to authorize your application */ this.facebookLogin = function () { } /** * private method */ var privateMethod = function() { }; this.init = function () { _this.facebookLogin(); return this; }; return this.init(); } return new _subModule(); }()); })(window.MODULE = window.MODULE || {}, jQuery) </code></pre> <p>Though it's pretty straight forward with comments and all but anyway let me elaborate it further, have been using Global Abatement using namespace, singleton inside the SIAF (to protect the scope and follow encapsulation) and using privileged private methods inside it and executing the privileged one in <code>init()</code>.</p> <p>And essentially returning the <code>submodule</code> in the last to available to the window level using namespace (MODULE).</p> <p>Looks pretty neat but still looking to make it better and robust.</p> <p>Would appreciate code review comments here.</p> <p>Thanks for your time.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T06:28:05.267", "Id": "25674", "Score": "0", "body": "BTW JavaScript Boilerplate has been on Git now @ https://github.com/mdarif/JavaScript-Boilerplate where I have integrated the review comments. And again anyone of you, have anything to add or have good suggestion, do send out the 'Pull' request which I can review and implement if feasible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T11:10:12.893", "Id": "40461", "Score": "0", "body": "It's also available as npm package, run ```$ npm install javascript-boilerplate```" } ]
[ { "body": "<p>Interesting work Arif. I really loved to see different as well as interesting JS patterns you have used. It is looking to me like, it is going in a good and right direction. </p>\n\n<p>Few things that you might consider to do is</p>\n\n<p>I) Create some example of different modules and ensure they are in different files (it is not very clear with the current example but I assume you have already thought about it).</p>\n\n<p>II) Might be a very personal choice, I don’t like _ in variable and method names. The way I know what is public and what is private is by looking at what is being returned at the bottom, as I use a pattern like below in most occasions </p>\n\n<pre><code> (function(MODULE, $) {\n MODULE.charting = function(options) {\n options = $.extend({\n defaultParam1: “a”,\n defaultParam2: “b”\n }, options);\n\n var xAxis, yAxis;\n\n function render() {\n\n }\n\n function destroy() {\n\n } \n\n (function init() {\n //Anything that is suppose to be called when a object of the\n //module is created. Acts like a psuedo constructor.\n })();\n\n return {\n render: render,\n destroy: destroy\n };\n };\n }(MODULE || {}, jQuery));\n</code></pre>\n\n<p>What do you think? In above example you can clearly see what is public and they can be exposed with a different name if one wants. So in refactoring it will not break other components as the way it is exposed outside can be different. If you see what I mean.</p>\n\n<p>III) If you are using jQuery, you can use extend like above to define defaults and then override if passed by the user.</p>\n\n<p>IV) Generally I don’t tend to put URLs in JavaScript and prefer to put them on jsp, asp, json response, etc. as then front-end doesn’t need to worry about context/domain/port.</p>\n\n<p>Will send you more comments if I think of any. For the time being have a think about it and let me know your views. Also keep on sharing the progress, would love to see this growing into a very fruitful thing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T04:12:14.480", "Id": "19513", "Score": "0", "body": "Thanks for the comments Manish.\n\nYou are right for #1 would be creating different modules in separate file.\n\n#2, you talking about \"Revealing Module Pattern\" which has few issues like a private function refers to a public function, that public function can't be overridden if a patch if necessary. This is because the private function will continue to refer to the private implementation and the pattern doesn't apply to public members, only to functions.\n\nI just tried to kept it simple and hence using Privileged Methods most of the time & exposing in init()." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T18:52:56.967", "Id": "12177", "ParentId": "12051", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T05:20:22.603", "Id": "12051", "Score": "8", "Tags": [ "javascript", "design-patterns", "singleton" ], "Title": "JavaScript Boilerplate - Review comments required" }
12051
<p>I've implemented <code>concurrent_blocking_queue</code> for <em>multiple-producers</em> and <em>single consumer</em>.</p> <p>I intend it to block the producers as well, when the queue is full, which is why I set the capacity of the queue in the constructor. I've provided my own implementation of <code>critical_section</code>, <code>scoped_lock</code> and <code>condition_variable</code>, using msdn primitives.</p> <p>Please review it. I want to know if there is any potential deadlocks.</p> <pre><code>template&lt;typename T&gt; class concurrent_blocking_queue : public noncopyable { std::queue&lt;T&gt; m_internal_queue; mutable critical_section m_critical_section; condition_variable m_queue_full; condition_variable m_queue_empty; const size_t m_capacity; public: concurrent_blocking_queue(size_t capacity) : m_capacity(capacity), m_critical_section() { } void put(T const &amp; input) { framework::scoped_lock lock(m_critical_section); //lock m_queue_full.wait(lock, [&amp;]{ return !full(); }); m_internal_queue.push(input); m_queue_empty.notify_all(); } T take() { framework::scoped_lock lock(m_critical_section); //lock m_queue_empty.wait(lock, [&amp;]{ return !empty(); }); T output = m_internal_queue.front(); m_internal_queue.pop(); m_queue_full.notify_all(); return output; } bool full() const { framework::scoped_lock lock(m_critical_section); if ( m_internal_queue.size() &gt; m_capacity ) { throw std::logic_error("size of concurrent_blocking_queue cannot be greater than the capacity."); } return m_internal_queue.size() == m_capacity; } bool empty() const { framework::scoped_lock lock(m_critical_section); return m_internal_queue.empty(); } //.. }; </code></pre> <p>And the remaining classes are posted below. Note that I've implemented them in <code>.h</code> and <code>.cpp</code> files, but here I've merged them to make the post short and simple, and have removed the namespace for brevity, otherwise all classes are defined in <code>framework</code> namespace.</p> <ul> <li><p>critical_section derives <em>publicly</em> from <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms683472%28v=vs.85%29.aspx" rel="nofollow">CRITICAL_SECTION</a>.</p> <pre><code>class critical_section : public CRITICAL_SECTION, public noncopyable { public: critical_section(void) { ::InitializeCriticalSection(this); } ~critical_section(void) { ::DeleteCriticalSection(this); } void lock() { ::EnterCriticalSection(this); } void unlock() { ::LeaveCriticalSection(this); } }; </code></pre></li> <li><p>condition_variable derives <em>privately</em> from <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms682052%28v=vs.85%29.aspx" rel="nofollow">CONDITION_VARIABLE</a>. </p> <pre><code>class condition_variable : private CONDITION_VARIABLE, public noncopyable { public: condition_variable() { ::InitializeConditionVariable(this); } ~condition_variable(void) {} void wait(scoped_lock &amp; lock) { if (!::SleepConditionVariableCS (this, &amp;lock.m_cs, INFINITE)) { DWORD error = ::GetLastError(); std::string msg = format("SleepConditionVariableCS() failed with error code = 0x%X.", error); throw std::runtime_error(msg); } } void wait(scoped_lock &amp; lock, std::function&lt;bool()&gt; predicate) { while( !predicate() ) { wait(lock); } } void notify_one() { ::WakeConditionVariable(this); } void notify_all() { ::WakeAllConditionVariable(this); } }; </code></pre></li> <li><p>scoped_lock </p> <pre><code>class scoped_lock : public noncopyable { friend class condition_variable; critical_section &amp; m_cs; public: scoped_lock(critical_section &amp; cs) : m_cs(cs) { m_cs.lock(); } ~scoped_lock(void) { m_cs.unlock(); } }; </code></pre></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T10:48:35.027", "Id": "19329", "Score": "0", "body": "Does the implementation you use for condition variables unlock the mutex lock in the call to wait() like it does in Posix? If not, then Ive located a dead-lock." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T11:07:13.107", "Id": "19330", "Score": "0", "body": "@Brady: As the MSDN doc says [Sleeps on the specified condition variable and releases the specified critical section as an atomic operation](http://msdn.microsoft.com/en-us/library/windows/desktop/ms686301(v=vs.85).aspx), so yes, the condition variable unlocks the mutex in `wait()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T11:09:49.353", "Id": "19331", "Score": "0", "body": "ok, thanks. I wasnt sure about the MS implementation. Another question as you can see in my answer: are the locks recursive? If not, then there is a dead-lock." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T11:10:35.753", "Id": "19332", "Score": "0", "body": "@Brady: Yes, we can recursively lock `CRITICAL_SECTION` as per the MSDN." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T13:00:56.010", "Id": "19337", "Score": "0", "body": "One last comment, it seems odd that the threads should call `m_queue_empty.notify_all()` if no other threads are waiting. If that behavior is allowed/supported by MSDN, then the rest looks ok to me." } ]
[ { "body": "<h3>Basic comments:</h3>\n<p>No point in functions that do nothing.<br />\nAlso avoid <code>void</code> as definition for empty parameter list.</p>\n<pre><code>~condition_variable(void) {}\n</code></pre>\n<p>Why put a member that has no default constructor in the initializer list ( I can go either way)</p>\n<pre><code>concurrent_blocking_queue(size_t capacity) \n : m_capacity(capacity), m_critical_section()\n</code></pre>\n<p><strong>But</strong> you should be consistent and thus if you do it for one then you should do it for all members.</p>\n<h3>Design:</h3>\n<p>When you call <code>full()</code> and <code>empty()</code> from within other members you already have a lock. Yet you are calling a function that will add another level of locking. And locking is usually relatively expensive.</p>\n<pre><code> m_queue_full.wait(lock, [&amp;]{ return !full(); });\n\n m_queue_empty.wait(lock, [&amp;]{ return !empty(); });\n</code></pre>\n<p>Thus I would change the above to call a private version of these function that do not use locks.</p>\n<pre><code> // OLD STUFF\n m_queue_full.wait(lock, [&amp;]{ return !test_full(); });\n\n // OLD STUFF\n m_queue_empty.wait(lock, [&amp;]{ return !test_empty(); });\n\n bool full() const\n {\n framework::scoped_lock lock(m_critical_section);\n return test_full();\n }\n bool empty() const\n {\n framework::scoped_lock lock(m_critical_section);\n return test_empty();\n }\n\n private:\n bool test_full() const {STUFF}\n bool test_empty() const {STUFF}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T10:59:22.140", "Id": "19667", "Score": "0", "body": "1) The destructor was generated by MSVS itself. I'm just too lazy to remove it from my code. 2) thanks for the idea of `test_full()` and `test_empty()`. They're good improvements to my code. 3) I assume there is no dead-lock in the implementation of the queue, as everyone here seems to have this opinion." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T04:24:31.770", "Id": "12090", "ParentId": "12052", "Score": "3" } }, { "body": "<pre><code>T take()\n</code></pre>\n\n<p>I do not like <code>take()</code> function returning by value. What if <code>T</code>'s copy constructor throws an exception? This was the exact reason for having separate <code>front()</code> and <code>pop()</code> functions in <code>std::stack</code>.</p>\n\n<p>In my implementation of a similar queue I took a different approach: the queue never removes its last element** and the <code>take()</code> function returns by (const) reference. This works and is easy to implement if the queue is designed for only one consumer, which was my case.</p>\n\n<p>** Well, it does on queue destruction.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T14:46:20.520", "Id": "50647", "Score": "0", "body": "Won't the copy be elided (assuming C++11)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T09:36:16.307", "Id": "50893", "Score": "0", "body": "@svick: Not entirely: one copy has to be made since the original object (the one in queue) is destroyed (m_internal_queue.pop();). A copy from return output; can and probably be elided." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T09:56:49.943", "Id": "31725", "ParentId": "12052", "Score": "1" } } ]
{ "AcceptedAnswerId": "12090", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T05:33:56.000", "Id": "12052", "Score": "5", "Tags": [ "c++", "multithreading" ], "Title": "Implementation of concurrent blocking queue for producer-consumer" }
12052
<p>This is a simple thread safe queue that is used in a producer-consumer model.</p> <pre><code>public class ThreadedQueue&lt;TType&gt; { private Queue&lt;TType&gt; _queue; private object _queueLock; protected ThreadedQueue() { _queue = new Queue&lt;TType&gt;(); _queueLock = new object(); } public void Enqueue(TType data) { lock (_queueLock) { // do not allow duplicates if (!_queue.Contains(data)) { _queue.Enqueue(data); } } } public bool TryDequeue(out TType data) { data = default(TType); bool success = false; lock (_queueLock) { if (_queue.Count &gt; 0) { data = _queue.Dequeue(); success = true; } } return success; } } </code></pre> <p>Is this complete and thread safe?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T07:53:37.357", "Id": "19326", "Score": "2", "body": "What's wrong with `ConcurrentQueue<T>`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T08:14:56.717", "Id": "19327", "Score": "0", "body": "I am not sure it is thread safe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T11:35:34.370", "Id": "19333", "Score": "2", "body": "The point of `ConcurrentQueue<T>` is that it *is* thread-safe. It says so at the very top of [the documentation](http://msdn.microsoft.com/en-us/library/dd267265): “Represents a thread-safe first in-first out (FIFO) collection.”" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T12:00:45.430", "Id": "19335", "Score": "0", "body": "I am on .Net 3.5 sorry for not mentioning it earlier. ConcurrentQueue<T> isn't available" } ]
[ { "body": "<p>This looks mostly fine by me (ignoring Reflection and other more obscure sources of thread safety failures), but I wouldn't call it a Queue per say (because of the duplicate check there). Does it really matter what order the set of items in this collection are in (if so then the duplicate check introduces a bug in that ordering, if not then why not call this a <code>Set</code>)?</p>\n<p>One change you should really make is adding <code>readonly</code> to your private members.</p>\n<p>Also, while this looks thread safe, there is no reason to assume that it is safe to use any of the items inside of it or any inherited versions of it. Consider code like this (intended to obviously be unsafe):</p>\n<pre><code>public class NotThreaSafeExampleClass {\n public Action&lt;string&gt; SayHello;\n}\n\n//thread 1: (q = shared ThreadedQueue&lt;NotThreaSafeExampleClass&gt;)\nvar mean = new NotThreaSafeExampleClass();\nq.Enqueue(mean);\nwhile (true) {\n mean.SayHello = name =&gt; { Console.WriteLine(&quot;Hi &quot;+name); };\n Thread.Sleep(10);\n mean.SayHello = null;\n Thread.Sleep(10);\n}\n\n//thread 2:\nNotThreaSafeExampleClass otherThreadMethod;\nq.TryDequeue(out otherThreadMethod);\nwhile (true) { otherThreadMethod.SayHello('odyodyodys'); Thread.Sleep(15);}\n</code></pre>\n<p>Lock based concurrency in .NET is a fairly simple paradigm (compared to the other ways of ensuring thread safety in .NET). When you lock, you declare a block of code as a critical section, protected by that lock object. .NET ensures that a second piece of code in the same app domain will never be running in a critical section protected by the same lock object while one instance is. Here is a good resource for more threading information: <a href=\"http://www.albahari.com/threading/part2.aspx\" rel=\"nofollow noreferrer\">http://www.albahari.com/threading/part2.aspx</a></p>\n<h3>Pedantry</h3>\n<p>When most people discuss thread safety they mean it in the same sense as saying strings are immutable. That is to say, as long as you don't do anything I shouldn't reasonably expect you might do it is safe.</p>\n<p>Unfortunately, locks aren't good enough to actually provide true thread safety (bulletproof against reflection and <code>unsafe</code> C# pointer code), they are good enough for most usages where you control the software stack out to the actual application. If you need to ensure thread safety in these instances you must ensure thread safety at the field level in your classes (stuff like the <code>volatile</code> keyword will help you here, but watch out).</p>\n<p>Some example threads that would break your safety here:</p>\n<pre><code>//as an additional thread running in the app, this would effectively make the locks no longer exclusive\nvar l = q.GetType().GetField(&quot;_queueLock&quot;, BindingFlags.NonPublic|BindingFlags.Instance);\nwhile (true) { l.SetValue(q,new object()); }\n//making the lock object readonly would protect against this\n\n//ex 2:\nvar qf = q.GetType().GetField(&quot;_queue&quot;, BindingFlags.NonPublic|BindingFlags.Instance);\nvar field = (Queue&lt;TType&gt;)qf.GetValue(q);\nfield.Clear(); //what if this will happen between the Count check and the Dequeue statement\n//readonly will not protect against this\n</code></pre>\n<p>While these examples are pretty far out there, consider if your Queue class were complex enough that I might want to add an extension method to it and need access to internal variables in the method to do some algorithm in a way much better than possible with the available public interface.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T20:42:26.417", "Id": "12079", "ParentId": "12053", "Score": "3" } } ]
{ "AcceptedAnswerId": "12079", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T06:39:49.160", "Id": "12053", "Score": "3", "Tags": [ "c#", "multithreading", "thread-safety", "queue" ], "Title": "Simple generic multithreaded queue" }
12053
<p>There are two ways I have been using to create links and style them as buttons:</p> <pre><code>background: url("/images/sing_up_btn.png") no-repeat scroll 0 0 transparent; font-family: Arial,Helvetica,Sans-serif; text-shadow: 0 -1px #444444; text-transform: none; </code></pre> <p>Another one is:</p> <pre><code>a.btn_link { background: #4468b2; /* Old browsers */ background: -moz-linear-gradient(top, #4468b2 0%, #3b5a9b 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#4468b2), color-stop(100%,#3b5a9b)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #4468b2 0%,#3b5a9b 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #4468b2 0%,#3b5a9b 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #4468b2 0%,#3b5a9b 100%); /* IE10+ */ background: linear-gradient(top, #4468b2 0%,#3b5a9b 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#4468b2', endColorstr='#3b5a9b',GradientType=0 ); /* IE6-9 */ color:#fff; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, .4); -moz-box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, .4); box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, .4); color: #FFFFFF; text-decoration:none; padding:5px 25px 5px 25px; } a.btn_link:active{ margin: 2px -2px 0px 2px; box-shadow:none; } </code></pre> <p>The image used as a background is almost the same as the second code creates a button design. I was wondering which is more efficient and optimized way to create button. With my little understanding, I would think that the one that doesn't uses image. But I have seen many new age well designed websites using images. Does that mean if I use such heavy CSS for a simple button, the code is not optimized?</p>
[]
[ { "body": "<p>I like the second option, it is easy to read if you just reformat it a little bit (also corrected your <code>:active</code> selector and fixed the shadow in IE9):</p>\n\n<pre><code>a.btn_link {\n background: #4468b2; /* Old browsers */\n background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#4468b2), color-stop(100%,#3b5a9b)); /* Chrome,Safari4+ */\n background: -webkit-linear-gradient(top, #4468b2 0%, #3b5a9b 100%); /* Chrome10+,Safari5.1+ */\n background: -moz-linear-gradient(top, #4468b2 0%, #3b5a9b 100%); /* FF3.6+ */\n background: -ms-linear-gradient(top, #4468b2 0%, #3b5a9b 100%); /* IE10+ */\n background: -o-linear-gradient(top, #4468b2 0%, #3b5a9b 100%); /* Opera 11.10+ */\n background: linear-gradient(top, #4468b2 0%, #3b5a9b 100%); /* W3C */\n filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#4468b2', endColorstr='#3b5a9b',GradientType=0 ); /* IE6-9 */\n\n -webkit-border-radius: 4px;\n -moz-border-radius: 4px;\n border-radius: 4px;\n\n -webkit-box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, .4);\n -moz-box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, .4);\n box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, .4);\n border-collapse: separate; /* http://stackoverflow.com/questions/5617455/issue-with-box-shadow-on-ie9/5617540#5617540 */\n\n color: #FFFFFF;\n text-decoration: none;\n padding: 5px 25px 5px 25px;\n}\na.btn_link:active {\n margin: 2px -2px 0 2px; \n -webkit-box-shadow: none;\n -moz-box-shadow: none;\n box-shadow: none;\n}\n</code></pre>\n\n<p>I would also add a simple hover affect like this:</p>\n\n<pre><code>a.btn_link:hover {\n background: #4468b2;\n filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);\n}\n</code></pre>\n\n<p>If you can, consider using a css preprocessor like <a href=\"http://lesscss.org/\" rel=\"nofollow\">LESS</a></p>\n\n<pre><code>.rounded-corners (@radius: 4px) {\n -webkit-border-radius: @radius;\n -moz-border-radius: @radius;\n border-radius: @radius;\n}\n\n.gradient-box (@baseColor) {\n @darker = darken(@baseColor, 6%);\n background: @baseColor; /* Old browsers */\n background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,@baseColor), color-stop(100%,@darker)); /* Chrome,Safari4+ */\n background: -webkit-linear-gradient(top, @baseColor 0%, @darker 100%); /* Chrome10+,Safari5.1+ */\n background: -moz-linear-gradient(top, @baseColor 0%, @darker 100%); /* FF3.6+ */\n background: -ms-linear-gradient(top, @baseColor 0%, @darker 100%); /* IE10+ */\n background: -o-linear-gradient(top, @baseColor 0%, @darker 100%); /* Opera 11.10+ */\n background: linear-gradient(top, @baseColor 0%, @darker 100%); /* W3C */\n filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='@baseColor', endColorstr='@darker',GradientType=0 ); /* IE6-9 */\n\n color: white;\n text-decoration: none;\n padding: 5px 25px 5px 25px;\n\n &amp;:hover {\n background: @baseColor;\n filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);\n }\n}\n\n.pressable-floating-box (@distance: 2px, @blur: 2px, @spread: 0px) {\n -webkit-box-shadow: @distance @distance @distance 0 rgba(0, 0, 0, .4);\n -moz-box-shadow: @distance @distance @distance 0 rgba(0, 0, 0, .4);\n box-shadow: @distance @distance @distance 0 rgba(0, 0, 0, .4);\n\n border-collapse: separate; // http://stackoverflow.com/questions/5617455/issue-with-box-shadow-on-ie9/5617540#5617540\n\n &amp;:active {\n margin-right: -@distance;\n margin-left: @distance;\n -webkit-box-shadow: none;\n -moz-box-shadow: none;\n box-shadow: none;\n }\n}\n\na.btn_link {\n .rounded-corners;\n .gradient-box(#3b5a9b);\n .pressable-floating-box;\n}\n</code></pre>\n\n<p>I really wouldn't be too worried about css efficiency, yes this does take a little more effort on the browser's part to render than a simple css background image, but the paths are all highly optimized already and this way you have defined the style instead of giving the browser a limited example (try a two line button with each, or zooming the document, or any other of the many ways to mess the button up in one or more browsers).</p>\n\n<p>Comparing the http transfer efficiency of these two probably comes out in favor of the latter as well. The image version comes in 2 requests, while the pure css version is only one. I'd bet they both are fairly minimal on the total bandwidth compared to your page as a whole, but if you were really concerned about this you could always inline the image. If you want to go that route, here is a useful tool: <a href=\"http://www.greywyvern.com/code/php./binary2base64\" rel=\"nofollow\">http://www.greywyvern.com/code/php./binary2base64</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-21T18:13:02.777", "Id": "22421", "Score": "0", "body": "`-moz` prefix can be deleted from code if you not support firefox 3.6" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T08:57:41.440", "Id": "25087", "Score": "0", "body": "@Bill: Thanks a lot for the detailed explanation and the modifications. I have chosen to go the CSS way for my project :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T15:00:47.873", "Id": "12068", "ParentId": "12054", "Score": "1" } } ]
{ "AcceptedAnswerId": "12068", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T06:42:10.747", "Id": "12054", "Score": "2", "Tags": [ "css" ], "Title": "Which is a better optmized CSS for a button design?" }
12054
<p>I have a constructor which sets a member variable. The setting of this variable throws an exception. Should I be throwing the exception in the contructor or enclosing the try/catch like below. Is below snippet an example of code smell ?</p> <pre><code>private NewManager newManager; public Save(final TheManager manager, final String str) { this.manager = manager; try { this.newManager = manager.getManager(str); } catch (Exception e) { e.printStackTrace(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T02:52:59.703", "Id": "19403", "Score": "3", "body": "I am confused about what exactly is a constructor in the supplied code, but my impression is that in this case `manager.getManager(str)` should be called before the constructor gets called - thus there will not be an exception happening inside of the constructor. Sometimes the constructor has to throw an exception, but as you might guess - it is better to avoid it if you can without too much effort." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-03T09:54:51.937", "Id": "174589", "Score": "0", "body": "But doesn't placing a try/catch block in a constructor cause memory leaks? Please confirm guys and gals." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-03T10:05:31.340", "Id": "174590", "Score": "0", "body": "This looks more like a generic best-practices question than a request to review your code, especially since you didn't include the implementation of `TheManager.getManager()`. Also, `NewManager`, `TheManager`, and `Exception` looks like placeholders." } ]
[ { "body": "<p>Catching an exception and just printing stack trace and proceeding like nothing happened is certainly Very Bad. What if no one is watching the standard error stream (where <code>e.printStackTrace()</code> dumps its output)? In your case, you'll probably end up with <code>NullPointerException</code> later on, since <code>newManager</code> is not set. It could be one second from now, or one year from now, depending on when someone is trying to use <code>newManager</code>. You want to <a href=\"http://en.wikipedia.org/wiki/Fail-fast\">fail fast</a> instead.</p>\n\n<p>There's nothing wrong in throwing exceptions from constructors. Just make sure that, wherever you catch it, you handle it appropriately.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T08:45:17.833", "Id": "12059", "ParentId": "12058", "Score": "23" } }, { "body": "<p>Catching an exception should be done for one of two reasons. </p>\n\n<ol>\n<li>You want to log it before rethowing.</li>\n<li>You know how to handle the exception.</li>\n</ol>\n\n<p>If you don't know how to deal with an exception, catching it puts you into an unstable situation. You want to fail as quickly as possible for several reasons.</p>\n\n<p>Let me be clear: this does not mean you have to \"fix\" the exception, it means you know what to do to allow the application to continue to operate appropriately. If you don't know the consequences of the application continuing after an exception, then do not catch it, you're just setting yourself up for further problems.</p>\n\n<p>But if you can continue with reduced functionality or otherwise deal with the situation in an appropriate manner, then you should catch the exception and continue.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T07:31:10.580", "Id": "12133", "ParentId": "12058", "Score": "6" } } ]
{ "AcceptedAnswerId": "12059", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T08:16:46.840", "Id": "12058", "Score": "7", "Tags": [ "java" ], "Title": "Bad practice to have try / catch in constructor?" }
12058
<p>I have the following function in a <code>Service</code> class</p> <pre><code>protected function writeToFile():void{ var destinationFile:File = File.applicationStorageDirectory.resolvePath(_newPath); var fs:FileStream = new FileStream(); fs.open(destinationFile, FileMode.WRITE); fs.writeBytes(_buffer, 0, _buffer.length); fs.close(); } </code></pre> <p>this <code>Service</code> class should dispatch a <code>SuccessfulCreateLocalFileEvent</code> when <code>writeToFile</code> is successful and an <code>UnsuccessfulCreateLocalFileEvent</code> if <code>writeToFile</code> is unsuccessful.</p> <p>I know that <code>FileStream</code> functions <code>open</code> and <code>writeBytes</code> may throw <code>IOError</code> if there is any problems. And all these <code>FileStream</code> functions all have <code>void</code> as return types.</p> <p>I believe I need try catch, but I am not entirely sure how to do so.</p> <p>Please advise.</p> <p>This question is replicated at <a href="http://knowledge.robotlegs.org/discussions/questions/924-what-is-best-way-to-write-dispatch-events-in-this-service-class-function" rel="nofollow">http://knowledge.robotlegs.org/discussions/questions/924-what-is-best-way-to-write-dispatch-events-in-this-service-class-function</a> Experimenting which site has better answers for such a question.</p>
[]
[ { "body": "<p>FileStream class has its own events which are dispatched when the file operation is successful or not.</p>\n\n<p><a href=\"http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/filesystem/FileStream.html#eventSummary\" rel=\"nofollow\">http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/filesystem/FileStream.html#eventSummary</a></p>\n\n<p>A possible refactor of the code is</p>\n\n<pre><code>protected function writeToFile():void{\n _destinationFile = File.applicationStorageDirectory.resolvePath(_newPath);\n\n var fs:FileStream = new FileStream();\n\n fs.open(_destinationFile, FileMode.WRITE);\n fs.writeBytes(_buffer, 0, _buffer.length);\n\n fs.addEventListener(Event.CLOSE, dispatchFileCreatedEvent);\n\n fs.close(); \n\n}\n</code></pre>\n\n<p>Thanks to krasimir of knowledge Robotlegs Community for his help in arriving at this answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T02:03:27.463", "Id": "12179", "ParentId": "12061", "Score": "3" } }, { "body": "<p>I'm not familiar with ActionScript but it seems to me that <a href=\"http://www.designscripting.com/2011/02/try-catch-statement-in-actionscript-flash-try-catch-exception-handling-as3/\" rel=\"nofollow\">the usual try-catch-finally structure is available in this language</a> too. A possible usage could be the following:</p>\n\n<pre><code>var fs:FileStream = new FileStream();\ntry {\n fs.open(destinationFile, FileMode.WRITE);\n fs.writeBytes(_buffer, 0, _buffer.length);\n} finally {\n fs.close();\n}\n</code></pre>\n\n<p>It ensures that the file will be closed even something throws an <code>IOError</code> or other exception. </p>\n\n<p>I don't know how event dispatch works in ActionScript but maybe you could use something like this:</p>\n\n<pre><code>boolean successful = false;\ntry {\n var fs:FileStream = new FileStream();\n try {\n fs.open(destinationFile, FileMode.WRITE);\n fs.writeBytes(_buffer, 0, _buffer.length);\n } finally {\n fs.close();\n }\n successful = true;\n} finally {\n if (successful) {\n // dispatch a SuccessfulCreateLocalFileEvent here\n } else {\n // dispatch an UnsuccessfulCreateLocalFileEvent here\n }\n}\n</code></pre>\n\n<p>It sets the <code>successful</code> flag to <code>true</code> only if no file operation throws exception.</p>\n\n<p>If you want to handle errors locally, you'll need a catch block too:</p>\n\n<pre><code>boolean successful = false;\ntry {\n var fs:FileStream = new FileStream();\n try {\n fs.open(destinationFile, FileMode.WRITE);\n fs.writeBytes(_buffer, 0, _buffer.length);\n } finally {\n fs.close();\n }\n successful = true;\n} catch (IOError) {\n // handle IOError here\n} finally {\n if (successful) {\n // dispatch a SuccessfulCreateLocalFileEvent here\n } else {\n // dispatch an UnsuccessfulCreateLocalFileEvent here\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T11:08:50.850", "Id": "13214", "ParentId": "12061", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T10:41:34.827", "Id": "12061", "Score": "3", "Tags": [ "exception-handling", "actionscript-3", "error-handling", "actionscript" ], "Title": "Add events dispatching for ActionScript framework Robotlegs" }
12061
<p>This is a minimal little utility that I've found useful while reorganizing my music and book libraries. Any issues you can see? Anything I could be doing better or more elegantly? Anyone wanna take a crack at the equivalent in Python/Perl?</p> <p>Take 2:</p> <pre><code>#!/usr/bin/ruby require 'optparse' require 'pp' require 'fileutils' $options = {:sub =&gt; "", :downcase =&gt; nil} OptionParser.new do |opts| opts.on('-r', '--regex REGEX', String, 'Specify the regular expression to replace') {|reg| $options[:regex] = Regexp.new(reg)} opts.on('-s', '--sub SUBSTITUTE', String, 'Specify what to replace the match with. By default, the empty string (so matches are stripped).') {|$options[:sub]|} opts.on('-d', '--downcase', 'If passed, all filenames will be downcased.'){|$options[:downcase]|} end.parse! usage unless ARGV.length &gt; 0 def rename(str) ($options[:downcase] ? str.downcase : str).gsub($options[:regex], $options[:sub]) end ARGV.each do |target| File.rename(target, rename(target)) end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T18:10:21.557", "Id": "19427", "Score": "0", "body": "I wonder if it might be better for you to add to the question rather than update it based on the review? Here is a [meta discussion](http://meta.codereview.stackexchange.com/questions/518/ask-for-another-code-review-based-on-feedback-from-previous-answer)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T18:14:24.577", "Id": "19429", "Score": "0", "body": "@blufox - I'm of the opinion that having a working diff is better than having a very tall question with multiple code blocks. Any consensus on that discussion by the way? The question you link was closed before anyone answered either way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T18:22:05.817", "Id": "19430", "Score": "0", "body": "See the second [answer](http://meta.codereview.stackexchange.com/questions/210/how-are-reposts-handled-on-code-review) in the question linked as a duplicate of. I agree that the more reviews there are, the longer the question becomes, and perhaps reduces in understandability. Perhaps the site should provide some mechanism to fold the older revisions? Can we ask for it in meta? What do you think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T18:49:17.107", "Id": "19436", "Score": "0", "body": "@blufox - There should be an \"edited\" link on the question which essentially provides what was proposed in that answer. Except with change highlighting (which is why I think this is the better approach). The only annoyance (which happens either way) is that responders need to note which edit they are responding to, since there's no mechanism to associate an answer with a particular version of the question. A solution may be worth asking for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T20:56:29.883", "Id": "19441", "Score": "0", "body": "Do you think a note saying ([Original here](http://codereview.stackexchange.com/revisions/12070/1)) would help? Atleast in this case?" } ]
[ { "body": "<p>Some observations. The space between #! and the path to binary is not needed. (It used to be for some arcane versions of Unix but not anymore AFAIK)</p>\n\n<p>Secondly, I prefer to let env find ruby for portability.</p>\n\n<pre><code>#!/usr/bin/env ruby\n\nrequire 'optparse'\nrequire 'pp'\nrequire 'fileutils'\n</code></pre>\n\n<p>The options are globals. So perhaps it is better to specify that explicitly.\nThis will help in modularization later.</p>\n\n<pre><code>$options = {:sub =&gt; \"\", :downcase =&gt; nil}\n</code></pre>\n\n<p>In the interests of people who have to use 80 char width terminals, I advice\nan 80 cols limit (or near abouts) for lines :) .\nI would also advice on verbose and dryrun flags to tell the user what is going to happen, and what is happening.</p>\n\n<p>The stdlib example is to just call .parse! directly and I think that that style\nis more rubyish than creating a new variable optparse.</p>\n\n<pre><code>OptionParser.new do |opts|\n opts.on('-r', '--regex REGEX', String, \n 'Specify the regular expression to replace'){|$options[:regex]|}\n opts.on('-s', '--sub SUBSTITUTE', String, \n 'Specify what to replace the match with. By default, the \\\n empty string (so the matched patterns are \\\n stripped).'){|$options[:sub]|}\n opts.on('-d', '--downcase', 'If passed, all filenames will be \\\n downcased.'){|$options[:downcase]|}\nend.parse!\n</code></pre>\n\n<p>I like programs to give me the usage if they are invoked with no input values.</p>\n\n<pre><code>usage unless ARGV.length &gt; 0\n</code></pre>\n\n<p>I also think that the transformation of old name to new name should be a\nseparate method. And why embed a string inside a string and then transform\nto a regular expression when you can directly transform that string to a regexp?</p>\n\n<pre><code>def transform(str)\n ($options[:downcase] ? \n str.downcase : str).gsub(Regexp.new $options[:regex], $options[:sub])\nend\n</code></pre>\n\n<p>And given all these, I prefer a little more functional way of processing\nThe advantage is that you are restricting the IO to a very small portion.</p>\n\n<pre><code>ARGV.map{|target| [target, transform(target)]}.each do |old,new|\n File.rename(old, new)\nend\n</code></pre>\n\n<p>Now, these comments are highly subjective. But given the length of\nyour snippet, I suppose that is justified? Because it obviously works as given.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T00:04:00.287", "Id": "19350", "Score": "0", "body": "Took most of your advice. I'm not sure about that use of the ternary operator, but it does the job. `ARGV.map{|target| [target, transform(target)]}.each do |old,new|...` is this really a commonly accepted idiom in the Ruby world? Is there a particular reason you wouldn't just do `File.rename(target, transform(target))` instead?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T00:28:55.330", "Id": "19352", "Score": "0", "body": "As I mentioned, it is very subjective. I feel that all IO should be isolated, and the above kind of reflects that. It is even more clear if you were doing python list comprehensions or Haskell. But in ruby it is perhaps debatable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T23:38:54.097", "Id": "12083", "ParentId": "12070", "Score": "3" } } ]
{ "AcceptedAnswerId": "12083", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T15:55:44.810", "Id": "12070", "Score": "3", "Tags": [ "ruby" ], "Title": "File Renaming with Ruby" }
12070
<p>See the full calculator with HTML -> <a href="https://gist.github.com/1861120" rel="nofollow">https://gist.github.com/1861120</a> You should be able to drag that html file from github into a browser and start using it. I'm only putting the js below. The calculator works fine but JS Lint is telling me I have an unexpected 'function' doCalc line 9 character 1.</p> <p>Also just looking for some general tips on best practices and how this might be refactored. Any help is appreciated. Thank you.</p> <pre><code>var type, n, r, formula; Math.factorial = function (n) { if (n &lt; 2) { return 1; } return (n * Math.factorial(n - 1)); } function doCalc(type) { switch (type) { case 'permutation': n = document.permutation.T1.value; r = document.permutation.T2.value; formula = function() { document.permutation.T3.value = Math.factorial(n) / Math.factorial(n - r); } break; case 'combination': n = document.combination.T1.value; r = document.combination.T2.value; formula = function() { document.combination.T3.value = Math.factorial(n) / (Math.factorial(r) * Math.factorial(n - r)); } break; } n = Number(n); r = Number(r); if (isNaN(n) || isNaN(r)) { alert("Factorial requires a numberic argument."); return null; } formula(); } window.onload = function() { document.getElementById('calculate-p').onclick = function() { doCalc('permutation'); } document.getElementById('calculate-c').onclick = function() { doCalc('combination'); } } </code></pre>
[]
[ { "body": "<p>It's complaining that you haven't ended your assignment statment, <code>Math.factorial = ...</code>, with a semi-colon. (This is the case for just about every error jslint will throw with your code.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T19:59:42.740", "Id": "12078", "ParentId": "12076", "Score": "1" } }, { "body": "<p>Well, you asked for general tips, so here goes ;)</p>\n\n<p>I would almost always refrain from extending built-in types. I will \"shim\" to provide standard-compliant functions which are not available (e.g. \"forEach\" on Array.prototype), but adding new methods to existing types is a recipe for problems. You could simply have a <code>factorial</code> function without the <code>Math</code> and it would work just as well.</p>\n\n<p>In fact, you could do yourself a favor and create your own <code>Math</code> object (named something different, of course) and add your <code>formula</code> functions to that, so:</p>\n\n<pre><code>var MathFactor = new function () {\n this.factorial = function (n) {\n return n &lt; 2 ? 1 : n * this.factorial(n - 1);\n };\n this.permutate = function (n, r) {\n return this.factorial(n) / this.factorial(n - r);\n };\n this.combine = function (n, r) {\n return this.factorial(n) / (this.factorial(r) * this.factorial(n - r));\n };\n};\n</code></pre>\n\n<p>Then <code>doCalc</code> is just a matter of a simple numeric check, then setting your <code>T3.value</code> to the output of a call to <code>MathFactor.permutate()</code> or <code>MathFactor.combine()</code>. Hope that helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T00:13:28.620", "Id": "19351", "Score": "0", "body": "`new function` = eww... I'd just use `MathFactor` instead of `this` and change the function into an object (or declare it as a named type in an IIFE if I really wanted a singleton). Javascript anonymous singleton instantiation syntax is easy to miss and often unexpected to those who aren't aware of what you are doing (then they decide the `new` is unnecessary and wind up with unintended globals)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T21:44:23.283", "Id": "12082", "ParentId": "12076", "Score": "3" } }, { "body": "<p>You are getting jslint errors because of missing semicolons (the function expressions) and there are a few space issues (<code>function()</code> -> <code>function ()</code>). I would also make a few other changes:</p>\n\n<ol>\n<li>Wrap with an IIFE and pass in globals <a href=\"https://codereview.stackexchange.com/questions/11233/optimizing-and-consolidating-a-big-jquery-function/11235#11235\">[see also]</a></li>\n<li>Add a \"use strict\"; line to use strict es5 syntax</li>\n<li>Change factorial to be iterative so it works on numbers > 3000 (the Firefox recursion limit)</li>\n<li>Get rid of the unused type variable</li>\n<li>Move the variables local to doCalc to actually be local</li>\n<li>Extract methods for the permutation and combination functions (and since we are already extending Math, why not put them there? - edit: I would prefer not doing it in the first place but didn't feel like suggesting that)</li>\n<li>Since the switch statement is now almost the same, simplify the code by replacing the string <code>type</code> parameter to be a function parameter</li>\n<li>Inline the repetitive assignments to <code>n</code> and <code>r</code></li>\n</ol>\n\n<h3>Results</h3>\n\n<pre><code>(function (Math, window, document) {\n \"use strict\";\n\n Math.factorial = function (n) {\n var r = n;\n while (n &gt; 1) {\n r = r * n;\n n -= 1;\n }\n return r;\n };\n\n Math.permutation = function (n, r) {\n return Math.factorial(n) / Math.factorial(n - r);\n };\n\n Math.combination = function (n, r) {\n return Math.factorial(n) / (Math.factorial(r) *\n Math.factorial(n - r));\n };\n\n function doCalc(formula) {\n var n = Number(document.permutation.T1.value),\n r = Number(document.permutation.T2.value);\n if (isNaN(n) || isNaN(r)) {\n window.alert(\"Factorial requires a numberic argument.\");\n return null;\n }\n document.permutation.T3.value = formula(n, r);\n }\n\n window.onload = function () {\n document.getElementById('calculate-p').onclick = function () {\n doCalc(Math.permutation);\n };\n document.getElementById('calculate-c').onclick = function () {\n doCalc(Math.combination);\n };\n };\n}(Math, window, document));\n</code></pre>\n\n<p>There is still more to do with this code. For example you shouldn't use the <code>on*</code> properties to attach events because it overrides existing ones.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T21:05:32.680", "Id": "19364", "Score": "0", "body": "You and @MikeMcCaughan both gave some really great feedback. My reputation is too low to even vote you up! Please vote up the question so I can vote up your answers. One thing I want to note is that JSLint apparently wants a space between function (n) but not function(). Something about when declaring with parameters it can be mistaken for a name. I don't see how but yeah." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T00:01:24.690", "Id": "12084", "ParentId": "12076", "Score": "2" } } ]
{ "AcceptedAnswerId": "12084", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T19:47:19.943", "Id": "12076", "Score": "3", "Tags": [ "javascript" ], "Title": "JSLint says \"unexpected function\" doCalc" }
12076
<p>I am trying to optimize inserts from a returned JSON which contains data from multiple tables on the remote server. My code is working, but I just want to figure out a way for it to work better. I need the structure to be very dynamic (i.e. fetching the table names from JSON then looping through to complete the inserts into SQLite). This is so if a table is added in the future, I will not have to change any code.</p> <pre><code>private boolean prepReturnedData(String newString) throws JSONException { long errCheck = 0; // tracks valid db inserts. JSONArray columns = new JSONArray(); JSONObject jsonObj = new JSONObject(newString); ArrayList&lt;String&gt; tables = new ArrayList&lt;String&gt;(); Iterator&lt;?&gt; tableKeys = jsonObj.keys(); while (tableKeys.hasNext()) { tables.add(tableKeys.next().toString()); } for (String table : tables) { // Loop through table names. columns = jsonObj.getJSONArray(table); for (int index = 0; index &lt; columns.length(); index++) { // Loop through Array of Entries ContentValues cv = new ContentValues(); // Figure out where to put this. Iterator&lt;?&gt; iter = columns.getJSONObject(index).keys(); // Creates an Iterator containing Column names. JSONObject newObj = columns.getJSONObject(index); // Creates a new JSONObject for retrieving column values. while (iter.hasNext()) { // Iterates to get Column names. String tColumn = iter.next().toString(); // Stores column name, for retrieval of column value. cv.put(tColumn, newObj.get(tColumn).toString()); } // end column iterator loop. String status = null; if (table == "Seizures") { status = "timestamp"; } else { status = "name"; } try { SQLiteDatabase db = this.getWritableDatabase(); errCheck = db.replace(table, status, cv); if (db.isOpen()); {db.close(); }; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // end entry loop } // end table loop if (errCheck &gt;= 0) { return true; } else { return false; } } </code></pre> <p>This function is within a <code>DatabaseHelper</code> class.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T16:53:43.677", "Id": "19343", "Score": "0", "body": "Every real database has a support for something that is called bulk insert. Look for it, check out this blog http://blog.quibb.org/2010/08/fast-bulk-inserts-into-sqlite/" } ]
[ { "body": "<p>When in doubt, run SQL statements, of either form:</p>\n\n<ul>\n<li><code>insert into table (col1, col2, ...) values ('val11', 'val12', ...), ('val21', 'val22', ...)</code></li>\n<li><code>insert into table (col1, col2, ...) values (@val1, @val2)</code></li>\n</ul>\n\n<p>Theoretically a proper DBMS would cache the plan for #2 and you could just loop through your values feeding the parameters one by one and executing each in row. Sqlite has different goals though, so the first version could be better (faster?), try em and see.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T15:51:41.457", "Id": "19353", "Score": "0", "body": "This sqlite under android I am working on. As far as I know you cannot simply run sql statements in this manner." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T15:52:40.777", "Id": "19354", "Score": "0", "body": "Are you sure? I see an `execSQL` method in the documentation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T16:06:48.887", "Id": "19355", "Score": "0", "body": "It is too early in the morning, you are correct about execSQL, I even use it in multiple places in my code. I am just wondering whether there would be any real change in efficiency by running a loop to assemble the large query then executing it, or using the prebuilt db.replace method in a loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T16:19:39.517", "Id": "19356", "Score": "0", "body": "Wouldn't know, I have an iPhone (nor do I use the desktop version of Sqlite). Try it and see, it's really not that much code to write." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T16:51:17.970", "Id": "19357", "Score": "0", "body": "@Blindy: execSQL call allows only single sql command!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T17:06:46.887", "Id": "19358", "Score": "0", "body": "What's your point? I gave both versions with one statement per round-trip in mind." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T15:45:47.567", "Id": "12086", "ParentId": "12085", "Score": "1" } }, { "body": "<p>I suggest some optimizations:</p>\n\n<ul>\n<li><p>Do not initialize columns with empty <code>JSONArray</code> - it will always be overwritten.</p></li>\n<li><p>Do not iterate twice and do not create overhead <code>ArrayList</code> object you can iterate json object once.</p></li>\n<li><p>Due to Android specific garbage collection it's better to reuse object than create a new one in each iteration (see where is declared <code>ContentValues cv = new ContentValues();</code> and cleared then later).</p></li>\n<li><p>Open database once not in loop -> be sure to close it (<code>finally</code> block).</p></li>\n<li><p>Your error reporting is leaky - the next db.replace would clear off the former <code>errCheck</code> value - I added some simple handling but I did not know the requirements in that area.</p>\n\n<pre><code>private boolean prepReturnedData(String newString) throws JSONException {\n JSONObject jsonObj = new JSONObject(newString);\n\n if(jsonObj.length() &gt; 0) {\n Iterator&lt;?&gt; tableKeys = jsonObj.keys();\n SQLiteDatabase db = null;\n\n try {\n db = getWritableDatabase();\n db.beginTransaction();\n\n ContentValues cv = new ContentValues();\n\n String table;\n JSONArray columns;\n\n String status;\n int columnsLength;\n JSONObject columnJson;\n Iterator&lt;?&gt; columnKeys;\n\n String tColumn;\n\n while (tableKeys.hasNext()) {\n table = tableKeys.next().toString();\n columns = jsonObj.getJSONArray(table);\n status = table == \"Seizures\" ? \"timestamp\" : \"name\";\n columnsLength = columns.length();\n\n for (int i = 0; i &lt; columnsLength; i++) { // Loop through Array of Entries\n cv.clear();\n\n columnJson = columns.getJSONObject(i); // Creates a new JSONObject for retrieving column values.\n columnKeys = columnJson.keys(); // Creates an Iterator containing Column names.\n\n while (columnKeys.hasNext()) {\n tColumn = columnKeys.next().toString();\n cv.put(tColumn, columnJson.optString(tColumn, \"\"));\n }\n\n\n if(db.replace(table, status, cv) == -1L) {\n throw new IllegalStateException(\n \"Insert failed for table: \" + table + \n \", contentValues: \" + cv.toString());\n }\n }\n }\n\n db.setTransactionSuccessful();\n }\n catch(Throwable e) {\n\n return false;\n }\n finally {\n if (db != null &amp;&amp; db.isOpen()) {\n db.endTransaction();\n db.close(); \n };\n }\n }\n\n return true;\n} \n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T17:37:19.583", "Id": "19359", "Score": "0", "body": "Thank you this seems like a very sensible, and less error prone approach." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T16:55:28.763", "Id": "12087", "ParentId": "12085", "Score": "4" } } ]
{ "AcceptedAnswerId": "12087", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T15:36:53.963", "Id": "12085", "Score": "3", "Tags": [ "java", "optimization", "android", "sqlite" ], "Title": "Optimizing mass inserts into SQLite" }
12085
<p>I have a Core Data model with two entities: <code>Video</code> and <code>Playlist</code>.</p> <ul> <li>A <code>Video</code> can be a member of many <code>Playlist</code>s</li> <li>A <code>Playlist</code> can have many <code>Video</code>s, including the same <code>Video</code> multiple times</li> <li>A <code>Playlist</code>'s <code>Video</code>s are ordered</li> </ul> <blockquote> <p><code>Video</code> &lt;&lt;----->> <code>Playlist</code></p> </blockquote> <p>That being said, I've decided that I need a third entity: <code>Playlist Item</code>.</p> <ul> <li>A <code>Playlist Item</code> has an index</li> <li>A <code>Playlist Item</code> can only have a relationship with one <code>Video</code> entity and one <code>Playlist</code> entity</li> </ul> <p>And so, this causes the original specification to be revised...</p> <ul> <li>A <code>Video</code> can have many <code>Playlist Item</code>s</li> <li>A <code>Playlist</code> can have many <code>Playlist Item</code>s, but each <code>Playlist Item</code> has a unique index</li> <li>A <code>Playlist</code>'s <code>Playlist Item</code>s are ordered using the index attribute</li> </ul> <p><code>Video &lt;----&gt;&gt; Playlist Item &lt;&lt;----&gt; Playlist</code></p> <p>So, the addition of the <code>Playlist Item</code> entity allows me to have many-to-many relationships between <code>Video</code> and <code>Playlist</code> and still maintain ordered lists. Adding this third entity however adds complexity to the overall design.</p> <p>I am wondering if it is wise to hide that complexity managing the <code>Playlist Item</code> objects in the <code>Video</code> and <code>Playlist</code> implementations.</p> <p><strong><code>Video</code></strong></p> <pre><code>@interface Video : NSManagedObject @property (strong, nonatomic) NSSet *playlists; // Custom accessor; Transient attribute; data persisted in Playlist Item // No declared NSSet for playlistItems @end </code></pre> <p><strong><code>Playlist</code></strong></p> <pre><code>@interface Playlist: NSManagedObject @property (nonatomic, strong) NSArray *videos; // Custom accessor... // No declared playlistItems here either! @end </code></pre> <p>It seems by doing this I will gain code that is better at revealing intentions.</p> <p>The code smell I'm getting is that <code>NSManagedObjects</code> subclasses are model classes and should therefore not have any controller type glue. Furthermore it makes my <code>Video</code> and <code>Playlist</code> classes completely dependent upon the <code>Playlist Item</code>s class. But, all of that said writing the accessor is trivial, which is why I'm considering this approach:</p> <pre><code>- (NSArray *)videos { [self willAccessValueForKey:@"videos"]; NSArray *v = [self primitiveVideos]; [self didAccessValueForKey:@"videos"]; if (v) { return v; } NSSet *pi = [self playlistItems]; NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"index" ascending:YES]; NSArray *orderedPlaylistItems = [pi sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; NSUInteger count = [orderedPlaylistItems count]; NSMutableArray *videos = [NSMutableArray arrayWithCapacity:count]; for (int index = 0; index &lt; count; index++) { [videos addObject:[[orderedPlaylistItems objectAtIndex:index] video]]; } v = videos; [self setPrimitiveVideos:v]; return v; } </code></pre> <p><em>(This code is pretty rough, but you get the point, a few lines and voila! an array of video objects from the set of playlist items)</em></p> <p>Maybe there is a design pattern or best practice that would help guide my decision?</p>
[]
[ { "body": "<p>Perhaps I'm missing something, but it seems that the <code>Video</code> objects don't really need to know about what playlists they belong to, do they?</p>\n\n<p>A playlist is a collection of videos. You don't need a playlist index object. You just need an array on each playlist that keeps track of what videos are on its playlist and in what order. A simple array does all this for you.</p>\n\n<p>It seems to me that the only reason a video would need to know what playlists it belonged to is if you wanted to provide some functionality for a video to quickly find all playlists it belonged to. And when I say this, I mean a request where it's important for this information to be returned near instantly.</p>\n\n<p>Even without the video knowing any information about the playlists, your code could still iterate through every playlist asking it whether or not it contained a given video and get the answer to what all playlists the video belongs to. This might be a little time consuming, but I think it's a rare request.</p>\n\n<p>But it seems what's most likely is that a user will either want to play an individual video, or play a playlist. The request to play all playlists that contain this particular video seems an odd one to me.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-06T15:16:40.887", "Id": "99012", "Score": "0", "body": "You are correct, however the Core Data framework forces my hand a bit - to-many relationships are represented as `NSSet`s not `NSArrays`. That's really the crux of the problem. The backward relationship (from video to playlist) is a consequence of how Core Data models relationships and maintains referential integrity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-06T15:17:49.547", "Id": "99013", "Score": "0", "body": "Oh, now I understand. Let me think about this bit and see if I can come up with a better solution." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-05T18:45:33.607", "Id": "56216", "ParentId": "12089", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T00:58:01.077", "Id": "12089", "Score": "2", "Tags": [ "objective-c", "ios", "core-data" ], "Title": "Core Data model of video and entities" }
12089
<p>I find myself nesting a lot of grids inside grids in WPF. I just found myself 3 Grids deep, and stopped to think: "Should I be doing this?" Is there some kind of performance cost? Is it unmaintainable? (Kind of like heavily nested <code>if</code>s maybe.)</p> <p>I guess the alternative is to have one grid, and use a whole lot of column spans.</p> <p>(You may ignore the use of Events, I am aware commands are prob a better idea)</p> <pre class="lang-xml prettyprint-override"><code>&lt;Grid Name="grid"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid Grid.Column="1"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="20"/&gt; &lt;RowDefinition/&gt; &lt;RowDefinition Height="20"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition/&gt; &lt;ColumnDefinition/&gt; &lt;ColumnDefinition/&gt; &lt;ColumnDefinition/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Button Grid.Row="0" Grid.Column="0" VerticalAlignment="Top" HorizontalAlignment="Left" Click="btnStart_Click" Content="New Game"/&gt; &lt;Button Grid.Row="0" Grid.Column="1" VerticalAlignment="Top" HorizontalAlignment="Center" Click="btnRun_Click" Content="Run"/&gt; &lt;Button Grid.Row="0" Grid.Column="2" VerticalAlignment="Top" HorizontalAlignment="Center" Click="btnUndo_Click" Content="Undo"/&gt; &lt;Button Grid.Row="0" Grid.Column="3" VerticalAlignment="Top" HorizontalAlignment="Right" Click="btnStep_Click" Content="Step"/&gt; &lt;Grid Grid.Row="1" Grid.ColumnSpan="4"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition/&gt; &lt;RowDefinition/&gt; &lt;/Grid.RowDefinitions&gt; &lt;board:BoardView x:Name="boardView" Grid.Row="0" Background="Firebrick"/&gt; &lt;GridSplitter ResizeDirection="Rows" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" /&gt; &lt;TextBox Name="txtLog" Grid.Row="1" Text="{Binding Path=GameLog.Log, Mode=TwoWay}" VerticalScrollBarVisibility="Visible" FontFamily="Global Monospace" AcceptsReturn="True" Height="260" VerticalAlignment="Stretch"/&gt; &lt;/Grid&gt; &lt;CheckBox Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" Content="Use Algebraic Notation" IsChecked="{Binding Path=UseAlgebraicNotation}"/&gt; &lt;/Grid&gt; &lt;ContentControl Grid.Column="0" Content="{Binding Path=Game.BlackPlayer}" Margin="3" /&gt; &lt;ContentControl Grid.Column="3" Content="{Binding Path=Game.WhitePlayer}" Margin="3" /&gt; &lt;/Grid&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-27T17:24:07.883", "Id": "19373", "Score": "0", "body": "If you asked me, if it makes sense to logically group the content within a grid, then go for it. If they're unrelated then you definitely should rethink what you're doing." } ]
[ { "body": "<p>The Grid is the most powerful layout control in XAML technology. Since you use a Grid inside another probably you already considered use another layout control first. But they can't fit where you want. In many cases I will need a layout control I think about some things:</p>\n\n<ol>\n<li>Can I stack these controls vertically or horizontally? So I use StackPanel.</li>\n<li>I want only a visual effect and will have only one child? So I use Border.</li>\n<li>I want to stack these controls but one of then need to fill the last? Use DockPanel.</li>\n</ol>\n\n<p>The layout controls other than Grid are very specific. The Grid gives to you the power to\nchoose your interface that is simpler to modify.</p>\n\n<p>As soon as you put a Grid inside other you made for other person easier to change things. You separate the logic of every part of your interface so it became compact in each part.</p>\n\n<p>P.S. Canvas I never used. Use only if you need to code something like drag n' drop or you need something that need to be very hard coded in the screen. (I can't remember things other than drag'n'drop). If you try to use only one Grid you can. But it will be very difficult for you and any people that need work on that code. If you open any Framework control you can see that its uses o lot of grids too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-07T20:06:03.530", "Id": "12358", "ParentId": "12091", "Score": "7" } }, { "body": "<p>It's better to use nested grids that are easy to read, than complex spanning. I try to avoid spanning in most scenarios, unless it's just 1 simple span. But when in doubt, nest the grids, because that way future layout changes won't break everything where as spanning is directly tied to the number of columns you have.</p>\n\n<p>A great example of this is headers and footers, you wouldn't want them to not fill the width of an app, </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T19:38:42.173", "Id": "26723", "ParentId": "12091", "Score": "17" } } ]
{ "AcceptedAnswerId": "26723", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T06:06:02.887", "Id": "12091", "Score": "28", "Tags": [ "c#", "wpf", "layout", "xaml" ], "Title": "Is nesting grids a good idea?" }
12091
<p>I took my first stab at a user authentication function. I invented my own way of doing this. Is this a safe and efficient way of giving a user Read/Edit/Delete permission on tables in a MySQL database?</p> <h2>The Class</h2> <pre><code>class Personnel { //set tables that will need permissions and actions protected static $actions = array("read", "edit", "delete"); protected static $table_names = array("species", "users", "news"); //this will generate a form with checkbox for each position in the permissions array public static function set_permissions_form($current_permissions) { for($i=0; $i&lt;count(self::$table_names); $i++) { $table_name = self::$table_names[$i]; $form .= $table_name . ":&lt;br /&gt;"; for($z=0; $z&lt;count(self::$actions); $z++) { $action = self::$actions[$z]; $form .= $action . ": &lt;input type='checkbox' name='permissions[" . $table_name . "][" . $action . "]'"; if($current_permissions) { $form .= ($current_permissions[$table_name][$action] == "1" ? " checked =\"checked\"" : ""); } $form .= " value=1 /&gt;"; $form .= "&lt;br /&gt;"; } } return $form; } } </code></pre> <h2>The Form</h2> <p>If this is a new user or an existing user with no permissions set then <code>$current_permissions</code> will be <code>NULL</code>. If a permissions array does exist in the database unserialize it and check any checkbox when name = array key.</p> <pre><code>$current_permissions = unserialize($personnel-&gt;permissions); $form = "&lt;form action='save_personnel.php' method='post'&gt;"; $form .= Personnel::set_permissions_form($current_permissions); $form .= "&lt;input type='submit' value='Save Changes' /&gt;"; $form .= "&lt;/form&gt;"; echo $form; </code></pre> <h2>Save</h2> <p>Once the form is submitted each box checked will be a "1" in the permissions array. This next snippet serializes the array and stores it in the database. I did not include code for $personnel->save() but you know what it does. Create user if does not exist, update user if it does.</p> <pre><code>$personnel = new Personnel(); $personnel-&gt;permissions = serialize($_POST['permissions']); if($personnel-&gt;save()) { redirect_to("manage_personnel.php"); } </code></pre> <h2>Check for Permission</h2> <p>The next steps I haven't completed yet but basically it will pull <code>$personnel-&gt;permissions</code> from database and unserialize it. Then say it is on a page where user is trying to edit species, <code>$permissions["species"]["read"] == '1' ? you shall pass : you shall not pass;</code>.</p> <p>Am I heading in the right direction with this or am I over complicating?</p>
[]
[ { "body": "<p>I think storing the serialized php structure to the database is not a good practice.</p>\n\n<p>You can make a separate table like this</p>\n\n<pre><code>permissions\n\n user_id \n\n table_id\n\n read - boolean\n\n update - boolean\n\n delete - boolean\n</code></pre>\n\n<p>Three boolean values ​​can be easily encoded into int(1), but I do not think it's worth doing.</p>\n\n<p>and this </p>\n\n<pre><code>editable_tables\n\nid - index\n\nname - real table name or pattern like '*'\n</code></pre>\n\n<p>when editing in php you can show all the tables from <code>editable_tables</code>. store data in the <code>permissions</code> to only those who have rights.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T13:43:21.857", "Id": "12093", "ParentId": "12092", "Score": "0" } }, { "body": "<p><strong>Loops</strong></p>\n\n<p>Why are you using a for loop? I would just use a foreach loop, its much more efficient, especially for what you are doing here.</p>\n\n<pre><code>foreach(self::$table_names as $table_name) {\n //etc...\n}\n</code></pre>\n\n<p><strong>Strings</strong></p>\n\n<p>The following are micro-optimizations, but ones that are usually accepted as standard practice.</p>\n\n<p>Single quotes should be used if no PHP processing is to be performed on a string. In other words, there are no PHP variables in the string. This is a micro optimization because it doesn't really add any noticeable overhead to your script. However, doing this you'll notice that you wont have to escape quotes nearly as frequently as you would have to if you started with single quotes. This is especially handy when dealing with HTML or XML attributes, which I'll get into soon.</p>\n\n<pre><code>$form .= $table_name . ':&lt;br /&gt;';\n</code></pre>\n\n<p>Double quotes should be used for strings that require PHP processing.</p>\n\n<pre><code>$form .= \"$table_name:&lt;br /&gt;\";\n</code></pre>\n\n<p><strong>HTML/XML Attributes</strong></p>\n\n<p>While most browsers accept it, it is still improper syntax to use single quotes on HTML/XML tag attributes. XML will actually produce errors. Either escape the double quotes or escape the string and only go back into PHP for the variables.</p>\n\n<pre><code>$form .= $action . \": &lt;input type=\\\"checkbox\\\" name=\\\"permissions[$table_name][$action ]\\\"\";\n//OR\n&lt;input type=\"checkbox\" name=\"permissions[&lt;?php echo $table_name; ?&gt;][&lt;?php echo $action; ?&gt;]\"\n</code></pre>\n\n<p><strong>Sanitizing and Validating</strong></p>\n\n<p>You shouldn't handle raw POST data. Always sanitize and validate it. Check out PHP's <code>filter_input()</code> function. That goes right along with what Shaad said about passing serialized data to your tables too. Its not a good idea, especially if it hasn't been sanitized and validated.</p>\n\n<p><strong>Comparisons</strong></p>\n\n<p>I would use absolute equality comparisons when checking for current permissions rather than loose comparison as your <code>$actions</code> table should only have boolean values. Also the quotes around an integer is unnecessary, unless you are comparing a string with absolute equality.</p>\n\n<pre><code>$form .= ($current_permissions[$table_name][$action] === TRUE ? \" checked =\\\"checked\\\"\" : \"\"); \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T00:49:10.177", "Id": "19445", "Score": "0", "body": "Thanks this was very helpful. I am attempting to redo using a table to store permissions instead of an array but am stuck on the logic of getting the selected permissions from the submitted form to the table. The key is that the # of permissions and tables that they control must be changed in one spot." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T19:15:45.453", "Id": "12152", "ParentId": "12092", "Score": "2" } } ]
{ "AcceptedAnswerId": "12152", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T23:53:32.697", "Id": "12092", "Score": "6", "Tags": [ "php", "mysql", "authentication", "crud" ], "Title": "User Authentication/Permissions for PHP MySQL CRUD" }
12092
<p>I'm working right now in a readers social network. The main points are this:</p> <ol> <li>When an user connects with his account I save his user id in the session variable. </li> <li>My MVC is working with DTO's all the way, filling the necessary variables for the presentation in the model.</li> </ol> <p>So, everything was ok, until today that I had to do a function that returns a DTO that has all the information of an user profile page. User profile pages can be accessed by anyone who has an account (Like Facebook user pages). </p> <p>This profile page, shows a button "Follow" if the profile is not the profile of the current user (to avoid you following yourself). If we are following that user, it will display an unfollow button.</p> <p>So I was thinking that the <code>UserProfileDTO</code> must have two boolean:</p> <p><code>isTheCurrentUser</code> and <code>isFollowedByTheCurrentUser</code>.</p> <pre><code>public class UserProfileDTO { private Long id; private String username; private Boolean isCurrentUser; private Boolean isfollowedByCurrentUser; ... </code></pre> <p>And the Domain Controller</p> <pre><code>public User getUserProfile(String username, Long currentUserId) throws UserNameDoesntExist { UserProfileDTO user = dataController.getUserByUsername(username); if(user != null) { user.setIsCurrentUser(currentUserId == user.getId()); user.setIsFollowedByCurrentUser(dataController.isFollowed(user.getId(), currentUserId)); ... </code></pre> <p>But I thought, "This DTO will be filled with information at the domain model. So the domain must have information that the presentation had first. That information is the current connected user, thus that will create a dependency between the two layers. </p> <p>Am I correct? Should the domain model be ignorant about who the current connected user is? Or is what I am doing okay?</p>
[]
[ { "body": "<ol>\n<li><p>I'd create an <code>UserProfilePageDTO</code> to separate that information:</p>\n\n<pre><code>public class UserProfilePageDTO {\n\n private UserProfileDTO userProfile;\n\n private Boolean isCurrentUser;\n private Boolean isfollowedByCurrentUser;\n ...\n}\n</code></pre></li>\n<li><p><code>UserNameDoesntExist</code> - it seem unusual a little bit because of the <code>nt</code>. I'd call it <code>UsernameDoesNotExists</code> or <code>UserNotFoundException</code> (same pattern as <code>ClassNotFoundException</code> and <code>FileNotFoundException</code> from JDK).</p></li>\n<li><p>I'd consider using a <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\">guard clause</a>:</p>\n\n<pre><code>public User getUserProfile(String username, Long currentUserId) \n throws UserNotFoundException {\n UserProfileDTO user = dataController.getUserByUsername(username);\n if (user == null) { \n throw new UserNotFoundException(...);\n }\n user.setIsCurrentUser(currentUserId == user.getId());\n user.setIsFollowedByCurrentUser(dataController.isFollowed(user.getId(), currentUserId));\n ...\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-09T00:03:12.513", "Id": "43827", "ParentId": "12094", "Score": "5" } } ]
{ "AcceptedAnswerId": "43827", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T15:26:32.347", "Id": "12094", "Score": "4", "Tags": [ "java", "mvc", "dto" ], "Title": "Is the \"current connected user\" an information that should be shared with the domain?" }
12094
<p>The code below is for modern browsers only.</p> <p>Naming conventions are as follows:</p> <pre><code>m or M - Model v or V - View c or C - Controller /******************************************************************************************** ******************************************************************************************** *( C )ontrol * Cin - Input Path * COut - Ouput Path ******************************************************************************************** *******************************************************************************************/ /** *COut */ var COut = ( function () { var messages = { name: 'Please enter a valid name', email: 'Please enter a valid email', email_s: 'Please enter a valid email.', pass: 'Please enter password, 6-40 characters', url: 'Please enter a valid url', title: 'Please enter a valid title', tweet: 'Please enter a valid tweet', empty: 'Please complete all fields', same: 'Please make emails equal', taken: 'Sorry, that email is taken', validate: 'Please contact &lt;a class="d" href="mailto:foo@@host.com"&gt;support&lt;/a&gt; to reset your password' . .. ... .... </code></pre>
[]
[ { "body": "<p>The code within the functions seems clear and simple to me, so my answer mostly focus on the naming conventions:</p>\n\n<ol>\n<li><p>Why call your variables m..., v..., c... when you could call them \"model\", \"view\", \"controller\"? This would make your code immediately clearer to anyone who reads it.</p></li>\n<li><p>The functions under \"CIn\" are also prefixed with \"c\", which is redundant. Since COut is a controller, it is obvious, that its functions are controller functions so they could simply be called \"tryIt\", \"block\", etc.</p></li>\n<li><p>Strictly speaking, in MVC, the role of a controller is to handle user input <em>and</em> (optionally) to output data. There is not one controller for input and another one for output, both should be handled by the same controller. It might make sense however to wrap output operations in a separate class. In Kohana for instance there's a \"Response\" object. This is pretty much what you've done with COut, except that you shouldn't call it a controller since that's not really what it is. You could call it \"Response\" or \"Output\" for example. \"HtmlResponse\" might be a good choice too as that would allow you to also have \"JsonResponse\", \"XmlResponse\", etc.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T16:05:52.500", "Id": "19389", "Score": "0", "body": "- Originally I spelled it out...but MVC is so prevalent + I provided a key" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T16:07:13.683", "Id": "19390", "Score": "0", "body": "- In the explanations I've seen output is not optional for a Controller class. If you have reference otherwise, please let me know." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T16:09:17.143", "Id": "19392", "Score": "0", "body": "- Additionally, I've removed the module patterns as I don't need closure...a simple function object will be more efficient. I will update here in a bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T16:17:37.570", "Id": "19394", "Score": "0", "body": "- This is the model I'm using http://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T16:17:51.953", "Id": "19395", "Score": "0", "body": "- It shows all data in/out of Controller" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-27T03:50:59.193", "Id": "12102", "ParentId": "12098", "Score": "1" } } ]
{ "AcceptedAnswerId": "12102", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T20:17:01.477", "Id": "12098", "Score": "1", "Tags": [ "javascript", "mvc", "library-design" ], "Title": "Foo - Control | Naming conventions update" }
12098
<p>Could you explain to me which code is better (more optimal) and why?</p> <p>Vesion 1:</p> <pre><code>while(something){ Runnable task = (Runnable) taskQueue.dequeue(); Throwable ex = null; ... } </code></pre> <p>Version 2:</p> <pre><code>Runnable task; Throwable ex; while(something){ task = (Runnable) taskQueue.dequeue(); ex = null; ... } </code></pre> <p>For me it looks like second version is optimized because variable declaration is out of while loop.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T21:06:46.143", "Id": "19365", "Score": "6", "body": "Any compiler worth its salt would move the declaration out for you automatically. Use the second if task and ex are to be accessed outside the block. Otherwise no recommendation here." } ]
[ { "body": "<p>At the bytecode level, there is no such thing as inner block. All local variables are declared at the scope of the method. As a result, both your variants should produce equivalent bytecode. To make sure, decompile them with javap and look at the bytecode. From the programmer's point of view, version 1 is more clear and concise.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T07:03:07.200", "Id": "12116", "ParentId": "12099", "Score": "3" } }, { "body": "<p>The first code style is more preferred according to concept \"minimization of life variables\" (R. Martin \"Clean code\"). In byte-code there is no diff.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T10:20:43.733", "Id": "12118", "ParentId": "12099", "Score": "0" } } ]
{ "AcceptedAnswerId": "12116", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T20:48:31.813", "Id": "12099", "Score": "2", "Tags": [ "java", "optimization" ], "Title": "Java - Object declaration out of while loop" }
12099
<p>I have n-times similar statements</p> <pre><code> if trigger_data.tt_closed unless trouble_ticket.changes.key?(:status) @run = 0 break end unless trouble_ticket.changes[:status][1] == "Closed" @run = 0 break end end if trigger_data.tt_assignee unless trouble_ticket.changes.key?(:assigned_to) @run = 0 break end unless trouble_ticket.changes[:assigned_to][1] == trigger_data.tt_assignee @run break end end </code></pre> <p>How to refactoring that code? Maybe dynamic statement build with pass some hash to input. I'm newbie in metaprogramming. Give me advise please</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T22:49:55.827", "Id": "19367", "Score": "0", "body": "Did you forget @run = 0 in the final one?" } ]
[ { "body": "<p>Are you inside a loop? Here is a possible way of doing it</p>\n\n<pre><code>def check(td, tt, trigger, key, ticket_changes)\n if td.send(trigger)\n unless tt.changes.key?(key)\n @run = 0\n return true\n end\n unless tt.changes[key][1] == ticket_changes\n @run = 0\n return true\n end\n end\n return false\nend\n\ndef metacheck(td, tt)\n [[:tt_closed, :status, \"Closed\"],\n [:tt_assignee, :assigned_to, td.tt_assignee]].each do |k|\n return if check(td, tt, k[0], k[1], k[2])\n end\nend\n\n\nmetacheck(trigger_data, trouble_ticket)\n</code></pre>\n\n<p>I have used an array of triplets to check the conditions.\nThe check can further be simplified as </p>\n\n<pre><code>def check(td, tt, trigger, key, ticket_changes)\n return false unless td.send(trigger)\n if !tt.changes.key?(key) or (tt.changes[key][1] != ticket_changes)\n @run = 0\n return true\n end\n return false\nend\n</code></pre>\n\n<p>We can join all the conditions together. But I think this captures the original intension best.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T23:14:11.913", "Id": "12101", "ParentId": "12100", "Score": "1" } } ]
{ "AcceptedAnswerId": "12101", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T21:25:46.733", "Id": "12100", "Score": "0", "Tags": [ "ruby" ], "Title": "Ruby code refactoring" }
12100
<p>I wrote this algorithm to determine the winning hand of two players going head to head with a hand of One Pair. Note that the hand is sorted once it is given out, and the algorithm has to compare the two hands one pair, if one has a higher one pair such as AA vs 33, there is an obvious winner. If the hands have matching one pairs, such as 44 &amp; 44, the high card must be compared to determine the winner.</p> <p>Please take a look at let me know how it looks. It is my first real algorithm taking into account so many factors. I am looking more for opinions, not answers. If you feel it is no good and needs improvement, please tell me so. It does work 100% as I have ran a lot of tests using different one pair hands of different values. </p> <pre><code> // Arrays to hold matching pair and high card PlayingCard[] pPairHigh = new PlayingCard[2]; PlayingCard[] oPairHigh = new PlayingCard[2]; for(int i = 0; i &lt; POKER_HAND_SIZE - 1 ; i++) { if(this.hand[i].compareTo(this.hand[i+1]) == 0) { pPairHigh[0] = this.hand[i]; if(i == 3) pPairHigh[1] = this.hand[i - 1]; else pPairHigh[1] = this.hand[POKER_HAND_SIZE - 1]; } if(otherHand.hand[i].compareTo(otherHand.hand[i+1]) == 0) { oPairHigh[0] = otherHand.hand[i]; if(i == 3) oPairHigh[1] = otherHand.hand[i - 1]; else oPairHigh[1] = otherHand.hand[POKER_HAND_SIZE - if(pPairHigh[0].compareTo(oPairHigh[0]) == 0){ if(pPairHigh[1].compareTo(oPairHigh[1]) &lt; 0) return -1; else if(pPairHigh[1].compareTo(oPairHigh[1]) &gt; 0) return 1; else return 0; } if(pPairHigh[0].compareTo(oPairHigh[0]) &lt; 0) return -1; else return 1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T12:37:28.240", "Id": "64559", "Score": "0", "body": "I dont wish to post a link as an answer, but look at http://www.suffecool.net/poker/evaluator.html for a fast solution" } ]
[ { "body": "<p>I'm not really any good at algorithms as such so my main suggestion would be to remove duplicate code. That is primarily in the creation of your pPairHigh and oPairHigh blocks of code.</p>\n\n<p>I admit they do share a common loop which in my implementation means this will be occurring twice. If this is an issue in performance it could be broken out so the pairs are created like you have done in a single loop. But I would still call a method to do the actual creation. However I'm working on the assumption performance is not really an issue, here is my suggestions.</p>\n\n<pre><code>// Please not I made a guess around your method name here\nprivate int ComparePairs() {\n PlayingCard[] myHand = getPokerHand(this.hand);\n PlayingCard[] otherPlayersHand = getPokerHand(otherHand);\n\n return compareMyHandAgainstOthers(myHand, otherPlayersHands)\n }\n\n private int compareMyHandAgainstOthers(PlayingCard[] myHand, PlayingCard[] otherHand) { \n if(pPairHigh[0].compareTo(oPairHigh[0]) == 0) {\n if(pPairHigh[1].compareTo(oPairHigh[1]) &lt; 0)\n return -1;\n else if(pPairHigh[1].compareTo(oPairHigh[1]) &gt; 0)\n return 1;\n else\n return 0;\n }\n\n if(pPairHigh[0].compareTo(oPairHigh[0]) &lt; 0)\n return -1;\n else\n return 1;\n } \n\n private PlayingCard[] getPokerHand(Array hand) {\n\n PlayingCard[] pair = new PlayingCard[2];\n for(int i = 0; i &lt; POKER_HAND_SIZE - 1 ; i++) {\n if(this.hand[i].compareTo(this.hand[i+1]) == 0) {\n pair[0] = this.hand[i];\n\n if(i == 3)\n pair[1] = this.hand[i - 1];\n else\n pair[1] = this.hand[POKER_HAND_SIZE - 1];\n\n }\n }\n\n // throw exception here as no possible pair found???\n return pair;\n }\n</code></pre>\n\n<p>Please note there may be java specific code as I haven't programmed in Java for a while.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-27T21:36:19.013", "Id": "12111", "ParentId": "12107", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-27T17:25:57.287", "Id": "12107", "Score": "1", "Tags": [ "java", "algorithm", "playing-cards" ], "Title": "2vs2 Poker Hand One Pair Winner Algorithm" }
12107
<p>I'm teaching myself BigDecimal and would appreciate a critique. In the code fragment below, I calculate a tip from user input: check and tip percentage (entered as integer): </p> <pre><code> txt_check = txtcheck.getText().toString(); tpercent = txttippct.getText().toString(); BigDecimal hundred = new BigDecimal("100"); BigDecimal pct = new BigDecimal(tpercent); BigDecimal bdpercent = pct.divide(hundred, 2,BigDecimal.ROUND_UNNECESSARY); BigDecimal bdcheck = new BigDecimal(txt_check); BigDecimal bdtip = new BigDecimal(txt_check); bdtip = bdtip.multiply(bdpercent); BigDecimal bdtotal = new BigDecimal(txt_check); bdtotal = bdtotal.add(bdtip); </code></pre> <p>The code above appears to function correctly. To display these values I convert to string:</p> <pre><code> scheck = new DecimalFormat("####.00").format(bdcheck.doubleValue()); scheck = StringUtils.leftPad(scheck,7," "); </code></pre> <p>Thanks for any input.</p>
[]
[ { "body": "<p>For such a simple calculation, the logic used for the <code>bdtip</code> and <code>bdtotal</code> variables wasnt straight forward. Instead of creating it with the value of one of the operands, then multiplying/adding it by the other operand, why not do something like the following:</p>\n\n<pre><code>txt_check = txtcheck.getText().toString();\ntpercent = txttippct.getText().toString();\n\nBigDecimal hundred = new BigDecimal(\"100\");\nBigDecimal pct = new BigDecimal(tpercent);\n\nBigDecimal bdpercent = pct.divide(hundred, 2, BigDecimal.ROUND_UNNECESSARY); \nBigDecimal bdcheck = new BigDecimal(txt_check);\n\nBigDecimal bdtip = bdcheck.mulitply(bdpercent);\nBigDecimal bdtotal = bdcheck.add(bdtip);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T06:11:24.277", "Id": "12115", "ParentId": "12108", "Score": "1" } }, { "body": "<ol>\n<li><p>Following naming conventions makes the code easier to read. See <em>Effective Java, 2nd Edition, Item 56: Adhere to generally accepted naming conventions</em></p></li>\n<li><p><code>new BigDecimal(\"100\")</code> could be a constant.</p></li>\n<li><p><a href=\"http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html#format%28java.lang.Object,%20java.lang.StringBuffer,%20java.text.FieldPosition%29\" rel=\"nofollow\"><code>DecimalFormat.format(Object number, StringBuffer toAppendTo, FieldPosition pos)</code></a> accepts <code>BigDecimal</code> objects (without the necessity of converting it to <code>double</code> and loss of precision).</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T09:47:41.980", "Id": "12117", "ParentId": "12108", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-27T17:58:17.583", "Id": "12108", "Score": "3", "Tags": [ "java", "android" ], "Title": "BigDecimal code critique" }
12108
<p>I've written the following <code>explode</code> function using <code>break</code>. The intended behavior is, that a list is divided into sublists by a predicate function, i.e. those elements which match the predicate are the separators - no empty lists should be returned.</p> <p>Here are some examples:</p> <pre><code>explode id [True, True, False] = [[False]] explode id [False, True, False] = [[False], [False]] explode undefined [] = [] explode id [False, False, True, False] = [[False, False], [False]] explode (\x -&gt; mod x 3 == 0) [0..10] = [[1,2],[4,5],[7,8],[10]] </code></pre> <p>The signature of this function is:</p> <pre><code>explode :: (a -&gt; Bool) -&gt; [a] -&gt; [[a]] </code></pre> <p>Here is the implementation:</p> <pre><code>explode _ [] = [] explode f xs | null zs = [z] | null z = explode f (tail zs) | True = z : explode f (tail zs) where (z, zs) = break f xs </code></pre> <p>Is there a better way to do this, a maybe more haskell-idiomatic one? Also, what is the complexity of such a function? I believe the running time is linear, but what about the space complexity?</p>
[]
[ { "body": "<p>grouping list separated by some values intuitively seems like a group by operation. That is, abc,def,ghi => (abc)(def)(ghi)\nSo groupBy seems more intuitive for me, and it results in more concise code.</p>\n\n<pre><code>import Data.List\n\nexplode fn = filter (nfn . head) . gb\n where nfn = not . fn\n gb = groupBy ((. nfn) . (&amp;&amp;) . nfn)\n</code></pre>\n\n<p>If you cann't tolerate pointfree, here is the alternate definition for gb</p>\n\n<pre><code>gb = groupBy (\\x y -&gt; nfn x &amp;&amp; nfn y)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T19:14:46.873", "Id": "19438", "Score": "1", "body": "I can `tolerate` pointfree ;-) - but why should I use this solution at all? I can't see where this code is better to read (= easier to maintain?) or has a better performance (testing shows no difference between my solution and yours). I had a look into the GHC libraries since `explode (== ' ')` should be the same as `words`, which is implemented in a rather “ugly” way - reminding me of my own explode function (also using `break`). So (no offense, I'm curious) why do you guys keep telling me about alternative solutions instead of criticizing my code or explaining in what way these are better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T19:16:40.927", "Id": "19439", "Score": "0", "body": "(reached the maximum length of a comment: here's the link to the words-function in GHC.Base http://www.haskell.org/ghc/docs/latest/html/libraries/base/src/Data-List.html#words )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T21:07:53.693", "Id": "19442", "Score": "0", "body": "Because Nature abhors a naked recursion :) ... Seriously, using the fold,map,filter trinity is one of the hallmarks of good functional code. See [Real World Haksell](http://book.realworldhaskell.org/read/functional-programming.html) the section \"Why use folds maps and filters\". This almost a given in the community that it is forgotten to explain it explicitly. Another tenet is to use the API where possible rather than inventing your own wheel. Here, I believe that your operation is a special groupBy, which is why I gave this solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T21:11:44.873", "Id": "19443", "Score": "1", "body": "A final point in their favor is that these higher order operations restrict the behavior, and provide assurances about their interface. That is, a filter never produces lists whose length is greater than given. A map always returns lists which are equal in magnitude, and fold captures the linear decomposition of the problem. So unless your solution has a good reason to use explicit recursion, you might expect these to be the first suggestions :). OTOH, this seems to be a good question you could ask to S.O" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-27T20:16:33.733", "Id": "12110", "ParentId": "12109", "Score": "1" } }, { "body": "<p>I like blufox' solution, but remember you can replace explicit recursion by a fold, too:</p>\n\n<pre><code>explode f xs = filter (not.null) $ foldr go [[]] xs where \n go x (xs:xss) = if f x then []:xs:xss else (x:xs):xss\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T19:07:51.827", "Id": "19437", "Score": "0", "body": "I don't like this solution due to the use of foldr. Testing with a very large list (like [1..1000000]) results in a stack overflow, whereas my solution does not. Also it is not faster in cases where it successfully computes the result. Of course I like the beauty of the code, but it's simply not more efficient or correct as my own version - so what is the advantage of this version?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T21:23:45.560", "Id": "19444", "Score": "0", "body": "@scravy In his favor, you did ask for a Haskell-idiomatic solution. This solution is one such. See my other explanation for why it is idiomatic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T10:55:30.270", "Id": "19459", "Score": "0", "body": "@scravy If it's not library code or so, readability is usually more important than anything else. I wouldn't care for the 1000000 elememts case until I really encounter such a list and actually *have* a performance problem." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T19:15:51.103", "Id": "12128", "ParentId": "12109", "Score": "3" } } ]
{ "AcceptedAnswerId": "12128", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-27T18:18:57.407", "Id": "12109", "Score": "2", "Tags": [ "haskell" ], "Title": "Haskell function to explode a list" }
12109
<p>Inspired by <a href="https://github.com/themattrix/poker_hand" rel="nofollow">this post</a> (along with a number of other people by the looks of it), I created a poker hand identifier with a very similar format. Note that the syntax of the hands is a little different to make parsing easier - rather than "A:C K:C Q:C J:C 10:C", the input is of the form "[(A,C),(K,C),(Q,C),(J,C),(10,C)]".</p> <p>The code works correctly for the sample inputs in the post, I'm more concerned about coding style and elegance. For example, I've used pointfree style and the <code>Maybe</code> monad (with <code>guard</code> and <code>isJust</code>) where I can so it's not very consistent. <code>getPair</code> doesn't seem very nice but it does save on a reasonable amount of boilerplate; am I right in thinking that returning <code>((Card,Card),Hand)</code> instead of <code>(Card,Card,Hand)</code> would make the pattern matching on it slightly nicer?</p> <p>Example usage:</p> <pre><code>identifyHand "[(5,H),(5,D),(A,S),(10,D),(5,C)]" == "Three of a kind" identifyHand "[(2,H),(3,H),(4,H),(5,H),(A,D)]" == "High card: A" </code></pre> <h1>pokerhands.hs</h1> <pre><code>import Data.List (sort, deleteBy, nub) import Data.Maybe (isJust) import Control.Monad (guard) import Data.Function (on) main :: IO () main = readFile "hands.txt" &gt;&gt;= putStrLn . unlines . map identifyHand . lines ------------------------- -- Types and instances -- ------------------------- type Hand = [Card] type Card = (Value,Suit) -- Num n is valid for 2 &lt;= n &lt;= 10 data Value = Num Int | Jack | Queen | King | Ace deriving (Eq, Ord) -- Clubs | Diamonds | Hearts | Spades data Suit = C | D | H | S deriving (Read, Show, Eq) data Combination = Royal | StraightFlush | Four | FullHouse | Flush | Straight | Three | TwoPair | Pair | High Value instance Show Value where show (Num n) = show n show Jack = "J" show Queen = "Q" show King = "K" show Ace = "A" instance Read Value where -- readsPrec :: Int -&gt; String -&gt; [(Value,String)] -- p.s. I do not really know how readsPrec works readsPrec _ ('J':xs) = [(Jack ,xs)] readsPrec _ ('Q':xs) = [(Queen,xs)] readsPrec _ ('K':xs) = [(King ,xs)] readsPrec _ ('A':xs) = [(Ace ,xs)] readsPrec _ xs = case reads xs of ((n,xs'):_) | n &gt;= 2 &amp;&amp; n &lt;= 10 -&gt; [(Num n,xs')] _ -&gt; [] instance Show Combination where show Royal = "Royal flush" show StraightFlush = "Straight flush" show Four = "Four of a kind" show FullHouse = "Full house" show Flush = "Flush" show Straight = "Straight" show Three = "Three of a kind" show TwoPair = "Two pair" show Pair = "One pair" show (High v) = "High card: " ++ show v ----------------------- -- Identifying hands -- ----------------------- identifyHand :: String -&gt; String identifyHand s = case reads s of ((h,_):_) | nub h /= h -&gt; "ERROR: Duplicate card" | length h &lt; 5 -&gt; "ERROR: Too few cards" | length h &gt; 5 -&gt; "ERROR: Too many cards" | otherwise -&gt; show (getComb h) _ -&gt; "ERROR: parse error" getComb :: Hand -&gt; Combination getComb h | isStraight h &amp;&amp; isFlush h = if isRoyal h then Royal else StraightFlush | isFour h = Four | isFullHouse h = FullHouse | isFlush h = Flush | isStraight h = Straight | isThree h = Three | isTwoPair h = TwoPair | isPair h = Pair | otherwise = High . maximum . map fst $ h isRoyal :: Hand -&gt; Bool -- h must be a straight flush isRoyal h = maximum (map fst h) == Ace isStraight :: Hand -&gt; Bool isStraight = isConsecutive . sort . map fst isFlush :: Hand -&gt; Bool isFlush h = all (x==) xs where (x:xs) = map snd h isFour :: Hand -&gt; Bool isFour h = isJust $ do ((c1,_),(_,_),h') &lt;- getPair h ((c2,_),(_,_),_ ) &lt;- getPair h' guard $ c1 == c2 isFullHouse :: Hand -&gt; Bool isFullHouse h = isJust $ do (_,_,h') &lt;- getPair h guard (isThree h') isThree :: Hand -&gt; Bool isThree h = case getPair h of Just ((c1,_),(c2,_),h') -&gt; any (`elem` [c1,c2]) (map fst h') Nothing -&gt; False isTwoPair :: Hand -&gt; Bool isTwoPair h = isJust $ do (_,_,h') &lt;- getPair h getPair h' isPair :: Hand -&gt; Bool isPair = isJust . getPair ---------------------- -- Helper functions -- ---------------------- getPair :: Hand -&gt; Maybe (Card,Card,Hand) -- if the hand has at least one pair then the two cards -- from the first pair are removed from the hand and then -- that pair and the remaining hand are returned getPair ((c,s):h) = case lookup c h of Just s' -&gt; Just ((c,s),(c,s') ,deleteBy ((==) `on` fst) (c,undefined) h) Nothing -&gt; getPair h getPair [] = Nothing isConsecutive :: [Value] -&gt; Bool isConsecutive (x:x1:xs) = isNext x x1 &amp;&amp; isConsecutive (x1:xs) isConsecutive _ = True isNext :: Value -&gt; Value -&gt; Bool isNext (Num 10) Jack = True isNext (Num n) (Num n') = n' == n+1 isNext Jack Queen = True isNext Queen King = True isNext King Ace = True isNext _ _ = False </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T07:47:04.070", "Id": "22124", "Score": "2", "body": "Don't forget about the \"wheel\" straight - A 2 3 4 5." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-17T22:37:41.947", "Id": "72191", "Score": "0", "body": "@user5402 To some that rule is optional" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-18T02:29:52.540", "Id": "72219", "Score": "0", "body": "***FYI:*** `Royal` is a subtype of `StraightFlush`. A `Royal` represents one of the **4** highest ranked instances of the **36** possible `StraightFlushes`. The arbitrary distinction has always driven me crazy." } ]
[ { "body": "<p>So here is my version of your program. It took some pragmas, but I hope it is alright?</p>\n\n<pre><code>{-# LANGUAGE FlexibleInstances,IncoherentInstances,ScopedTypeVariables #-}\nimport Data.List (sort, deleteBy, nub)\nimport Data.Maybe (isJust)\nimport Control.Monad (guard)\nimport Data.Function (on)\n\nmain :: IO ()\nmain = readFile \"hands.txt\" &gt;&gt;= putStrLn . unlines . map identifyHand . lines\n\n-------------------------\n-- Types and instances --\n-------------------------\n\ntype Hand = [Card]\ntype Card = (Value,Suit)\n\n-- Num n is valid for 2 &lt;= n &lt;= 10\ndata Value = Num Int | Jack | Queen | King | Ace\n deriving (Eq, Ord)\n</code></pre>\n\n<p>I removed the Combination data type because it did not seem to be adding\nany use to the program. Instead I modified the show to be more intelligent.</p>\n\n<p>I also got rid of isNext because it is actually trying to do an Enum poorly. So\ninstead we have an Enum and a Bound (They are not completely necessary, but\ngoing by the spirit of building the language in which to describe the problem\nfirst, I would say they are justified.)</p>\n\n<pre><code>instance Enum Value where\n succ King = Ace\n succ Queen = King\n succ Jack = Queen\n succ (Num 10) = Jack\n succ (Num i) = Num $ succ i\n\n pred Ace = King\n pred Queen = Jack\n pred King = Queen\n pred Jack = (Num 10)\n pred (Num i) = Num (pred i)\n\n fromEnum (Num i) = i\n fromEnum v = succ $ fromEnum (pred v)\n toEnum i | i &lt;= 10 = Num i\n toEnum i = pred $ toEnum (succ i)\n\ninstance Bounded Value where\n minBound = Num 2\n maxBound = Ace\n\ndata Suit = C | D | H | S\n deriving (Read, Show, Eq)\n\ninstance Show Value where\n show (Num n) = show n\n show Jack = \"J\"\n show Queen = \"Q\"\n show King = \"K\"\n show Ace = \"A\"\n\ninstance Read Value where\n readsPrec _ ('J':xs) = [(Jack ,xs)]\n readsPrec _ ('Q':xs) = [(Queen,xs)]\n readsPrec _ ('K':xs) = [(King ,xs)]\n readsPrec _ ('A':xs) = [(Ace ,xs)]\n readsPrec _ xs = case reads xs of\n ((n,xs'):_) | n &gt;= 2 &amp;&amp; n &lt;= 10\n -&gt; [(Num n,xs')]\n _ -&gt; []\n</code></pre>\n\n<p>So, our show changes.</p>\n\n<pre><code>instance Show [Card] where\n show h\n | isStraight h\n &amp;&amp; isFlush h = if isRoyal h then \"Royal\" else \"Straight flush\"\n | isFour h = \"Four of a kind\"\n | isFullHouse h = \"Full house\"\n | isFlush h = \"Flush\"\n | isStraight h = \"Straight\"\n | isThree h = \"Three of a kind\"\n | isTwoPair h = \"Two pair\"\n | isPair h = \"One pair\"\n | otherwise = \"High card: \" ++ show (maximum . map fst $ h)\n\n-----------------------\n-- Identifying hands --\n-----------------------\n\nidentifyHand :: String -&gt; String\nidentifyHand s = case reads s of\n ((h::Hand,_):_) | nub h /= h -&gt; \"ERROR: Duplicate card\"\n | length h &lt; 5 -&gt; \"ERROR: Too few cards\"\n | length h &gt; 5 -&gt; \"ERROR: Too many cards\"\n | otherwise -&gt; show h\n _ -&gt; \"ERROR: parse error\"\n\nisRoyal :: Hand -&gt; Bool\nisRoyal h = maximum (map fst h) == Ace\n\nisStraight :: Hand -&gt; Bool\nisStraight = isConsecutive . sort . map fst\n</code></pre>\n\n<p>When possible, define generic methods, and use them</p>\n\n<pre><code>isFlush :: Hand -&gt; Bool\nisFlush = same . (map snd)\n\nsame :: Eq a =&gt; [a] -&gt; Bool\nsame = (1 ==) . length . nub\n</code></pre>\n\n<p>I found isThree to be rather similar to isFour. So in the interests of\nconsistency they are defined similarly</p>\n\n<pre><code>isFour :: Hand -&gt; Bool\nisFour h = isJust $ do\n ((c1,_),(_,_),h') &lt;- getPair h\n ((c2,_),(_,_),_ ) &lt;- getPair h'\n guard $ c1 == c2\n\nisThree :: Hand -&gt; Bool\nisThree h = isJust $ do\n ((c1,_),x,h') &lt;- getPair h\n ((_,_),(c2,_),_ ) &lt;- getPair (x:h')\n guard $ c1 == c2\n</code></pre>\n\n<p>I like the cleanliness of chaining rather than the do notation, but that is\nsubjective.</p>\n\n<pre><code>isFullHouse :: Hand -&gt; Bool\nisFullHouse h = isJust $ return h &gt;&gt;= getPair &gt;&gt;= (guard . isThree . remHand)\n\nisTwoPair :: Hand -&gt; Bool\nisTwoPair h = isJust $ return h &gt;&gt;= getPair &gt;&gt;= (getPair . remHand)\n\nisPair :: Hand -&gt; Bool\nisPair = isJust . getPair\n\n----------------------\n-- Helper functions --\n----------------------\n</code></pre>\n\n<p>Did a little bit of modifications here too. I feel this is more idiomatic than\nyour version.</p>\n\n<pre><code>-- if the hand has at least one pair then the two cards\n-- from the first pair are removed from the hand and then\n-- that pair and the remaining hand are returned\ngetPair :: Hand -&gt; Maybe (Card,Card,Hand)\ngetPair (x:h) = case h'' of\n [] -&gt; Nothing\n _ -&gt; Just (x, head h'', h' ++ tail h'')\n where (h',h'') = break (\\ x' -&gt; fst x' == fst x) h\n\nremHand :: (Card,Card,Hand) -&gt; Hand\nremHand (_,_,h) = h\n</code></pre>\n\n<p>A side benefit is isConsecutive which is now applicable for any arrays that have\nEnum defined for their elements.</p>\n\n<pre><code>isConsecutive :: (Enum a, Eq a) =&gt; [a] -&gt; Bool\nisConsecutive (x:xs) \n | x == maxBound = False\n | otherwise = succ x == (head xs) &amp;&amp; isConsecutive xs\n\n-- isConsecutive (x:xs) = snd $ foldl (\\(x,b) y -&gt; (y, succ x == y &amp;&amp; b)) (x,True) xs\n</code></pre>\n\n<p>I would encourage you to add a quickcheck to these functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T13:28:29.430", "Id": "19378", "Score": "0", "body": "A note on `isConsecutive`: `succ` is undefined for `maxBound` - your code would throw an error for, say, a pair of aces. I think you need to add an explicit check for `maxBound` there." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T05:49:44.183", "Id": "12114", "ParentId": "12112", "Score": "1" } }, { "body": "<p>Some more ideas - you could have an <code>Enum</code> instance / <code>isNext</code> derived without all the boilerplate if you defined <code>Value</code> either as</p>\n\n<pre><code>{-# LANGUAGE GeneralizedNewtypeDeriving #-}\nnewtype Value = Val Int\n deriving (Eq, Ord, Enum, Bounded)\n</code></pre>\n\n<p>or as</p>\n\n<pre><code>data Value = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten \n | Jack | Queen | King | Ace\n deriving (Eq, Ord, Bounded, Enum)\n</code></pre>\n\n<p>depending on whether that seems like a good idea to you or not. The latter representation is better than it might appear at first - after all, the <code>Enum</code> instance allows you to easily convert to and from numerical values using <code>toEnum</code> / <code>fromEnum</code>, so you don't have to change your <code>Read</code> &amp; <code>Show</code> instances much.</p>\n\n<hr>\n\n<p>Also, I feel like your hand matching could be simplified if you preprocessed the hand a bit:</p>\n\n<pre><code>getComb :: Hand -&gt; Combination\ngetComb h\n ...\n where hg = sortBy (compare `on` length) $\n groupBy ((==) `on` fst) $\n sortBy (compare `on` fst) h\n</code></pre>\n\n<p>This \"grouped\" hand representation has the nice property that you can write hand group checks like follows:</p>\n\n<pre><code>type HandGrouped = [[Card]]\n\nisPair :: HandGrouped -&gt; Maybe HandGrouped\nisPair ([_,_]:xs) = Just xs\nisPair _ = Nothing\n\nisTwoPair :: HandGrouped -&gt; Maybe HandGrouped\nisTwoPair h = isPair h &gt;&gt;= isPair\n</code></pre>\n\n<hr>\n\n<p>Hm, but isn't your implementation actually quite incomplete? Right now, you can't distinguish between ace-high and jack-high straights, for example, or equal pairs with different kickers.</p>\n\n<p>Here's a quick (untested) sketch of how I think you could build the program to have all the mentioned features, using slightly more involved trickery:</p>\n\n<pre><code>-- Low-value combinations first, so it works well with Value\ndata Combination = HighCard | Pair Value | TwoPair Value Value | ...\n deriving Ord\n\n-- Combination, remaining cards / kicker. Implicit Ord instance gives\n-- you card value order!\ntype Evaluation = (Combination, HandGrouped)\n\ngetPair, getTwoPair :: HandGrouped -&gt; Maybe Evaluation\ngetPair ([c,_]:xs) = Just (Pair (fst c), xs)\ngetPair _ = Nothing\ngetTwoPair xs = do\n (Pair v1, xs') &lt;- getPair xs\n (Pair v2, xs'') &lt;- getPair xs'\n return (TwoPair v1 v2, xs'')\n\ngetCombination :: HandGrouped -&gt; Maybe Evaluation\ngetCombination xs = msum\n [ ...\n , getTwoPair xs\n , getPair xs\n , return (HighCard, xs)\n ]\n</code></pre>\n\n<p>Using that <code>msum</code> returns the first value in the list that is not <code>Nothing</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T14:18:16.560", "Id": "12125", "ParentId": "12112", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-27T22:39:22.403", "Id": "12112", "Score": "4", "Tags": [ "haskell", "playing-cards" ], "Title": "Poker hand identifier" }
12112
<p><a href="http://en.wikipedia.org/wiki/Bell_number" rel="nofollow noreferrer">Bell number</a> \$B(n)\$ is defined as the number of ways of splitting \$n\$ into any number of parts, also defined as the sum of previous \$n\$ <a href="http://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind" rel="nofollow noreferrer">Stirling numbers of second kind</a>.</p> <p>Here is a snippet of Python code that Wikipedia provides (slightly modified) to print bell numbers:</p> <pre><code>def bell_numbers(start, stop): t = [[1]] ## Initialize the triangle as a two-dimensional array c = 1 ## Bell numbers count while c &lt;= stop: if c &gt;= start: yield t[-1][0] ## Yield the Bell number of the previous row row = [t[-1][-1]] ## Initialize a new row for b in t[-1]: row.append(row[-1] + b) ## Populate the new row c += 1 ## We have found another Bell number t.append(row) ## Append the row to the triangle for b in bell_numbers(1, 9): print b </code></pre> <p>But I have to print the \$n\$th bell number, so what I did was I changed the second last line of code as follows:</p> <pre><code>for b in bell_numbers(n,n) </code></pre> <p>This does the job, but I was wondering of an even better way to print the \$n\$th bell number.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-17T22:31:12.390", "Id": "276934", "Score": "1", "body": "Please check whether your code is indented correctly." } ]
[ { "body": "<p>You can use the <a href=\"http://mathworld.wolfram.com/DobinskisFormula.html\" rel=\"noreferrer\">Dobinski</a> formula for calculating Bell numbers more efficiently. </p>\n\n<p>Dobinski's formula is basically something like this line, although the actual implementation is a bit more complicated (this function neither returns precise value nor is efficient, see this <a href=\"http://fredrik-j.blogspot.com/2009/03/computing-generalized-bell-numbers.html\" rel=\"noreferrer\">blogpost</a> for more on this):</p>\n\n<pre><code>import math\nITERATIONS = 1000\ndef bell_number(N):\n return (1/math.e) * sum([(k**N)/(math.factorial(k)) for k in range(ITERATIONS)])\n</code></pre>\n\n<p>E.g. you can use the <a href=\"http://code.google.com/p/mpmath/\" rel=\"noreferrer\">mpmath</a> package to calculate the nth Bell number using this formula:</p>\n\n<pre><code>from mpmath import *\nmp.dps = 30\nprint bell(100)\n</code></pre>\n\n<p>You can check the implementation <a href=\"http://code.google.com/p/mpmath/source/browse/trunk/mpmath/functions/functions.py\" rel=\"noreferrer\">here</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T14:54:57.283", "Id": "19381", "Score": "0", "body": "The first method is returning error values as follows, the 5th bell number is actually 52 but this returns 50.767... and same is for other higher bell polynomials as well, I dont understand why this error is showing up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T15:26:48.673", "Id": "19383", "Score": "0", "body": "I know my `bell_number` function doesn't return precise value, it is just meant to display the general idea. The reason for the error is described in the referred [blogpost](http://fredrik-j.blogspot.com/2009/03/computing-generalized-bell-numbers.html), look for [this part](http://upload.wikimedia.org/math/2/f/e/2fe8b4e5768cc4c3b2884cab699317c0.png)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T15:36:42.317", "Id": "19385", "Score": "0", "body": "I see, thanks for this awesome answer, but i cant fully understand what mpmaths is, is it a pyhton library? and how to write the code that uses mpmaths in calculating Bell number,that code returns an error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T15:40:48.890", "Id": "19387", "Score": "0", "body": "mpmath is a Python module (library). You'll need to install that before you can use it. [mpmath install instructions](http://mpmath.googlecode.com/svn/trunk/doc/build/setup.html)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T13:00:10.667", "Id": "12121", "ParentId": "12119", "Score": "6" } }, { "body": "<p>Change <code>yield t[-1][0]</code> to <code>yield t[-1][-1]</code> so the \\$n\\$th Bell number is on the \\$n\\$th line - that is, gives correct output, so the call:</p>\n\n<pre><code>for b in bell_numbers(1, 9):\n print b\n</code></pre>\n\n<p>prints the correct bell numbers 1 to 9.</p>\n\n<p>So, if you just want the \\$n\\$th Bell number only:</p>\n\n<pre><code>for b in bell_numbers(n, n):\n print b\n</code></pre>\n\n<p>or change the code to take just one argument.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-17T22:04:05.563", "Id": "147349", "ParentId": "12119", "Score": "1" } } ]
{ "AcceptedAnswerId": "12121", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T10:21:14.857", "Id": "12119", "Score": "2", "Tags": [ "python", "combinatorics" ], "Title": "Printing nth bell number" }
12119
<p>I have to interface to some old code using nested arrays, so I have to convert my nested Lists to nested arrays. Any idea, suggestions, improvements are warmly welcomed.</p> <pre><code>public static &lt;E&gt; int getNestedListMaxSize(List&lt;List&lt;E&gt;&gt; list){ int result = 0; if (list != null &amp;&amp; list.size() &gt; 0){ for (List&lt;E&gt; innerList : list){ result = Math.max(result, innerList == null ? 0 : innerList.size()); } } return result; } @SuppressWarnings("rawtypes") public static &lt;E&gt; Class getNestedListClass(List&lt;List&lt;E&gt;&gt; list){ Class result = null; if (list != null &amp;&amp; list.size() &gt; 0){ for (List&lt;E&gt; innerList : list){ if (innerList != null &amp;&amp; innerList.size() &gt; 0){ result = innerList.get(0).getClass(); break; } } } return result; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static &lt;E&gt; E[][] convertNestedList(List&lt;List&lt;E&gt;&gt; list){ E[][] result = null; Class clazz = getNestedListClass(list); if (clazz != null){ result = (E[][]) Array.newInstance(clazz, list.size(), getNestedListMaxSize(list)); for(int i=0; i &lt; list.size(); i++) { E[] element = null; if (list.get(i) != null){ E[] dummy = (E[]) Array.newInstance(clazz, list.get(i).size()); element = list.get(i).toArray(dummy); } result[i] = element; } } return result; } public static void main(String[] args) { List&lt;List&lt;String&gt;&gt; list = new ArrayList&lt;List&lt;String&gt;&gt;(); list.add(new ArrayList&lt;String&gt;()); list.get(list.size()-1).add("0.0"); list.get(list.size()-1).add("0.1"); list.get(list.size()-1).add("0.2"); list.add(new ArrayList&lt;String&gt;()); list.get(list.size()-1).add("1.0"); list.get(list.size()-1).add("1.1"); list.get(list.size()-1).add("1.2"); list.get(list.size()-1).add("1.3"); list.add(new ArrayList&lt;String&gt;()); list.get(list.size()-1).add("2.0"); list.get(list.size()-1).add("2.1"); String [][] array = convertNestedList(list); System.out.println(Arrays.deepToString(array)); } </code></pre>
[]
[ { "body": "<p>I'd use <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">guard clauses</a> to check whether the list parameter is <code>null</code> or not. Furthermore, the <code>list.size() &gt; 0</code> check looks unnecessary in the first two methods, the result will be same if you omit it.</p>\n\n<p>Anyway, are you sure that <code>null</code> is an acceptable parameter here? Wouldn't it better to throw an exception in this case?</p>\n\n<pre><code>public static &lt;E&gt; int getNestedListMaxSize(final List&lt;List&lt;E&gt;&gt; list) {\n if (list == null) {\n return 0;\n }\n int result = 0;\n for (final List&lt;E&gt; innerList: list) {\n if (innerList == null) {\n continue;\n }\n result = Math.max(result, innerList.size());\n }\n return result;\n}\n</code></pre>\n\n<p>In the <code>getNestedListClass</code> I'd use guard clauses too and a <code>return</code> instead of the <code>break</code>.</p>\n\n<pre><code>@SuppressWarnings(\"rawtypes\")\npublic static &lt;E&gt; Class getNestedListClass(final List&lt;List&lt;E&gt;&gt; list) {\n if (list == null) {\n return null;\n }\n\n for (final List&lt;E&gt; innerList: list) {\n if (innerList == null || innerList.isEmpty()) {\n continue;\n }\n return innerList.get(0).getClass();\n }\n return null;\n}\n</code></pre>\n\n<p>I think the <code>return</code> makes the code much easier to read and follow.</p>\n\n<p>In the <code>convertNestedList</code> method </p>\n\n<ol>\n<li><p>the <code>dummy</code> variable should have a meaningful name, for example <code>innerListArray</code>,</p></li>\n<li><p>the default value of <code>result[i]</code> is <code>null</code>, so you don't have to set it to <code>null</code> explicitly if the inner list is <code>null</code>,</p></li>\n<li><p><code>list.get(i)</code> is called three times. It could have a local variable.</p></li>\n</ol>\n\n\n\n<pre><code>public static &lt;E&gt; E[][] convertNestedList(final List&lt;List&lt;E&gt;&gt; list) {\n final Class&lt;?&gt; clazz = getNestedListClass(list);\n if (clazz == null) {\n return null;\n }\n final E[][] result = (E[][]) Array.newInstance(clazz, list.size(), \n getNestedListMaxSize(list));\n\n for (int i = 0; i &lt; list.size(); i++) {\n final List&lt;E&gt; innerList = list.get(i);\n if (innerList == null) {\n continue;\n }\n final E[] innerListArray = (E[]) Array.newInstance(clazz, innerList.size());\n result[i] = innerList.toArray(innerListArray);\n }\n return result;\n}\n</code></pre>\n\n<p>The main method should be a unit test method with proper assert calls:</p>\n\n<pre><code>@Test\npublic void testConvertNestedList() {\n final List&lt;List&lt;String&gt;&gt; list = new ArrayList&lt;List&lt;String&gt;&gt;();\n list.add(new ArrayList&lt;String&gt;());\n list.get(list.size() - 1).add(\"0.0\");\n list.get(list.size() - 1).add(\"0.1\");\n list.get(list.size() - 1).add(\"0.2\");\n list.add(new ArrayList&lt;String&gt;());\n list.get(list.size() - 1).add(\"1.0\");\n list.get(list.size() - 1).add(\"1.1\");\n list.get(list.size() - 1).add(\"1.2\");\n list.get(list.size() - 1).add(\"1.3\");\n list.add(new ArrayList&lt;String&gt;());\n list.get(list.size() - 1).add(\"2.0\");\n list.get(list.size() - 1).add(\"2.1\");\n\n final String[][] array = ListConvert.convertNestedList(list);\n\n // @formatter:off\n final String[][] expected = new String[][] { \n { \"0.0\", \"0.1\", \"0.2\" }, \n { \"1.0\", \"1.1\", \"1.2\", \"1.3\" },\n { \"2.0\", \"2.1\" } };\n // @formatter:on\n assertArrayEquals(expected, array);\n}\n</code></pre>\n\n<p>It helps detecting regressions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T15:07:15.673", "Id": "19382", "Score": "1", "body": "I was worried I made some conceptual error, like there was a much simpler way to achieve my goal. Nevertheless, these are all valid and good remarks, so thanks @palacsint." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T15:28:10.243", "Id": "19384", "Score": "0", "body": "An idea: have you searched for already existed libraries which does this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T15:37:01.313", "Id": "19386", "Score": "1", "body": "Well, I searched on Google/StackOverflow and nothing surfaced. I also thought to myself that such feature should be already implemented in some existing library. I have checked Apache Commons and Guava but I did not find it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T13:33:40.677", "Id": "12122", "ParentId": "12120", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T10:38:51.187", "Id": "12120", "Score": "1", "Tags": [ "java", "array", "generics" ], "Title": "Java generics, convert nested list to array" }
12120
<p>Im working on a small desktop app which controls services on a server. For controlling services i am using ServiceController class. What i want to do is; testing my code and abstract the ServiceController class from my code. So i did something like below.</p> <pre><code> public interface IServiceControllerWrapper { string ServerNameOrIP { get; } int Status { get; } bool CanStop { get; } void StartService(); } public class ServiceControllerWrapper : IServiceControllerWrapper { ServiceController _controller; const string ServiceName = "W3SVC"; public ServiceControllerWrapper(string serverNameOrIP) { _controller = new ServiceController(ServiceName, serverNameOrIP); } public string ServerNameOrIP { get { return _controller.MachineName; } } public int Status { get { switch (_controller.Status) { case ServiceControllerStatus.ContinuePending: case ServiceControllerStatus.PausePending: case ServiceControllerStatus.Paused: return 4; case ServiceControllerStatus.StopPending: case ServiceControllerStatus.Stopped: return 0; case ServiceControllerStatus.StartPending: case ServiceControllerStatus.Running: return 1; default: return -1; } } } public bool CanStop { get { return _controller.CanStop; } } public void StartService() { _controller.Start(); } //shortened } </code></pre> <p>and i am using this class within another named ServerContext. Implementation is;</p> <pre><code> public interface IServerContext { string ServerName { get; } IServerContext Parent { get; } IServiceControllerWrapper Controller { get; } bool HasError { get; set; } int GetServiceStatus(); } public class ServerContext : IServerContext { IServerContext _parent; IServiceControllerWrapper _controller; public ServerContext(IServerContext parent, IServiceControllerWrapper wrapper) { _parent = parent; _controller = wrapper; } public string ServerName { get { return _controller.ServerNameOrIP; }} public IServerContext Parent { get { return _parent; } } public IServiceControllerWrapper Controller { get { return _controller; } } public bool HasError { get; set; } public int GetServiceStatus() { return _controller.Status; } } </code></pre> <p>My question here is, i am tryint to test ServerContext and ServiceControllerWrapper but i cant manage to create fake objects. this test method always throws exception because ServerName is null.How can i arrange this code to pass test and or how can i test those classes?</p> <pre><code> [Fact] public void ServerName_CannotBeEmpty() { Mock&lt;IServiceControllerWrapper&gt; _controller = new Mock&lt;IServiceControllerWrapper&gt;(); ServerContext serverContext = new ServerContext(null, _controller.Object); //this code fails. serverContext.ServerName.Should().Not.Be.NullOrEmpty(); } </code></pre> <p>Any suggestions are welcome. Note: i am using moq,xunit and SharpTestsEx libraries for testing.</p>
[]
[ { "body": "<p>If your mocking framework is similar to the one I use, you probably need to stub ServerNameOrIP on your injected IServiceControllerWrapper mock. It is not uncommon for mocked objects to return default(T) for anything not yet stubbed.</p>\n\n<p>As an aside, I would suggest modifying your IServiceControllerWrapper to eliminate your Controller property. The purpose of the wrapper is only to expose those methods/properties that your code requires from ServiceController while hiding the fact that you are using a ServiceController object to execute them. If someone else were to code against your wrapper and use this property, they have effectively re-coupled the code to ServiceController.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T08:02:35.450", "Id": "19449", "Score": "0", "body": "thanks for your suggestions. I edited the code and the test methos to reflect my question clearly. I think i dont know how to stub ServerNameOrIP. Maybe i didnt understand testing frameworks clearly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T18:23:00.327", "Id": "12149", "ParentId": "12126", "Score": "0" } }, { "body": "<p>You'll have to do something like (this will work for Moq, change the api usage to match your Mocking framework). </p>\n\n<pre><code>_controller.Setup(p=&gt;p.ServerNameOrIP).Returns(\"testServerName\");\n</code></pre>\n\n<p>before you call your assert statement. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T12:40:29.437", "Id": "19461", "Score": "0", "body": "oppps you are right.It seems that i need to learn mocking framework first and than testing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T08:41:25.543", "Id": "12159", "ParentId": "12126", "Score": "1" } } ]
{ "AcceptedAnswerId": "12159", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T15:25:44.470", "Id": "12126", "Score": "1", "Tags": [ "c#", "unit-testing" ], "Title": "Testing ServiceController Class" }
12126
<p>I want to create lists of the nodes of a binary tree at each depth.<br> So if the depth is X I would have X lists.<br> Please see my approach. I think it is correct. Am I right to believe it is correct? Any input is welcome: </p> <pre><code>public List&lt;List&lt;BinaryNode&gt;&gt; getNodesPerDepth(BinaryNode root){ if(root == null) { throw new IllegalArgumentException(); } List&lt;LinkedList&lt;BinaryNode&gt;&gt; result = new LinkedList&lt;LinkedList&lt;BinaryNode&gt;&gt;(); result.add(new LinkedList&lt;BinaryNode&gt;()); getNodesPerDepth(result, root, 0); return result; } private void getNodesPerDepth(List&lt;LinkedList&lt;BinaryNode&gt;&gt; lists, BinaryNode root , int depth){ if(root == null){ return; } lists.get(depth).add(root); if(lists.size() &lt; depth + 1 &amp;&amp; (root.left != null || root.right != null)){ lists.add(new LinkedList&lt;BinaryNode&gt;()); } getNodesPerDepth(lists, root.left, depth + 1); getNodesPerDepth(lists, root.right, depth + 1); } </code></pre>
[]
[ { "body": "<p>Do you really want to go recursive on this? Binary trees in the worst case may be a linear list. A better idea is to do some thing like this:</p>\n\n<pre><code>getNodesPerDepth(rootNode) {\n list.add(rootNode); // Start with the root node,\n dlst = new List() // depth lit\n while(list.size() != 0) {\n nextlst = new List(); // make a list of children to iterate next phase.\n for(e : list) {\n for (c : e.children())\n nextlst.add(c);\n }\n dlst.add(list);\n list = nextlst;\n }\n return dlst;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T05:36:34.127", "Id": "12132", "ParentId": "12127", "Score": "2" } } ]
{ "AcceptedAnswerId": "12132", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T17:28:30.900", "Id": "12127", "Score": "3", "Tags": [ "java", "algorithm" ], "Title": "List creation of BST's nodes" }
12127
<p>This is for a plugin I am making for the game called Minecraft. The code is responsible for finding out the blocks placed by the player and if they are in the following sequence as shown in the picture then create an <code>Antenna</code>. <code>block</code> in <code>block.getType()</code> returns the block placed by the player. Also, it doesn't matter in what order the player places the blocks.</p> <p><img src="https://i.stack.imgur.com/nL0vD.png" alt="enter image description here"></p> <pre><code>// if block placed was a jukebox and block directly above is a diamond block // and the block above the diamond block is an iron fence if(block.getType() == Material.JUKEBOX &amp;&amp; block.getRelative(BlockFace.UP, 1).getType() == Material.DIAMOND_BLOCK &amp;&amp; block.getRelative(BlockFace.UP, 2).getType() == Material.IRON_FENCE){ System.out.println("Antenna Created"); player.sendMessage("Antenna Created"); } // if block placed was a diamond block and block directly above is a iron fence // and the block below is a jukebox if(block.getType() == Material.DIAMOND_BLOCK &amp;&amp; block.getRelative(BlockFace.UP, 1).getType() == Material.IRON_FENCE &amp;&amp; block.getRelative(BlockFace.DOWN, 1).getType() == Material.JUKEBOX){ System.out.println("Antenna Created"); player.sendMessage("Antenna Created"); } // if block placed was an iron fence and the block directly below is a diamond block // and the block below that is a jukebox if(block.getType() == Material.IRON_FENCE &amp;&amp; block.getRelative(BlockFace.DOWN, 1).getType() == Material.DIAMOND_BLOCK &amp;&amp; block.getRelative(BlockFace.DOWN, 2).getType() == Material.JUKEBOX){ System.out.println("Antenna Created"); player.sendMessage("Antenna Created"); } </code></pre> <p>I am not happy with the following code and I get the feeling there is a better way to do this? I'm also wondering how would I go about designing these <code>if</code> Statements to allow for future extendibility?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T02:22:29.567", "Id": "19399", "Score": "0", "body": "Aren't you creating three antennas there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T02:38:21.833", "Id": "19400", "Score": "0", "body": "@kaoD no the three \"Antenna Created\" messages is duplicate code which I want to get rid of with a better design." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T02:43:45.227", "Id": "19401", "Score": "0", "body": "You just need ONE of those ifs, so actually the way to get rid of duplicated code is removing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T02:50:29.107", "Id": "19402", "Score": "0", "body": "@kaoD It's a requirement to allow the antenna to be repaired, so say the middle block (diamond block) is destroyed replacing that block should re-create the antenna. The three if statements is to allow the player to build from any point and still create an antenna as long as the blocks are in that sequence. Also I plan on making the antenna longer so I'd like to know how to go about coding something that's scalable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T17:56:23.743", "Id": "19425", "Score": "0", "body": "I have a feeling that you want to build some sort of shape map setup, with the ability to navigate from any placed block. When a block is placed, it looks up all 'shapes' that contain that block, then uses them as the 'root' to search from. You should then need to only store one 'map' of the completed object (although you'll probably want indexing for root search). Ideally, you could do something with repeating patterns or ranges, and _possibly_ proportions (difficult). Since this should be query-only, it's also decently parallelizable." } ]
[ { "body": "<p>As it is mentioned in the comments, It seems your code is exactly same as the below. So that is the first suggestion. </p>\n\n<pre><code>main = block.getType();\nup1 = block.getRelative(BlockFace.UP, 1).getType();\nup2 = block.getRelative(BlockFace.UP, 2).getType();\ndown1 = block.getRelative(BlockFace.DOWN, 1).getType();\ndown2 = block.getRelative(BlockFace.DOWN, 2).getType();\n\n\nif ((main == Material.JUKEBOX &amp;&amp; up1 == Material.DIAMOND_BLOCK &amp;&amp; up2 == Material.IRON_FENCE)||\n (main == Material.DIAMOND_BLOCK &amp;&amp; up1 == Material.IRON_FENCE &amp;&amp; down1 == Material.JUKEBOX) ||\n (main == Material.IRON_FENCE &amp;&amp; down1 == Material.DIAMOND_BLOCK &amp;&amp; down2 == Material.JUKEBOX)) {\n System.out.println(\"Antenna Created\");\n player.sendMessage(\"Antenna Created\");\n}\n</code></pre>\n\n<p>Now, as far as extendibility goes, You need to add newer conditions, it is not a good idea. What you have coded here is just an FSM (A state machine).</p>\n\n<p>The easiest method to capture a state machine is to turn that into a regular expression. In this case, Say, the ordering is</p>\n\n<pre><code>up1 up2 main down1 down2\n</code></pre>\n\n<p>The conditions are</p>\n\n<pre><code>DIJ.. | I.DJ. | ..IDJ\n</code></pre>\n\n<p>So this captures your state machine fully. Adding future conditions is just as simple as adding to the above regular expression.</p>\n\n<p>The code would look like</p>\n\n<pre><code>first(var) {\n return first_char(var)\n}\nstring = { first(up1.toS()), first(up2.toS()),\n first(main.toS()),\n first(down1.toS()), first(down2.toS())};\nre = new Regexp('DIJ..|I.DJ.|..IDJ')\nif (re.match(string)) {\n player.send('Antena Created');\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T13:03:47.410", "Id": "19409", "Score": "0", "body": "Hi thanks for your answer it's been very helpful. I also have been playing around trying to figure out a way (see my answer below). I got something working but I am wondering which of our solutions would be better to implement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T00:47:40.780", "Id": "23750", "Score": "0", "body": "This FSM concept looks very intriguing. Looks very similar to something else that is implemented in the ModLoader library for this game. Definitely a +1. Now to figure out this awesome new toy. Shame its REGEX though :(" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T04:17:27.080", "Id": "12130", "ParentId": "12129", "Score": "3" } } ]
{ "AcceptedAnswerId": "12130", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T00:09:33.247", "Id": "12129", "Score": "2", "Tags": [ "java", "optimization", "minecraft" ], "Title": "Plugin for finding placed blocks and if they are in a certain sequence" }
12129
<p>I'm switching to Ruby from Java and so, for exercise purposes, I wrote this verbose leap year Ruby program. The comments express my concerns about Ruby best practices. I'd be glad if some Ruby experienced programmer could dispel my doubts. Every hint such as <em>"in Ruby you can achieve this thing better this way"</em> is truly welcomed.</p> <p>First of all, this is a possible execution:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Pick a starting year: 2000 Now pick an ending year: 2024 From year 2000 to year 2024 there are 7 leap years. Specifically: The year 2000 was a leap year, The year 2004 was a leap year, The year 2008 was a leap year, The year 2012 is a leap year, The year 2016 will be a leap year, The year 2020 will be a leap year, The year 2024 will be a leap year. </code></pre> </blockquote> <p>Please note the verb conjugation and that <strong>every line has a comma at the end, except the last one that has a period</strong>.</p> <pre class="lang-ruby prettyprint-override"><code># I just felt bad about calling Time.now.year every time just to know the present year, # is this simple memoization a good solution? def was_is_or_will_be(year) @present ||= Time.now.year return 'is' if year == @present return 'was' if year &lt; @present return 'will be' if year &gt; @present end # first of all, let's ask for the years interval puts 'Pick a starting year:' starting = gets.chomp.to_i puts 'Now pick an ending year:' # Is this the best "repeat..until" pattern for ruby? # Because it doesn't seems very clear to me. # There is no way to write somethin more explicit like a "do..while"? while true ending = gets.chomp.to_i if ending &gt; starting break end puts "The ending year must be greater than the starting year,\n please pick a valid ending year:" end # This piece of code seems 'ruby-way' to me... isn't it? leap_years = [] (starting..ending).each do |year| if year%4 == 0 &amp;&amp; (year%100 != 0 || year%400 == 0) leap_years &lt;&lt; year end end # This is the best way I found to handle this simple pluralization puts "From year #{starting} to year #{ending} there #{leap_years.count == 1 ? 'is' : 'are'} " + "#{leap_years.count} leap #{leap_years.count == 1 ? 'year' : 'years'}." # If there are some leap_years in the interval I want a verbose list of them if leap_years.count &gt; 0 puts "Specifically:" # Is there a way to achieve the same function (a comma at the end of every line but a period at the end of the last one) # Without an 'i' counter? With such as a Java 'hasNext()' equivalent? i = 1; leap_years.each do |leap_year| puts "The year #{leap_year} #{was_is_or_will_be(leap_year)} a leap year#{ i &lt; leap_years.count ? ',' : '.'}" i += 1 end end </code></pre>
[]
[ { "body": "<p>Nice effort, :) here are a few comments.</p>\n\n<p>unless you are calling this as part of another class, \ndo not use @member syntax. What you really want is a global.</p>\n\n<pre><code>$present = Time.now.year \n</code></pre>\n\n<p>Shorter name :), plus it is better to capture it in case statement rather\nthan abuse return :).</p>\n\n<pre><code>def tense(year)\n return case \n when year &lt; $present ; 'was'\n when year &gt; $present ; 'will be'\n else 'is'\n end\nend\n\ndef get_years()\n # first of all, let's ask for the years interval\n puts 'Pick a starting year:'\n starting = gets.chomp.to_i \n puts 'Now pick an ending year:'\n</code></pre>\n\n<p>Now, what you asked for is possible, for example,</p>\n\n<pre><code> #begin\n # ending = gets.chomp.to_i \n #end while ending &lt;= starting\n</code></pre>\n\n<p>However, I dont recommend it.</p>\n\n<pre><code> while true\n ending = gets.chomp.to_i \n break if ending &gt; starting\n</code></pre>\n\n<p>Use heredocs if you have more than one line to output.</p>\n\n<pre><code> puts &lt;&lt;-EOF\nThe ending year must be greater than the starting year,\nplease pick a valid ending year:\n EOF\n end\n return [starting,ending]\nend\n</code></pre>\n\n<p>Modularize a little bit. get_years is obviously a specific functionality.</p>\n\n<pre><code>starting,ending = get_years()\n</code></pre>\n\n<p>It is rubyish (and smalltalkish) to use select, inject, collect etc rather than\nexplicit loops where possible.</p>\n\n<pre><code>leap_years = (starting..ending).select do |year|\n year%4 == 0 &amp;&amp; (year%100 != 0 || year%400 == 0)\nend\n</code></pre>\n\n<p>Smaller width lines if you can :). It helps, and it looks good.\nAlso make use of case in these cases.</p>\n\n<pre><code>puts \"From year #{starting} to year #{ending} there \" + case leap_years.count\n when 0 ; \"are no leap years.\"\n when 1 ; \"is 1 leap year.\"\n else \"are #{leap_years.count} leap years.\"\n end\n</code></pre>\n\n<p>Choose to exit early rather than another indentation level</p>\n\n<pre><code>exit 0 unless leap_years.count &gt; 0\n\nputs \"Specifically:\" \nputs leap_years.map{|leap_year|\n \"The year #{leap_year} #{tense(leap_year)} a leap year\"\n}.join(\",\\n\") + \".\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T09:37:54.317", "Id": "19457", "Score": "0", "body": "Just two observations: **1]** your inline syntax for the switch case construct doesn't work (am I missing something?) so I changed it for the ordinary multiline one. **2]** the last line returns an error because the interpreter tries to add \".\" to the result of puts (nil) so I changed the last 3 lines adding a 'report' variable this way: \"report = leap_years.map ....\" and then \"puts report\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T14:16:48.833", "Id": "19464", "Score": "0", "body": "I have updated the last line. (My fault, I changed it without testing.). What is the error that you get while using inline case? See this example in [wiki](http://en.wikipedia.org/wiki/Switch_statement#Ruby) for a simple use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T14:21:01.293", "Id": "19465", "Score": "1", "body": "Uhh, if you are using ruby 1.9, please use ';' instead of ':' as case separator. (See updated.) You could also use when ... then ... construct instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T09:00:42.440", "Id": "19519", "Score": "0", "body": "And it is also possible to omit the 'return' in your 'tense(year)' method :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T09:11:36.527", "Id": "19521", "Score": "0", "body": "Thank you, now it all works fine. I'm going with the 'when..then' construct that allowed me to write self-commenting code like 'when 0 then \"there are no leap years\"'. I think I'll never look back to Java... And so 'do..end' and '{}' to define blocks aren't equivalent in terms of execution flow... interesting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T13:53:32.783", "Id": "19530", "Score": "0", "body": "@DuccioArmenise Yes, if return statement is omitted, the last expression becomes the return value :). Wrt do...end and {} they are equivalent in terms of control flow but one binds tighter (has higher precedence) than the other. You could also have used puts (begin ... end.join + _)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T17:24:03.427", "Id": "12147", "ParentId": "12136", "Score": "4" } }, { "body": "<p>Don't code like below:</p>\n\n<pre><code>while true\n ending = gets.chomp.to_i \n if ending &gt; starting\n break\n end\n puts \"The ending year must be greater than the starting year,\\n please pick a valid ending year:\"\nend \n</code></pre>\n\n<p>instead, you should use:</p>\n\n<pre><code>loop do \n &lt;code goes here&gt;\n break if &lt;condition&gt;\nend \n</code></pre>\n\n<p>see: <a href=\"https://stackoverflow.com/questions/190590/ruby-builtin-do-while\">https://stackoverflow.com/questions/190590/ruby-builtin-do-while</a> and \n<a href=\"http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745\" rel=\"nofollow noreferrer\">http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T08:22:03.710", "Id": "19451", "Score": "0", "body": "Thank you very much for this hint about the \"loop\" construct. I didn't know it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T09:36:36.583", "Id": "19455", "Score": "0", "body": "Uhm, I tried with 'loop do...end' but inside the 'do..end' (the block) the variables are local! So replacing a 'while true' with a 'loop do' doesn't seem to be always proper or convenient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T09:56:28.167", "Id": "19458", "Score": "0", "body": "I just looked it up in my pickaxe book. It is presented as the \"Last, and probably least...\". Anyway, is good to know about it. One interesting thing to know about Ruby blocks (and that I just learned) is that their inner variables are local by default but if a variable already exists with the same name before the block, then inside the block that variable is local no more! So it's possible tu use loop..do construct in this context provided that the \"ending\" variable must be defined before it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T11:10:29.563", "Id": "19460", "Score": "1", "body": "I think the problem you mentioned is \"[shadow variables ( or Variable Shadowing)](http://en.wikipedia.org/wiki/Variable_shadowing) \", unfortunately, Ruby 1.8 has the bug. you can avoid this by using Ruby1.9. For more details, please refer to <<Metaprogramming Ruby>>, really great book along side with the pickaxe book." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T01:17:18.157", "Id": "12153", "ParentId": "12136", "Score": "1" } } ]
{ "AcceptedAnswerId": "12147", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T10:47:36.780", "Id": "12136", "Score": "3", "Tags": [ "ruby", "datetime", "iterator" ], "Title": "Leap year program" }
12136
<p>I needed to build a slider, and this is my first attempt. I'm trying to make it as dynamic as possible. My code works, but I'm wondering if there is a better way and if anyone has any suggestions. I'll be making the width calculated as well. I just have it hardcoded for testing.</p> <p>Also, I need to make pagination for this. I'm not sure where to start with the way I have things set up. Any hints as to where to start would be much appreciated.</p> <p>Here is the link to the working slider: <a href="http://wss.manage-website.com/stg/4406" rel="nofollow">http://wss.manage-website.com/stg/4406</a></p> <p>Javascript:</p> <pre><code>jQuery.noConflict(); jQuery(document).ready(function ($) { function doAnimation() { count = $('.slider img').length; $('.slider img').each(function(index) { // calculate and asign z-index to the images. First image in the stack recieves highest. var zindex = count - index; $(this).css('z-index', zindex); $(this).delay(3000*index).animate({ left: '495px' }, 500, function() { $('.slider img').each(function(index) { // convert z-index to an integer var zindex = parseInt($(this).css('z-index')); // calculate z-index of images to retain order in the stack. Send this one to the back, push the rest up one. if (zindex &lt; count) { $(this).css('z-index', zindex + 1); } else { $(this).css('z-index', zindex - (count-1)); } }); $(this).animate({ left: '0' }, 500, function() { // if we're at the end, repeat. if (index == count - 1) { setTimeout(doAnimation,1500); } }); }); }); } doAnimation(); }); </code></pre>
[]
[ { "body": "<p>Some minor improvements you can make:</p>\n\n<ol>\n<li><p>Cache your DOM lookups (e.g. <code>$('.slider img')</code>) to prevent having to parse the DOM multiple times. That's as simple as making a new variable:</p>\n\n<pre><code>var sliderImages = $('.slider img');\n</code></pre></li>\n<li><p>Use a ternary statement for setting your z-index:</p>\n\n<pre><code>$(this).css('z-index', zindex &lt; count ? zindex + 1 : zindex - count - 1);\n</code></pre>\n\n<p>That'll remove 4 lines and remove unnecessary repetition.</p></li>\n<li><p>Add the <code>var</code> keyword to your <code>count</code> variable so it's not global (it should remain accessible to all the functions within your function scope anyway).</p></li>\n<li><p>Add some simple comments to explain why you're changing the <code>z-index</code> in the first place.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T02:36:29.007", "Id": "19410", "Score": "0", "body": "Thanks for the tips! I've implemented them. Sorry about the no comments. The system at work strips comments from the code, so I'm very used to not putting them in! I've edited the code to include comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T05:22:29.923", "Id": "19411", "Score": "0", "body": "OK, so now from your comments I finally understand what you're doing! You're not building a [slider](http://en.wikipedia.org/wiki/Slider_(computing)) like I assumed, so much as as an image slider/carousel." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T13:02:26.317", "Id": "19412", "Score": "0", "body": "Right. Sorry for the confusion. Wasn't sure what to call it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T02:03:03.453", "Id": "12140", "ParentId": "12139", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T01:45:39.087", "Id": "12139", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Refactoring jQuery slider code suggestions" }
12139
<p>I have 30 icons, and after hover, different icons are shown. How can I write this shorter?</p> <p><strong>jQuery</strong></p> <pre><code>$('#iconTech01').hover( function() { $('#iconTechBig01').stop(true, true).fadeIn("slow"); $('#iconTech01 img').stop(true, true).fadeOut("slow"); }, function() { $('#iconTechBig01').stop(true, true).fadeOut("slow"); $('#iconTech01 img').stop(true, true).fadeIn("slow"); }); $('#iconTech02').hover( function() { $('#iconTechBig02').stop(true, true).fadeIn("slow"); $('#iconTech02 img').stop(true, true).fadeOut("slow"); }, function() { $('#iconTechBig02').stop(true, true).fadeOut("slow"); $('#iconTech02 img').stop(true, true).fadeIn("slow"); }); $('#iconTech03').hover( function() { $('#iconTechBig03').stop(true, true).fadeIn("slow"); $('#iconTech03 img').stop(true, true).fadeOut("slow"); }, function() { $('#iconTechBig03').stop(true, true).fadeOut("slow"); $('#iconTech03 img').stop(true, true).fadeIn("slow"); }); $('#iconTech04').hover( function() { $('#iconTechBig04').stop(true, true).fadeIn("slow"); $('#iconTech04 img').stop(true, true).fadeOut("slow"); }, function() { $('#iconTechBig04').stop(true, true).fadeOut("slow"); $('#iconTech04 img').stop(true, true).fadeIn("slow"); }); $('#iconTech05').hover( function() { $('#iconTechBig05').stop(true, true).fadeIn("slow"); $('#iconTech05 img').stop(true, true).fadeOut("slow"); }, function() { $('#iconTechBig05').stop(true, true).fadeOut("slow"); $('#iconTech05 img').stop(true, true).fadeIn("slow"); }); </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div id="iconWraper"&gt; &lt;div id="iconTech01" class="icon"&gt;&lt;img src="img/icons/tech/tech01.png" alt="icon 01" /&gt;&lt;/div&gt; &lt;div id="iconTech02" class="icon"&gt;&lt;img src="img/icons/tech/tech02.png" alt="icon 02" /&gt;&lt;/div&gt; &lt;div id="iconTech03" class="icon"&gt;&lt;img src="img/icons/tech/tech03.png" alt="icon 03" /&gt;&lt;/div&gt; &lt;div id="iconTech04" class="icon"&gt;&lt;img src="img/icons/tech/tech04.png" alt="icon 04" /&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id="iconTechBig01" class="iconBig"&gt;&lt;img src="img/icons/tech/tech01Big.png" alt="ikona 01" /&gt;&lt;/div&gt; &lt;div id="iconTechBig02" class="iconBig"&gt;&lt;img src="img/icons/tech/tech02Big.png" alt="ikona 02" /&gt;&lt;/div&gt; &lt;div id="iconTechBig03" class="iconBig"&gt;&lt;img src="img/icons/tech/tech03Big.png" alt="ikona 02" /&gt;&lt;/div&gt; &lt;div id="iconTechBig04" class="iconBig"&gt;&lt;img src="img/icons/tech/tech04Big.png" alt="ikona 02" /&gt;&lt;/div&gt; </code></pre>
[]
[ { "body": "<p>Certainly, assign a class to each tech icon (I'm assuming they're divs), use a JQuery selector to select all DOM element with the assigned class and then use <code>each()</code> to step through each item. </p>\n\n<pre><code>&lt;div class=\"icon\" id=\"iconTech01\"&gt;&lt;img ..../&gt;&lt;/div&gt;\n&lt;div class=\"icon\" id=\"iconTech02\"&gt;&lt;img ..../&gt;&lt;/div&gt;\n&lt;div class=\"icon\" id=\"iconTech03\"&gt;&lt;img ..../&gt;&lt;/div&gt;\n\n&lt;script type=\"text/javascript\"&gt;\n$('.icon').each(function () {\n $(this).hover(\n function () {\n $(this).stop(true, true).fadeIn(\"slow\");\n },\n function () {\n $('img', this).stop(true, true).fadeOut(\"slow\");\n }\n );\n});\n&lt;/script&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T08:36:28.090", "Id": "19452", "Score": "0", "body": "I think you can do directly `$('.icon').hover(function () { });`, or the modern version: `$('.icon').on('hover', function () {});` - but one would need to test it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T09:14:29.043", "Id": "19454", "Score": "0", "body": "i will test it and let you know how it goes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T09:37:48.000", "Id": "19456", "Score": "0", "body": "i've added html code, there are iconTechxx and iconTechBigxx and on hover iconTechxx is fadeout and iconTechBigxx is fadein, example that Sacred Socks wrote it's obvious, my problem is slightly more complex" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:04:23.037", "Id": "19468", "Score": "0", "body": "hey gidzior, sorry i'm a little bit confused as to what you're trying to do - are you trying to build scroll over icons like on Mac OS?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T15:25:47.953", "Id": "12145", "ParentId": "12141", "Score": "4" } }, { "body": "<p>Overall it could be written like this, assuming we could write a suitable <code>getBigHere</code> function:</p>\n\n<pre><code>$('.icon').each(function () {\n var $this = $(this),\n $big = getBigHere($this);\n $this.on({\n mouseenter: function () {\n $this.find('img').stop(true, true).fadeOut('slow');\n $big.stop(true, true).fadeIn('slow');\n },\n mouseleave: function () {\n $big.stop(true, true).fadeOut('slow');\n $this.find('img').stop(true, true).fadeIn('slow');\n }\n });\n});\n</code></pre>\n\n<p>So the question is how can that function be written?</p>\n\n<p>If you can alter the html, you could add a <code>data-for</code> attribute (or something like that) to the div tags with the ids of the big div tags:</p>\n\n<pre><code>&lt;div id=\"iconWraper\"&gt;\n &lt;div id=\"iconTech01\" class=\"icon\" data-for=\"iconTechBig01\"&gt;...&lt;/div&gt;\n ...\n&lt;/div&gt;\n&lt;div id=\"iconTechBig01\" class=\"iconBig\"&gt;...&lt;/div&gt; \n...\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>function getBigHere($t) { return $('#' + $t.data('for')); }\n</code></pre>\n\n<p>Otherwise we need to get a little messy:</p>\n\n<pre><code>function getBigHere($t) { return $('#iconTechBig' + $t.attr('id').slice(-2)); }\n</code></pre>\n\n<p>Fortunately the second can be inlined nicely:</p>\n\n<pre><code>$('.icon').each(function () {\n var $this = $(this),\n $big = $('#iconTechBig' + this.id.slice(-2));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T14:25:39.760", "Id": "19466", "Score": "0", "body": "I've updated question, consol says that \"$this.on is not a function\", what's wrong ??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T14:55:40.407", "Id": "19467", "Score": "1", "body": "What version of jQuery are you using? `.on` was added in 1.7; if you are using an older version you can use `.hover` instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:07:33.043", "Id": "19470", "Score": "0", "body": "it's almost working, i will put link to the example a little bit later" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T20:33:20.700", "Id": "19502", "Score": "0", "body": "well this is the long version http://gidzior.net/hover/project.html and this is the new one http://gidzior.net/hover/projectNew.html there is something wrong" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T20:55:00.450", "Id": "19503", "Score": "0", "body": "`$this.stop(true, true)` should be `$this.find('img').stop(true, true)`. [Fiddle here](http://jsfiddle.net/2suhh/)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T21:07:31.613", "Id": "19504", "Score": "0", "body": "yeah guys you are great, thx for help" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T13:31:08.250", "Id": "12161", "ParentId": "12141", "Score": "4" } } ]
{ "AcceptedAnswerId": "12161", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T13:49:57.347", "Id": "12141", "Score": "4", "Tags": [ "javascript", "jquery", "html", "image" ], "Title": "Showing different icons on hover" }
12141
<p>The reason why I want to have something like this is to be able to add custom methods/props to certain arrays only. I came up with this little object that works well but I'm wondering if you guys have better way.</p> <pre><code>(function (scope) { var target = scope || window; target.Hurray = function() { this.length = 0; this.count = 0; var _arr = Array.prototype.slice.call(arguments); this.reset = function() { for (var prop in this) { if (!isNaN(prop)) { this[prop] = undefined; try { delete this[prop]; } catch(e) { } } } for (var x = 0; x &lt; _arr.length; x++) { this[x] = _arr[x]; } this.length = _arr.length; this.count = this.length; }; this.reset(); this.toArray = function() { return _arr; }; this.concat = function() { _arr.concat.apply(_arr, arguments); this.reset(); return this; }; this.indexOf = function() { var index = _arr.indexOf.apply(_arr, arguments); this.reset(); return index; }; this.join = function() { var rtn = _arr.join.apply(_arr, arguments); this.reset(); return rtn; }; this.lastIndexOf = function() { var index = _arr.reverse().indexOf.apply(_arr, arguments).reverse(); return index; }; this.pop = function() { var elem = _arr.pop.apply(_arr, arguments); this.reset(); return elem; }; this.push = function() { var elem = _arr.push.apply(_arr, arguments); this.reset(); return elem; }; this.reverse = function() { _arr.reverse.apply(_arr, arguments); this.reset(); return this; }; this.shift = function() { var elem = _arr.shift.apply(_arr, arguments); this.reset(); return elem; }; this.slice = function() { return _arr.slice.apply(_arr, arguments); }; this.sort = function() { _arr.sort.apply(_arr, arguments); this.reset(); return this; }; this.splice = function() { _arr.splice.apply(_arr, arguments); this.reset(); return this; }; this.toString = function() { return _arr.toString.apply(_arr, arguments); }; this.unshift = function() { _arr.concat.apply(_arr, arguments); this.reset(); return this.length; }; this.valueOf = function() { return _arr.concat.apply(_arr, arguments); }; this.add = function() { return this.push.apply(this, arguments); }; this.removeAt = function(index) { return this.splice(index, 1); }; this.find = function(value, caseInsensitive) { var rtn = new Hurray(); if (!caseInsensitive) { for (var x = 0; x &lt; this.length; x++) { var currval = this[x]; if (currval == value) rtn.push(currval); } } else { value = value.toString().toLowerCase(); for (var x = 0; x &lt; this.length; x++) { var currval = this[x].toString().toLowerCase(); if (currval == value) rtn.push(currval); } } }; this.findByProperty = function(key, value, caseInsensitive) { var rtn = new Hurray(); if (!caseInsensitive) { for (var x = 0; x &lt; this.length; x++) { var currval = this[x][key]; if (currval == value) rtn.push(currval); } } else { value = value.toString().toLowerCase(); for (var x = 0; x &lt; this.length; x++) { var currval = this[x][key].toString().toLowerCase(); if (currval == value) rtn.push(currval); } } }; this.replace = function() { var args = Array.prototype.slice.call(arguments); args.splice(1, 1, 0); // Add 1 as the delete parameter return this.splice.apply(this, args); }; this.insert = function() { var args = Array.prototype.slice.call(arguments); args.splice(1, 0, 0); // Add 0 as the delete parameter return this.splice.apply(this, args); }; this.addRange = function() { return this.concat.apply(this, arguments); }; this.insertRange = function() { var arrays = Array.prototype.slice.call(arguments); var index = arrays.splice(0, 1); for (var x = 0; x &lt; arrays.length; x++) { for (var k = 0; k &lt; arrays[x].length; k++) { _arr.splice(index++, 0, arrays[x][k]); } } this.reset(); return this; }; this.getRange = function() { return this.concat.slice(this, arguments); }; this.remove = function(value, onlyFirstFind) { var index = _arr.indexOf(value); if (index == -1) return this; _arr.splice(index, 1); index = _arr.indexOf(value); if (!onlyFirstFind) { while (index != -1) { _arr.splice(index, 1); index = _arr.indexOf(value); } } this.reset(); return this; }; this.clear = function() { _arr = []; this.reset(); return this; }; this.contains = function(value, caseInsensitive) { if (!caseInsensitive) { return this.indexOf(value) != -1; } else { var value = value.toString().toLowerCase(); for (var x = 0; x &lt; this.length; x++) { if (this[x].toString().toLowerCase() == value) { return true; } } } return false; }; this.each = function(callback) { for (var x = 0; x &lt; _arr.length; x++) { var newVal = callback.apply(this, [_arr[x]]); if (newVal) _arr[x] = newVal; } this.reset(); return this; }; this.toHurray = function() { return this; }; }; Array.prototype.toHurray = function () { return new Hurray().concat(this); }; })(); //scope goes here! </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T19:35:45.477", "Id": "19414", "Score": "2", "body": "What's wrong with using regular arrays? How many do you have?" } ]
[ { "body": "<p>If you don't need the magic <code>.length</code> property, then how about making a constructor function whose prototype is an object that inherits from <code>Array.prototype</code>?</p>\n\n<pre><code>function Hurray() {}\n\nHurray.prototype = Object.create(Array.prototype);\n</code></pre>\n\n<hr>\n\n<pre><code>var h = new Hurray;\nh.push('a','b','c');\n\nalert(h.length); // 3\n\nvar last = h.pop();\n\nalert(last); // 'c'\nalert(h.length); // 2\n</code></pre>\n\n<p>And add your custom methods to <s><code>Array.prototype</code></s> <code>Hurray.prototype</code> as you need. <em>(Thanks to <a href=\"https://codereview.stackexchange.com/users/12874/bill-barry\">Bill Barry</a> for spotting my mistake!)</em></p>\n\n<p>The way you're doing it right now, you're not taking any advantage of inheritance, but instead are creating a bunch of duplicate functions every time a new object is created.</p>\n\n<hr>\n\n<p>If you don't want the original Array methods, you could still use prototypal inheritance for your methods, and use the <code>Array.prototype</code> methods under the hood.</p>\n\n<pre><code>var _arr_proto = Array.prototype;\n\nfunction Hurray() {}\nHurray.prototype.length = 0;\n\nHurray.prototype.add = function() {\n _arr_proto.push.apply(this, arguments);\n return this;\n};\nHurray.prototype.removeFromEnd = function() {\n _arr_proto.pop.apply(this, arguments);\n return this\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T15:25:47.633", "Id": "19419", "Score": "2", "body": "just one small nit, don't modify `Array.prototype`, modify `Hurray.prototype`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T15:48:49.320", "Id": "19420", "Score": "0", "body": "@BillBarry: Ah, I didn't see it at first, but you're talking about my sentence... *\"...add your custom methods to `Array.prototype` as you need\"*, and you're absolutely correct. That was a flub... should have said `Hurray.prototype`. Thanks for spotting it!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T19:39:23.290", "Id": "12143", "ParentId": "12142", "Score": "9" } } ]
{ "AcceptedAnswerId": "12143", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T19:32:23.907", "Id": "12142", "Score": "3", "Tags": [ "javascript" ], "Title": "What is a good way create a Javascript array-like object?" }
12142
<p><strong>Edit</strong></p> <p>The rest of my code utilises the Command/Query seperation pattern. I'll probably move this out into a command and a query but for now I've written this directly in my MVC controller for brevity.</p> <p><strong>Original</strong></p> <p>I'm quite new to Fluent NHibernate and its various workings. This code is designed to receive an array of tag names, get those tags from the database and then create any tags that were in the array but not already in the database.</p> <p>Here's the code I've just written:</p> <pre><code>private IEnumerable&lt;Tag&gt; GetOrCreateTags(IEnumerable&lt;string&gt; tagNames) { var tagCriteria = _nHibernateSession.CreateCriteria&lt;Tag&gt;(); var or = Restrictions.Disjunction(); foreach (var tagName in tagNames) { or.Add(Restrictions.Eq("Name", tagName)); } tagCriteria.Add(or); var tagsFromTagNames = tagCriteria.List&lt;Tag&gt;(); foreach (var newTagNeverSeen in tagNames.Except(tagsFromTagNames .Select(x =&gt; x.Name))) { using (var transaction = _nHibernateSession.BeginTransaction()) { var newTag = new Tag { Name = newTagNeverSeen, Enabled = true, DateCreated = DateTime.Now }; _nHibernateSession.SaveOrUpdate(newTag); tagsFromTagNames.Add(newTag); transaction.Commit(); } } return tagsFromTagNames; } </code></pre> <p>How would you improve this? I feel like I'm doing too much here already so I'll likely refactor this to split it out.</p>
[]
[ { "body": "<p>Admittedly I am using a really old version of nhibernate, but I think this is still there (to replace a few lines):</p>\n\n<pre><code>Restrictions.InG(\"Name\", tagNames.ToList())\n</code></pre>\n\n<p>I think I would also bring the using statement outside of the loop:</p>\n\n<pre><code>private IEnumerable&lt;Tag&gt; GetOrCreateTags(IEnumerable&lt;string&gt; tagNames)\n {\n var tagList = tagNames.ToList(); //or make the parameter above an ICollection&lt;string&gt;\n\n var tagCriteria = _nHibernateSession.CreateCriteria&lt;Tag&gt;();\n tagCriteria.Add(Restrictions.InG(\"Name\", tagList));\n\n var tagsFromTagNames = tagCriteria.List&lt;Tag&gt;();\n\n //naming this for readability\n var existingTagNames = tagsFromTagNames.Select(x =&gt; x.Name);\n\n var newTags = tagList\n .Except(existingTagNames)\n .Select(t =&gt; new Tag\n {\n Name = newTagNeverSeen,\n Enabled = true,\n DateCreated = DateTime.Now\n }); //moving this outside the loop makes the loop cleaner\n\n if (newTags.Any())\n {\n using (var transaction = _nHibernateSession.BeginTransaction())\n {\n foreach (var tag in newTags)\n {\n _nHibernateSession.SaveOrUpdate(tag);\n tagsFromTagNames.Add(tag);\n }\n transaction.Commit();\n }\n }\n return tagsFromTagNames;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T17:06:38.500", "Id": "19487", "Score": "0", "body": "Thanks Bill, just what I was looking for. The `InG` method works a treat and moving the `using` statement out of the loop seems obvious now you mention it. Cheers again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T17:11:05.950", "Id": "19489", "Score": "0", "body": "The other parts are really helpfull too. The code is much more readable now. To note, the `InG` restriction can take the `IEnumerable<string>` tagNames as an input so no need for the conversion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T18:25:47.913", "Id": "19493", "Score": "0", "body": "Good to know, my version doesn't take `IEnumerable`. Yet another reason to upgrade." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T14:01:13.160", "Id": "12163", "ParentId": "12150", "Score": "2" } } ]
{ "AcceptedAnswerId": "12163", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T18:23:38.980", "Id": "12150", "Score": "1", "Tags": [ "c#", "asp.net-mvc-3" ], "Title": "Fluent NHibernate, Getting or Creating a new `Tag`" }
12150
<p>I need to pass an array of values in Url.Action.</p> <p>Currently I'm doing:</p> <pre><code>var redirectUrl = Url.Action("search", new { q = criteria.Q, advanced = criteria.Advanced, salaryfrom = criteria.SalaryFrom, salaryto = criteria.SalaryTo, }); if (criteria.JobTypes != null) redirectUrl += criteria.JobTypes.Aggregate(string.Empty, (a, x) =&gt; a += "&amp;jobTypes=" + x); </code></pre> <p>To give me something like:</p> <pre><code>/search?q=developer&amp;advanced=false&amp;salaryfrom=20000&amp;salaryto=80000&amp;jobTypes=Full%20Time&amp;jobTypes=Contract </code></pre> <p>Is there a nicer/cleaner approach?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T13:11:47.583", "Id": "19433", "Score": "0", "body": "If it is few 2-4, It is ok to pass in URL ,But you have lots of values, I would like to pass an ID and get the object again in the next action method. But in your case i guess it is the search criteria from a search form, This should be OK to do ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T08:42:49.270", "Id": "19453", "Score": "0", "body": "As per @Cygal's answer, the main reason we include the criteria in the URL is so that search results are GETable. So when someone POSTs a search, all we do is form the URL based on their input and redirect to our GET action." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T14:08:39.763", "Id": "19463", "Score": "0", "body": "see: [stackoverflow:asp-net-mvc-routedata-and-arrays](http://stackoverflow.com/questions/1752721/asp-net-mvc-routedata-and-arrays)" } ]
[ { "body": "<ul>\n<li>Concerning the comment you got about passing an ID, note that it's better to put search parameters in the URL, since it allows users to link to that search and refresh the page without having issues. All search engines do that.</li>\n<li>Make sure to test for null without using type coercion: <code>if(criteria.JobTypes !== null)</code>. It's a best practice that will avoid you a few surprises.</li>\n<li>As for passing an array of values, I don't know much about ASP.NET but it looks like you can pass an array of values with <a href=\"https://stackoverflow.com/questions/717690/asp-net-mvc-pass-array-object-as-a-route-value-within-html-actionlink\">Html.ActionLink</a>. I don't know what version you're using but this seems specific to ASP.NET MVC 2.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T07:59:56.280", "Id": "12158", "ParentId": "12151", "Score": "1" } } ]
{ "AcceptedAnswerId": "12158", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T13:07:25.370", "Id": "12151", "Score": "2", "Tags": [ "c#", "asp.net" ], "Title": "Passing an array of values in UrlAction" }
12151
<p>I am not experienced in C++, and wrote this code for implementing a stack data structure using a linked list.</p> <p>Can you please point out any flaws, errors, stupid mistakes, general improvements etc that can make this code better?</p> <pre><code>#include &lt;iostream&gt; using namespace std; struct Node; struct Node { int data; Node* next; }; class Stack { public: Node* first; Node* last; Stack() { first = 0; last = 0; } ~Stack() { while (first != 0) { pop(); } } Stack&amp; push(int value) { Node* temp = new Node; temp-&gt;data = value; temp-&gt;next = 0; if (first == 0) { first = temp; last = temp; } else { last-&gt;next = temp; last = last-&gt;next; } cout &lt;&lt; "Pushed " &lt;&lt; value &lt;&lt; " on the stack\n"; temp = 0; return *this; } Stack&amp; pop() { if (first == 0) { cout &lt;&lt; "No nodes to pop.\n"; } else { // only one node left if (first == last) { cout &lt;&lt; "Popped " &lt;&lt; first-&gt;data &lt;&lt; " off the stack\n"; delete first; first = 0; last = 0; return *this; } Node* temp = first; while (temp-&gt;next != last) { temp = temp-&gt;next; } cout &lt;&lt; "Popped " &lt;&lt; last-&gt;data &lt;&lt; " off the stack\n"; delete last; last = temp; last-&gt;next = 0; } return *this; } }; int main() { Stack s; s.pop(); s.push(1); s.push(2); s.pop(); s.push(3).push(4); s.pop().pop(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T06:00:31.673", "Id": "19447", "Score": "1", "body": "If you are using c++, is there any reason you are not using STL containers?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T06:01:45.233", "Id": "19448", "Score": "4", "body": "Yes, I wanted to learn my way around basics before plunging into STL." } ]
[ { "body": "<p>A few comments, wrt style.</p>\n\n<pre><code>#include &lt;iostream&gt; \nusing namespace std;\n</code></pre>\n\n<p>You don't need a forward declaration of struct Node.</p>\n\n<pre><code>//struct Node;\n</code></pre>\n\n<p>You could add a constructor here just like in class. So your initialization\nis simpler.</p>\n\n<pre><code>struct Node {\n int data;\n Node* next;\n Node(int d):data(d), next(0){}\n};\n</code></pre>\n\n<p>It may be a good idea to write an abstract class as an interface, and then write\nthe concrete class to conform to it. Another idea is to try to templatize Node so that the data can be any type. Also look at the stack class in STL</p>\n\n<p>You may also want top() and empty() methods</p>\n\n<p>on logic: If you are going to implement a stack using a linked list, you don't really need to keep a first and a last. Just keep the reference to the top element. On push, create a new node, set its next to the current top, and set it to top. On pop, set the top to the next of current top, and delete the node. Something along the lines of: (may contain bugs.)</p>\n\n<pre><code>struct Node {\n int data;\n Node* next;\n Node(int v, Node* n):data(v),next(n) {}\n};\n\nclass Stack {\n public:\n Node* top;\n Stack():top(0){}\n ~Stack() {\n while (top != 0) pop();\n }\n Stack&amp; push(int value) {\n top = new Node(value, top);\n return *this;\n } \n Stack&amp; pop() {\n if (!top) throw \"No nodes to pop.\";\n Node* t = top;\n top = top-&gt;next;\n delete t;\n return *this;\n }\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T06:38:38.660", "Id": "12156", "ParentId": "12155", "Score": "6" } }, { "body": "<h3>Style</h3>\n\n<p>Please learn to indent your code consistently.<br>\nThis is really hard to read and make sure ti works.</p>\n\n<h3>Algorithm</h3>\n\n<p>I would expect both <code>push()</code> and <code>pop()</code> to have a complexity of O(1). Unfortunately the pop is O(n) as you have to search to the end to remove the last item.</p>\n\n<pre><code> while (temp-&gt;next != last) {\n temp = temp-&gt;next;\n }\n</code></pre>\n\n<p>You can solve this by using a doubly linked list. Then removing the last item would be:</p>\n\n<pre><code> temp = last-&gt;prev;\n</code></pre>\n\n<p>Personally I would use a doubly linked list and sentinel values (thus you don't need to check for NULL). This makes both inserting and removing the values very simple.</p>\n\n<pre><code> // Note: First points at the sentinel.\n // Last points at the last item inserted.\n // If no items are inserted then it points at the sentinel.\n // When there are no items the sentinel points at itself in next/prev\n // thus making the list circular.\n stack&amp; push(int value)\n {\n // Value Prev Next\n Node* temp = new node(value, last, last-&gt;next);\n last-&gt;next-&gt;prev = temp;\n last-&gt;next = temp;\n last = temp;\n return *this;\n }\n stack&amp; pop()\n {\n if (first == last)\n { throw std::runtime_error(\"Bad Pop\");\n }\n Node* temp = last;\n last-&gt;next-&gt;prev = temp-&gt;prev;\n last-&gt;prev-&gt;next = temp-&gt;next;\n delete temp;\n return *this;\n }\n</code></pre>\n\n<h3>Code Comments</h3>\n\n<p>Stop doing this</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Its a bad habit to get into it. See my other posts for an explanation.</p>\n\n<p>Use encapsulation correctly.</p>\n\n<pre><code>public:\n Node* first;\n Node* last;\n</code></pre>\n\n<p>Member variables should not be public.<br>\nModification of the object state should only be through a controlled environment (method call). </p>\n\n<p>Note: It is OK for the <code>Node</code> to have all public member variables (ie a struct)</p>\n\n<pre><code>struct Node {\n int data;\n Node* next;\n};\n</code></pre>\n\n<p>This is because you never expose a <code>Node</code> object via the <code>Stack</code> interface. Though personally I would make node a private sub class inside the <code>Stack</code> class.</p>\n\n<p>Use a constructor in Node to set it up.</p>\n\n<pre><code> Node* temp = new Node;\n temp-&gt;data = value;\n temp-&gt;next = 0;\n\n // Can be written:\n Node* temp = new Node(value, 0);\n</code></pre>\n\n<p>Don't bother with this.<br>\nIt does not add to readability and it does no work.</p>\n\n<pre><code> temp = 0;\n</code></pre>\n\n<p>In main if you don't explicitly return the compiler inserts a return 0. Thus if there is no possibility of an error state for your program then don't return anything (this is an indication that it will always work).</p>\n\n<pre><code>int main() {\n // return 0; Don't need this if the application always works.\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T07:01:44.543", "Id": "12157", "ParentId": "12155", "Score": "6" } }, { "body": "<p>Adding to what has already been mentioned by others.</p>\n\n<ol>\n<li><p>Since you wish to learn C++, it is alright to implement a stack\nclass. On the other hand, if you want a stack class for use in a\nproduction project, it would be wiser to simply use the built-in STL\nstack class. Humble thyself and reuse :)</p></li>\n<li><p>The std namespace</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>You are dumping all the identifiers from the <code>std</code> namespace into your global namespace. This defeats the purpose of having namespaces. Since the only thing that you are using from the <code>std</code> namespace is <code>cout</code>, you can write <code>using std::cout;</code> or <code>std::cout &lt;&lt; \"Pushed \" &lt;&lt; value &lt;&lt; \" on the stack\\n\";</code> Read <a href=\"http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.5\" rel=\"nofollow\">this</a> for more.</p></li>\n<li><p>In the <code>Stack</code> class's constructor, prefer initialization lists to assignment. Read more <a href=\"http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6\" rel=\"nofollow\">here</a>.</p></li>\n<li><p>In future, when you go one step forward and start implementing reusable\nclasses, you would need to start thinking about how another part of\nyour code (say, another class) can use your <code>Stack</code> class. Currently,\nthis is not (directly/gracefully/intuitively) possible because the other class can only <em>push</em> data onto\nthe stack; it cannot retrieve any data since the <code>pop()</code> method does\nnot return any <code>int</code> data.</p></li>\n<li><p>For containers like the stack, you should also (at least) implement\noverloaded assignment operator and copy constructor.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T18:19:28.197", "Id": "12202", "ParentId": "12155", "Score": "2" } } ]
{ "AcceptedAnswerId": "12157", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T05:57:54.337", "Id": "12155", "Score": "5", "Tags": [ "c++", "stack" ], "Title": "Simple stack implementation" }
12155
<p>I was building a quiz module for one website. It is a simple true/false statements where you first choose the answer, the correct answer is displayed, and then you can move forward to the next question. </p> <p>For better understanding, please find working code snippet <a href="http://jsfiddle.net/ylokesh/Qaf8w/50/" rel="nofollow">here</a>.</p> <p>I need mentor guidance in order to make my existing code shorter and optimized. </p> <p>Here is the jQuery code for this quiz module:</p> <pre><code>var flag = $('.quiz ul'), currentPosition = 0, currentQuestion = 0, slideWidth = 200, option = $('.flag'), tryCTA = $('.CTAtry'), nextQuestion = $('.next'), answer = $('span.answer') questionWrapper = $('.quiz ul'), totalQuestions = $('.quiz ul li').length, answers = ["True","False","False"]; //Set UL width questionWrapper.css('width',totalQuestions*slideWidth) option.on('click',function(e) { e.preventDefault(); var nextCTA = $(this).parent().next(nextQuestion).length, optionWrapper = $(this).parent(); if(nextCTA) { optionWrapper.next(nextQuestion).show(); } else { tryCTA.show(); } optionWrapper.parent().find(answer).html(answers[currentQuestion]).show(); optionWrapper.hide(); }); nextQuestion.on('click',function(e){ e.preventDefault(); currentPosition = currentPosition+1; $(this).parent().parent().animate({ 'marginLeft' : slideWidth*(-currentPosition) }); currentQuestion++; }); tryCTA.on('click',function(e) { e.preventDefault(); resetQuiz(e); $(this).hide(); }) function resetQuiz(e) { $('.quiz ul').animate({ opacity: 0 },0) .animate({ opacity: 1 },500) $('span.answer').html(" "); $('.quiz ul').css('margin-left','0'); $('.options').show(); $('.next').hide(); currentPosition = 0; currentQuestion = 0; } </code></pre> <p>HTML: </p> <pre><code>&lt;div class="quiz"&gt; &lt;ul&gt; &lt;li&gt; &lt;span class="answer"&gt;&lt;/span&gt; &lt;p&gt;Writing Object Oriented JavaScript is not a FUN.&lt;/p&gt; &lt;div class="options"&gt; &lt;a href="" class="flag"&gt;True&lt;/a&gt; &lt;span&gt;or&lt;/span&gt; &lt;a href="" class="flag"&gt;False&lt;/a&gt; &lt;/div&gt; &lt;a href="" class="next"&gt;Next&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;span class="answer"&gt;&lt;/span&gt; &lt;p&gt;Let's give it a try! No harm in learning anything NEW.&lt;/p&gt; &lt;div class="options"&gt; &lt;a href="" class="flag"&gt;True&lt;/a&gt; &lt;span&gt;or&lt;/span&gt; &lt;a href="" class="flag"&gt;False&lt;/a&gt; &lt;/div&gt; &lt;a href="" class="next"&gt;Next&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;span class="answer"&gt;&lt;/span&gt; &lt;p&gt;Some code running !&lt;/p&gt; &lt;div class="options"&gt; &lt;a href="" class="flag"&gt;True&lt;/a&gt; &lt;span&gt;or&lt;/span&gt; &lt;a href="" class="flag"&gt;False&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;a href="" class="CTAtry"&gt;Try Again!&lt;/a&gt; &lt;/div&gt; </code></pre>
[]
[ { "body": "<p>Overall this is already pretty well organized and compact. There isn't a lot of duplication or obvious abstractions that can be made. It would be helpful to see the HTML to see if there are any changes that would make the Javascript easier to write.</p>\n<p>A couple of suggestions:</p>\n<ol>\n<li><p>Wrap the entire code block in an <a href=\"http://benalman.com/news/2010/11/immediately-invoked-function-expression/\" rel=\"nofollow noreferrer\">IIFE</a> to avoid cluttering global namespace</p>\n<pre><code> (function ($, undefined) {\n // Your code here ...\n } (jQuery));\n</code></pre>\n</li>\n<li><p>Use <code>.width()</code> instead of <code>.css('width', ...)</code></p>\n</li>\n<li><p>Some of your variables are only being referenced once and can be inlined:</p>\n<pre><code> $('.flag').on('click', ...); // etc.\n</code></pre>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T08:29:07.540", "Id": "19578", "Score": "0", "body": "About 4, he cannot merge them because the `.show()` is applied to the \"answer\" inside the \"optionWrapper\", and the hide is applied to the \"optionWrapper\". But yes, the `.show()` feels redundant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T10:16:54.990", "Id": "19581", "Score": "0", "body": "@pgraham thanks a lot for your feedback. I will definitely incorporate your points and post the updated code by tomorrow. Only thing where i need some guidance is \"Why are we passing 'undefined' with $\"?? any specific reason ??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T14:09:34.257", "Id": "19636", "Score": "1", "body": "passing undefined and then not providing a value for it is a way of protecting against `undefined = 'A defined value';` or similar somewhere in previous code. It is not strictly necessary but ensures that `undefined` is actually `undefined` within that block of code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-05-31T21:18:57.000", "Id": "12205", "ParentId": "12164", "Score": "3" } } ]
{ "AcceptedAnswerId": "12205", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T14:56:44.057", "Id": "12164", "Score": "4", "Tags": [ "javascript", "jquery", "html" ], "Title": "Static quiz module with predefined answers" }
12164
<p>I wrote a factorial/permutations/combinations program in Java, and I want to do the same in C#. I noticed (from various research) that when you use the <code>ulong</code> variable type, the max value is higher than Java's <code>long</code>. My limitation in the Java version was that the <code>long</code> type was too small to do numbers like 30, or 100. I wrote a little thing that would test if my hypothesis that C# could stretch the range of my program, but I was proven wrong. My Java version can reach approximately 24, but the C# goes to roughly 20. Is there anything I can do to reach my goal?</p> <pre><code>using System; namespace codeAdmiral{ public class Factorial{ public static void Main(){ ulong num; Console.WriteLine("Enter value"); num = ulong.Parse(Console.ReadLine()); ulong factorial = 1; for (ulong forBlockvar = num; forBlockvar &gt; 1; forBlockvar--){ factorial *= forBlockvar; } Console.WriteLine("The Factorial for the Given input is:"); Console.WriteLine(factorial); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:06:18.713", "Id": "19469", "Score": "2", "body": "Use `double` if you want a greater range." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:08:34.853", "Id": "19471", "Score": "0", "body": "In Java, things got screwed up when i tried to use a double... Are ulong and double interchangable like int and long in Java??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:31:58.553", "Id": "19472", "Score": "1", "body": "@JesseC.Slicerm Using `double` to compute precise values is not a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:33:34.680", "Id": "19474", "Score": "0", "body": "Not in the least. Check out these tables for what their differences are: http://msdn.microsoft.com/en-us/library/exx3b86w and http://msdn.microsoft.com/en-us/library/9ahet949.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:35:33.057", "Id": "19475", "Score": "0", "body": "@JesseC.Slicer My point is that if you use `double`, you won't get precise results. When you're computing factorials, approximate results are usually not enough." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:35:37.973", "Id": "19476", "Score": "0", "body": "@svick Yes, I am well aware of that point. Unfortunately, we don't have integer types that have that range for such a computation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:36:10.967", "Id": "19477", "Score": "3", "body": "@JesseC.Slicer [Are you sure?](http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:38:07.223", "Id": "19478", "Score": "0", "body": "@svick fascinating. Well there goes my productivity for the day." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:42:39.990", "Id": "19479", "Score": "0", "body": "@JesseC.Slicer Great! Another feature introduced in .NET 4.0 that I didn't know about." } ]
[ { "body": "<p>Signed 64-bit integer (<code>long</code> in both Java and C#) can have values between approximately -9 · 10<sup>18</sup> and 9 · 10<sup>18</sup>. Unsigned 64-bit integer (<code>ulong</code> in C#) can have values between 0 and approximately 1.8 · 10<sup>19</sup>. The value of 20! is approximately 2 · 10<sup>18</sup>, so it fits comfortably both to <code>long</code> and <code>ulong</code>. The value of 21! is approximately 5 · 10<sup>19</sup>, so it doesn't fit even into <code>ulong</code>.</p>\n\n<p>Because of this, 20! should be computed correctly both in Java and c#, but 21! should be incorrect in both, no matter whether you use <code>long</code> or <code>ulong</code>.</p>\n\n<p>If you want to make sure you are getting correct results in C#, you can use <a href=\"http://msdn.microsoft.com/en-us/library/a569z7k8.aspx\"><code>unchecked</code></a>. If you do that and the computation overflows, you will get an exception.</p>\n\n<p>What should you do if you want to compute larger values than 20!? The best option would be if there was some type that could represent arbitrarily large integers. Fortunately, both languages have them, there is <a href=\"http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx\"><code>BigInteger</code> in C#</a> and <a href=\"http://docs.oracle.com/javase/1.4.2/docs/api/java/math/BigInteger.html\"><code>BigInteger</code> in Java</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T16:22:36.790", "Id": "19484", "Score": "0", "body": "Alright, thanks!! I have tried to use BigInteger in the Java version a while back, but that was before I understood oo programming..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T18:11:12.800", "Id": "19490", "Score": "1", "body": "The fact that factorial grows so fast makes a compelling case to store the first 20 results pre-computed in a static look-up array for practical implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T18:19:45.177", "Id": "19492", "Score": "0", "body": "But that just isnt the same :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T18:44:36.690", "Id": "19497", "Score": "1", "body": "@Leonid I don't see much reason to do that. Computing 20! is so fast that pre-computing it most likely won't speed up your code noticeably." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T14:05:39.320", "Id": "19613", "Score": "0", "body": "And it's more satisfiying to write something that computes it rather than just creating an array :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:50:42.227", "Id": "12169", "ParentId": "12165", "Score": "8" } } ]
{ "AcceptedAnswerId": "12169", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:00:29.433", "Id": "12165", "Score": "3", "Tags": [ "c#" ], "Title": "Factorial/permutations/combinations program" }
12165
<p>I struggled a short while to make this work, so I'm wondering if there are any smarter ways for finding the highest of two values per array element? Uh, hard to explain by words, but by code its easy:</p> <p>Data (random):</p> <pre><code> (a) (b) // a and b are both positive values. 10 0.5 13 10.8 8 0.123 9 0.123 17 0.3 17 0.4 &lt;- must find this 17 0.1 0 0.13 0 0.5 </code></pre> <p>Code:</p> <pre><code>int max_a = -1; float max_b = -1; for(int i = 0; i &lt; total_values; i++){ if(values[i].a &gt; max_a){ max_a = values[i].a; max_b = -1; // reset } if(values[i].a == max_a){ if(values[i].b &gt; max_b){ max_b = values[i].b; found_id = i; } } } </code></pre> <p>So far it seems to work. But is this the most efficient way of doing this? (without changing the for loop; must loop linearly like that)</p> <p><strong>Edit:</strong> Some notes: I use std::vector for my arrays. The code should work with any struct given to the vector, only 2 of the elements from that struct will be used for value checking. <strong>Edit2:</strong> Values cannot have negative values, thats why there is initial -1 values set to mean "not set".</p> <p><strong>Edit: My test code:</strong></p> <pre><code>struct valuestruct { int a; float b; // this could have more values than just two. still, only two values are tested. // using shortest struct as possible to save memory for testing. valuestruct(int a, float b) : a(a), b(b) {} }; bool operator&lt;(const valuestruct &amp;v1, const valuestruct &amp;v2){ return (v1.a &lt; v2.a) || ((v1.a == v2.a) &amp;&amp; (v1.b &lt; v2.b)); } void test_speeds(){ // initialize array values: int total_values = 10000000; // = 80megs ram vector&lt;valuestruct&gt; values; for(int i = 0; i &lt; total_values; i++){ values.push_back(valuestruct(random(0,1000), random(0.0f,100.0f))); } int found_id = -1; // dummy stuff for preventing loops optimized off: int ids = 0; int out_id1 = -1; int out_id2 = -1; int out_id = -1; // Loki's solution: float t1 = microtime(); if(total_values &gt; 0){ // prevent crash accessing empty array. for(int dummy_repeat = 0; dummy_repeat &lt; 100; dummy_repeat++){ valuestruct max = values[0]; for(int i = 1; i &lt; total_values; i++){ if(max &lt; values[i]){ max = values[i]; found_id = i; } } out_id = found_id; ids += found_id; // dummy } out_id2 = out_id; } float speed1 = microtime()-t1; // Keith's solution: float t2 = microtime(); for(int dummy_repeat = 0; dummy_repeat &lt; 100; dummy_repeat++){ int max_a = -1; float max_b = -1; for(int i = 0; i &lt; total_values; i++){ if(values[i].a &gt; max_a || (values[i].a == max_a &amp;&amp; values[i].b &gt; max_b)){ max_a = values[i].a; max_b = values[i].b; found_id = i; } } out_id = found_id; ids += found_id; // dummy } out_id1 = out_id; float speed2 = microtime()-t2; clock_t t3 = clock(); for(int dummy_repeat = 0; dummy_repeat &lt; 100; dummy_repeat++){ std::vector&lt;valuestruct&gt;::iterator find = std::max_element(values.begin(), values.end()); found_id = std::distance(values.begin(), find); out_id = found_id; ids += found_id; // dummy } clock_t speed3 = clock() - t3; // Output: // Lokis: 6166.7ms // Keith: 3932.1ms // Timing on Loki's machine (using 1000 dummy iterations) // Compiled uisng g++ -O3 (replaced microtime() with clock()) // Times are in seconds (result is the value of ids) Loki: 12.814812000 Result: 53500000 Keith: 12.885715000 Result: 53500000 Max: 12.832419000 Result: 53500000 } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:33:29.890", "Id": "19473", "Score": "0", "body": "Do you have max_bounds for either a or b? That is other than max_int?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T16:02:47.593", "Id": "19481", "Score": "0", "body": "@blufox, no other bounds than the values cant be < 0. both of the values wont exceed 1000000, im sure about that, if that matters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T16:18:34.220", "Id": "19483", "Score": "0", "body": "I was wondering if you could use some thing like (a << 20) + b > (a' << 20) + b' as the comparison perhaps?." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T16:51:29.453", "Id": "19485", "Score": "0", "body": "@blufox, no no no... this must work for any datatype. basically im just finding better if-structures there. if possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T17:02:25.663", "Id": "19486", "Score": "0", "body": "I was thinking, if the `a` was float value, should i compare equality? I heard that same value in float can be represented in many ways or something like that, so equality wont always work..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T20:28:03.353", "Id": "19566", "Score": "0", "body": "This is the wrong site for this type of question. Best to ask on stackoverflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T10:28:02.260", "Id": "19582", "Score": "0", "body": "@LokiAstari, wait... what? im confused. what exactly is this site for...? i read the FAQ and i chose this site according to that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T10:43:37.963", "Id": "19584", "Score": "0", "body": "@Rookie: This site is for review of working code. What you are asking for fits better on stackoverflow. and because of the higher traffic there you are likely to get better answers. The best solution is use [`std::max_element()`](http://www.sgi.com/tech/stl/max_element.html) which would have come up very quickly over there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T11:00:47.740", "Id": "19587", "Score": "0", "body": "@LokiAstari, my code works. By the way, max_element() doesnt do what i intend to do; i need to find index, not the values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T11:29:53.383", "Id": "19590", "Score": "0", "body": "@Rookie: That is what max_element() does. It returns you an iterator (points at the element). Converting this to an actual index is trivial (see [`std::distance()`](http://www.sgi.com/tech/stl/distance.html)). But if you need that you have other parts of your design that need to be worked on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T11:39:21.670", "Id": "19592", "Score": "0", "body": "@Rookie: PS. You need to add to your question: 1) You are actually looking for the index. 2) The types of values (in C++ the type is the **most** important thing in a question and you are missing this. We do not know the type of `values` or the types held by `values`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T11:46:31.740", "Id": "19596", "Score": "0", "body": "@Rookie: Code. Add code. English description of what you did is not enough. If you could show `compilable code`. Then we can start dissecting it for real." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T12:38:07.760", "Id": "19603", "Score": "0", "body": "When I run these I get exactly the same time (which is what I expect as the optimizer will turn them into the same code). What you are probably experiencing is cash warm up. The first algorithm warms up the cache which then helps the second algorithm. Also with optimizations turned on both of these take less that a second so that is not really much of a test. Optimizations off they take 10S." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T12:40:03.530", "Id": "19604", "Score": "0", "body": "Added a version that uses std::max_element to you test. Please run again. Probably 10,000 iterations. May want to increase the array size to something big" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T12:55:24.150", "Id": "19605", "Score": "0", "body": "PS. I had to add a line to print `ids` or it was optimized out. So I printed the `ids after each loop. But in all my tests the difference between the three methods is insignificant (at less than 0.1%)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T13:37:55.330", "Id": "19608", "Score": "0", "body": "@LokiAstari, it seems like that my compiler options were weird. i had \"only inline\" for inlining functions... now i set to \"any suitable\" (Q:will it also inline the functions with inline command in them?) and yours is actually faster o_O ! but still, i cant use your code because its depending on the size of the struct being same as the tested variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T16:54:39.773", "Id": "19618", "Score": "0", "body": "@Rookie: Modern compilers (if not over-ridden by their user) will completely ignore the keyword inline (in term of in-lining). Their internal algorithms for choosing what to inline are much more sophisticated than what a normal program would use. As a result the compiler is much more accomplished at correctly deciding what to inline than a human. Note: Let it decide." } ]
[ { "body": "<p>What you are doing is just normal search for a max pair using <a href=\"http://en.wikipedia.org/wiki/Lexicographical_order\" rel=\"nofollow\">lexicographical</a> ordering.</p>\n\n<p>The issue with your code is that, it is linear O(n). While for a single use, this might be the best way, if you have to do it repeatedly, it would be better to build a priority queue [O(n)] with the comparison operator defined as pair compare, and then extract the top. (Even better if you can build the priority queue as you receive the elements.)</p>\n\n<p>The pair comparison is derived directly from the definition </p>\n\n<pre><code>(a,b) ≤ (a′,b′) if and only if a &lt; a′ or (a = a′ and b ≤ b′).\n</code></pre>\n\n<p>However you have mentioned the constraint that the loop shouldn't be changed. Is there a reason for that?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T16:12:50.263", "Id": "19482", "Score": "0", "body": "The loop cannot be changed because i dont want to add any more complexity there, keeping it simple; i can later optimize it myself. I will probably optimize this by quadtrees (these objects are in 2d world); i would still have to loop linearly, but that doesnt hurt much on performance." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:41:20.473", "Id": "12167", "ParentId": "12166", "Score": "1" } }, { "body": "<pre><code>if(values[i].a &gt; max_a || (values[i].a == max_a &amp;&amp; values[i].b &gt; max_b))\n{\n max_a = values[i].a;\n max_b = values[i].b;\n found_id = i;\n}\n</code></pre>\n\n<p>or...eliminating max_a and max_b</p>\n\n<pre><code>if(values[i].a &gt; values[found_id].a || (values[i].a == values[found_id].a &amp;&amp; values[i].b &gt; values[found_id].b))\n {\n found_id = i;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T10:41:08.920", "Id": "19583", "Score": "0", "body": "Your latter code isnt right. How could it, when it doesnt remember the previous value? (i tested it and it doenst work). Your first code works so far, im not sure why though.... need to think more." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T10:57:27.993", "Id": "19585", "Score": "0", "body": "I'm surprised, your first version is 30% faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T02:40:24.547", "Id": "19628", "Score": "0", "body": "second one doesn't try to remember it just uses the index location of the highest value and compares new values against that, never tested it though" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T02:47:50.363", "Id": "12208", "ParentId": "12166", "Score": "0" } }, { "body": "<h3>Real SOlution</h3>\n\n<pre><code>typedef std::pair&lt;int, float&gt; Value;\ntypedef std::vector&lt;Value&gt; Values;\n\nValues values;\n// Initialize all values;\n\n// Then.\nValues::const_iterator find = std::max_element(values.begin(), values.end());\n\n// Want the raw index number for some strange reason.\nint index = std::distance(values.begin(), find);\n\n// Note if you insist on using arrays rather than vectors then the C++11 version\n// works with vectors and arrays exactly the same way:\nValue* find = std::max_element(std::begin(values), std::end(values));\n\n// But if you insist on using arrays but are stuck with C++03\nValue* find = std::max_element(&amp;values[0], &amp;values[size]);\n</code></pre>\n\n<h3>Review of code</h3>\n\n<p>Neither of this is a minimum value.</p>\n\n<pre><code>int max_a = -1;\nfloat max_b = -1;\n</code></pre>\n\n<p>So if your data happens to be all negative it will fail. </p>\n\n<p>Unless there is some space concerns I do not see the point in using float. Prefer double the extra precision is usually worth it.</p>\n\n<p>Why did you use two variables to hold the max. This is sort of an indication that you are looking for the max in each column separately. This is not the case so you should have a max value object.</p>\n\n<pre><code>Value max = values[0]; // Initialize with first element.\n</code></pre>\n\n<p>OK. This is always going to be a linear algorithm O(n) as the data is not sorted. But prefer pre-increment <code>++i</code> over post increment. Technically there will be no difference for POD types (like int) but it is a good habit to get into for when you start using other types to iterate across the array.</p>\n\n<p>Personally I hate such short variables names. But I know other like it for looping. The problem is that if the loop gets to any non trivial size the looking for all occurrences of <code>i</code> becomes a pain the arse. It is much easier to spot a longer variable name.</p>\n\n<pre><code>for(int i = 0; i &lt; total_values; i++){\n</code></pre>\n\n<p>All this is way to complex. </p>\n\n<pre><code> if(values[i].a &gt; max_a){\n max_a = values[i].a;\n max_b = -1; // reset\n }\n if(values[i].a == max_a){\n if(values[i].b &gt; max_b){\n max_b = values[i].b;\n found_id = i;\n }\n }\n</code></pre>\n\n<ul>\n<li>You don't need a <code>found_id</code>. If the container is empty then you will not find a max.</li>\n<li>Otherwise use the first element to initialize the max.</li>\n<li>The loop over the other elements (ie starting at 1)</li>\n<li>See below on how to do the test in one condition.</li>\n</ul>\n\n<p>Algorithm should look like this:</p>\n\n<pre><code> Value max = values[0];\n for(int loop = 1; loop &lt; size; ++loop)\n {\n max = std::max(max, values[loop]);\n }\n // Modified based on comments. To get index use:\n Value max = values[0];\n int index = 0;\n for(int loop = 1; loop &lt; size; ++loop)\n {\n if (max &lt; values[loop])\n {\n index = loop; \n max = values[loop];\n }\n }\n</code></pre>\n\n<p>Now all you need to do is define the relationship between elements. By default <code>std::max()</code> will use the <code>operator&lt;</code> to do comparisons but you can define your own comparison operator if you want a non standard way of determining max.</p>\n\n<p>If The type of <code>Value</code> (which holds your int/float) pair is actualy typedefed to <code>std::pair&lt;int, float&gt;</code> then this is the default behavior.</p>\n\n<pre><code> // It would be equivalent to this\n bool operator&lt;(Value const &amp; lhs, Value const&amp; rhs)\n {\n return (lhs.first &lt; rhs.first)\n || ((lhs.first == rhs.first) &amp;&amp; (lhs.second &lt; rhs.second));\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T10:59:32.627", "Id": "19586", "Score": "0", "body": "Will this work? I need to find the array index, not the array values. Interesting solution though!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T11:16:02.777", "Id": "19589", "Score": "0", "body": "@Rookie: It already does that. std::max_element returns an iterator the max element. Which can be the index if you are using raw arrays (which is bad idea use a vector)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T11:38:42.263", "Id": "19591", "Score": "0", "body": "Unfortunately your code is twice as slow as the code made by Keith. I didnt test your distance() solution yet, though, but im not sure will it even work; I should also mention that i cant use std::pair here, because my struct is larger than just a pair, and the code should work with any struct. PS. i do use vectors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T11:42:04.087", "Id": "19593", "Score": "0", "body": "@Rookie: If you think my code is twice as slow as anything then **you** are doing something wrong. The STL algorithms are very efficient. So add to your question what you wrote and how you tested it. so we can point out your mistakes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T11:43:12.837", "Id": "19594", "Score": "0", "body": "@Rookie: If you use vectors then that should be part of the code you have in your question!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T11:43:58.840", "Id": "19595", "Score": "0", "body": "@Rookie: You have two values. What is this new thing about a structure. You are obviously missing much more from your question that you need to add." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T12:05:37.927", "Id": "19599", "Score": "0", "body": "I added my compileable code (all you need to add is the random() function, i can provide that too if you need, though)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T14:01:09.590", "Id": "19612", "Score": "0", "body": "Now when i set the optimizations correctly, I'm confused, why is your code faster? Even when i increase the struct size to 200 bytes, its still faster! Why? It's basically the same code as Keith's is, except your comparisons are inverted, could that be the reason? BTW, why did you invert your comparison operators, and why does it even work correctly, im not sure why it works..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T16:59:06.617", "Id": "19619", "Score": "0", "body": "@Rookie: My algorithm should on average by no faster than Keith's. What you are probably seeing are differences caused by other parts of the hardware. Cache warm up affects. memory fetch stalls caused because their are other programs running on the computer. etc. That is why you should run the application on significant large data sets and over sufficiently large number of times to try and average out these affects. Update the size and loop count so they run for like 500 seconds. I bet you will see that they flip flop on which is better (also the difference will be less than 1%)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T19:44:56.753", "Id": "19622", "Score": "0", "body": "I've tried everything, i changed the order of the code execution, and i ran it multiple times, it still is faster. i dont have any programs running that would explain the speed differences, and even if i did, it would mean i would be using 99.99% of 4 CPU cores to have such an effect you described, but im not... can you explain why is it faster to copy 200 bytes struct than 2 variables...?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T19:58:01.567", "Id": "19623", "Score": "0", "body": "@Rookie: Have you **seeded** the random number generator to make sure you get different numbers each time (the default action will to produce the same set of numbers each time you run the application). The actual shape of the data could be affecting the results. But if you want an opinion you need to post code that I can read. English description of code is worse than useless as English is in-precise so we both make assumptions that will be different." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T20:00:42.063", "Id": "19624", "Score": "0", "body": "PS. You are running a very complex OS on the machine. Expecting that to have no affect on the timmings is neive. The OS is always using memory and the bus and all sorts of things in the back ground. The effect of the OS on causing cache misses can affect timing results drastically thus is why you need to run it over several minutes to make sure the affects on both timings average out to the same." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T20:48:02.837", "Id": "19626", "Score": "0", "body": "I already posted the code as far as i know. I used the same random seed for each time of course, why would i change that, i also tested with different random ranges, they did affect the performance, so the data was working correctly. caching? i dont know, why it would take many seconds if it \"cached\" the results, and why it fails on the other code right after it? I tested it now 100 times (ran for 10mins), and every each time yours was faster. That cant be a coincidence of my OS doing always something at that precise moments 100 times in row?" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T10:51:34.663", "Id": "12213", "ParentId": "12166", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "17", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:28:00.790", "Id": "12166", "Score": "3", "Tags": [ "c++", "search", "sorting" ], "Title": "Finding the highest values a and b from an array" }
12166
<p>The Enumeration in question is based on <code>int</code>, so the following Extension returns a <code>Dictionary&lt;int, string&gt;</code> of the Enum's Value and Description.</p> <p>Is there a cleaner way of implementing this?</p> <pre><code>public enum TeamDepartments { [Description("Geschäftsleitung")] Management = 1, [Description("Verkaufsleitung")] Sales = 2 } public static class UtilityExtensions { public static Dictionary&lt;int, string&gt; ToDictionary(this Type EnumerationType) { Dictionary&lt;int, string&gt; RetVal = new Dictionary&lt;int,string&gt;(); var AllItems = Enum.GetValues(EnumerationType); foreach (var CurrentItem in AllItems) { DescriptionAttribute[] DescAttribute = (DescriptionAttribute[])EnumerationType.GetField(CurrentItem.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false); string Description = DescAttribute.Length &gt; 0 ? DescAttribute[0].Description : CurrentItem.ToString(); RetVal.Add((int)CurrentItem, Description); } return RetVal; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T19:40:24.883", "Id": "19563", "Score": "0", "body": "The method name should be `GetDescription`. Also, the dictionary is unnatural because you lose some of the type-safety, plus you are not wasting THAT much time if you call `GetDescription` every time. If you do want to keep the dictionary anyway, then I would at least wrap access to it into a method with a tighter signature." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T04:49:28.793", "Id": "19572", "Score": "0", "body": "The larger context for this Extension is binding an Enum to an ASP.net dropdown, which now occurs to me can be refactored into a single method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T15:24:35.040", "Id": "19615", "Score": "0", "body": "I have often dealt with a situation where I need to display something in a combo box, something that does not change very often, something that does not have too many possible values, but also something that comes from a database. My situation is very similar to: http://stackoverflow.com/questions/5886394/how-to-keep-a-c-sharp-enum-in-sync-with-a-table-in-database At the end of it I decided that it is better to not use Enums, but have a small object that overrides a `ToString` for display purposes but also contains a bunch of other useful info." } ]
[ { "body": "<p>You should separate the code returning the attributes of a type into another extension method. It would probably prove useful later on, anyway. Perhaps return an IEnumerable&lt;> of attributes, and process it into a dictionary using a LINQ statement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T18:13:41.923", "Id": "12174", "ParentId": "12173", "Score": "0" } }, { "body": "<p>I have this class in my code which is very similar to what you are looking for:</p>\n\n<pre><code>public static class EnumHelper {\n public static string GetRealName(this Enum value) {\n if (value == null) {\n throw new ArgumentException(\"value\");\n }\n\n string name = value.ToString();\n var fieldInfo = value.GetType().GetField(name);\n if (fieldInfo == null) return \"\";\n var attributes = (RealNameAttribute[])fieldInfo.GetCustomAttributes(typeof(RealNameAttribute), false);\n\n if (attributes.Length &gt; 0) {\n name = attributes[0].Name;\n }\n\n return name;\n }\n public static bool IsIgnored(this Enum value) {\n if (value == null) {\n throw new ArgumentException(\"value\");\n }\n\n string name = value.ToString();\n var fieldInfo = value.GetType().GetField(name);\n\n return fieldInfo == null || fieldInfo.IsDefined(typeof(IgnoreAttribute), true);\n }\n\n public static Dictionary&lt;int, string&gt; ToDictionary(this Type enumType) { \n return Enum.GetValues(enumType)\n .Cast&lt;object&gt;()\n .Where(f =&gt; !((Enum)f).IsIgnored())\n .ToDictionary(k =&gt; (int)k, v =&gt; ((Enum)v).GetRealName()); \n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T14:00:41.797", "Id": "19532", "Score": "0", "body": "I adjusted your code to fit my needs and I'll update the question with it -> answer accepted." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T19:01:48.190", "Id": "12178", "ParentId": "12173", "Score": "1" } } ]
{ "AcceptedAnswerId": "12178", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T17:33:35.163", "Id": "12173", "Score": "2", "Tags": [ "c#", "reflection", "enum" ], "Title": "Casting an Enumeration with Descriptions into a Dictionary" }
12173
<p>I have an extremely simple self-playing Tetris game which I coded up and I am looking to see how it could be improved. It would also be a learning curve for me to see how those much better than I am would go about improving the code.</p> <pre><code>############################################################################### ## an implementation of a ***very*** basic Tetris game in Python using Pygame ############################################################################### '''rotate --- r pause ---- p direction buttons for movement''' import sys import copy import pygame import random size = width, height = 200, 400 sqrsize, pen_size = 20, 1 occupied_squares = [] top_of_screen = (0, 0) color = {'white':(255, 255, 255)} top_x, top_y = top_of_screen[0], top_of_screen[1] pygame.init() screen = pygame.display.set_mode(size) background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((color['white'])) screen.blit(background, top_of_screen) pygame.display.flip() ################################################################################ #constructors and selectors for a tetrominoe shape ################################################################################ def make_tetrominoe(block1, block2, block3, block4, name): """Inputs&lt;- 4 constituent blocks that make up a tetrominoe shape and name of tetrominoe shape. This returns a tetrominoe shape.""" return [block1, block2, block3, block4, name] def get_tetname(tetrominoe): """returns the name of a tetrominoe shape""" return tetrominoe[4] def get_blocks(tetrominoe): """returns a list of blocks that make up a tetrominoe piece""" return tetrominoe[:4] def get_refblock(tetrominoe): """gets reference block.Reference block is one around which other blocks are drawn""" return tetrominoe[3] def block_points(tetronimoe): """gets the coordinates of the individual blocks that make up a tetrominoe piece""" blocks = get_blocks(tetronimoe) return [get_point(block) for block in blocks] ############################################################################### #constructors and selectors for a tetrominoe shape block ############################################################################### def make_block(point, breadth, length): """This returns a block. A block is one of the constituent parts of a tetrominoe shape and is made up of a start coordinate,the breadth of the block and the lenght""" return [point, breadth, length] def get_point(a_block): """returns the coordinate start point of block""" return a_block[0] def block_width(a_block): """Returns the width of a block""" return a_block[1] def block_height(a_block): """Returns the height of a block""" return a_block[2] ############################################################################# #constructors and selectors for coordinate points ############################################################################## def make_point(x_coord, y_coord, colour): """Input&lt;-coordinate of a point, color returns a point object with the coordinates of the point and color""" return [x_coord, y_coord, colour] def point_x(a_point): """Returns the xcoordinate of a point structure""" return a_point[0] def point_y(a_point): """Returns the ycoordinate of a point structure""" return a_point[1] def point_color(a_point): """Returns the color of a point structure""" return a_point[2] ############################################################################### ############################################################################### def delta_point(a_block, delta_x, delta_y): """input&lt;- a block(constituent of a tetrominoe shape), integer, integer output-&gt;a block function which takes a block and increments its POINT""" point = get_point(a_block) return (make_block(make_point(point_x(point)+delta_x, point_y(point)+delta_y, point_color(point)), block_width(a_block), block_height(a_block))) ############################################################################### ## game controller ############################################################################### def tetris(): """Sets up the whole game play and handles event handling""" mov_delay = 150 events = {276: 'left', 275: 'right', 112: 'pause'} while True: move_dir = 'down' #default move direction game = 'playing' #default game state play:- is game paused or playing? tet_shape = random_shape() if legal(tet_shape): draw_shape(tet_shape) else: break #game over dets = find_column(get_tetname(tet_shape)) sel_col = dets[0] rotate_count = dets[-1] mov_cnt = (sel_col - 80) / sqrsize if mov_cnt &lt; 0: move_dir = 'left' elif mov_cnt &gt; 0: move_dir = 'right' elif mov_cnt == 0: move_dir = 'down' mov_cnt = abs(mov_cnt) while rotate_count &gt; 0: new_tet_shape = rotate(tet_shape) if legal(new_tet_shape): prev_tet, tet_shape = tet_shape, new_tet_shape draw_and_clear(tet_shape, prev_tet, mov_delay) rotate_count = rotate_count - 1 while mov_cnt &gt; 0: new_tet_shape = move(tet_shape, move_dir) if legal(new_tet_shape): prev_tet, tet_shape = tet_shape, new_tet_shape draw_and_clear(tet_shape, prev_tet, mov_delay) mov_cnt = mov_cnt - 1 while True: if game == 'paused': for event in pygame.event.get((pygame.KEYDOWN, pygame.KEYUP)): if event.key == pygame.K_p: game, move_dir = 'playing', 'down' else: for event in pygame.event.get((pygame.KEYDOWN, pygame.KEYUP)): if event.type == pygame.KEYDOWN: if event.key == pygame.K_p: game, move_dir = 'paused', 'pause' break elif event.type == pygame.KEYUP: mov_delay, move_dir = mov_delay, 'down' move_dir = 'down' new_tet_shape = move(tet_shape, move_dir) if legal(new_tet_shape): prev_tet, tet_shape = tet_shape, new_tet_shape draw_and_clear(tet_shape, prev_tet, mov_delay) else: #If shape didn't move and direction of movement is down #then shape has come to rest so we can check for a full row #which we delete before exiting loop and generating a new #tetrominoe. if direction for movement is sideways #and block did not move it should be moved down rather if move_dir == 'down': occupied_squares.extend(block_points(tet_shape)) for row_no in range(height, -sqrsize, -sqrsize): while row_filled(row_no): delete_row(row_no) background.fill(color['white']) for point in occupied_squares: draw_block(point) break else: draw_shape(tet_shape) pygame.time.delay(mov_delay) ########################################################################### ########################################################################### def draw_and_clear(tetrominoe, prev_tet, delay): """input&lt;-two tetrominoe shapes clear the previously drawn tetrominoe first and then draw a new tetrominoe""" for point in block_points(prev_tet): background.fill((color['white']), (point_x(point), point_y(point), sqrsize, sqrsize)) screen.blit(background, top_of_screen) pygame.display.update() draw_shape(tetrominoe) pygame.time.delay(delay) ############################################################################ ############################################################################ def draw_shape(tetrominoe): """input&lt;-tetriminoe shape This draws a tetrominoe shape to game board""" for point in block_points(tetrominoe): draw_block(point) screen.blit(background, top_of_screen) pygame.display.update() ############################################################################# ############################################################################# def draw_block(a_point): """draws a basic shape to screen""" pygame.draw.rect(background, point_color(a_point), (point_x(a_point), point_y(a_point), sqrsize, sqrsize), 1) ############################################################################ ############################################################################ def row_filled(row_no, board=None): """input&lt;-tetriminoe shape checks if a row on game board is fully occupied by a shape block""" if board: filled_coords = [(point_x(point), point_y(point)) for point in board] for col in range(0, width, sqrsize): if (col, row_no) in filled_coords: continue else: return False return True else: filled_coords = [[point_x(pt), point_y(pt)] for pt in occupied_squares] for col in range(0, width, sqrsize): if [col, row_no] in filled_coords: continue else: return False return True ############################################################################## ############################################################################## def delete_row(row_no): """input&lt;-integer(a row number) output-&gt;list of points removes all squares on a row from the occupied_squares list and then moves all square positions which have y-axis coord less than row_no down board""" global occupied_squares occupied_squares = [point for point in occupied_squares if point_y(point) != row_no] for index in range(len(occupied_squares)): if point_y(occupied_squares[index]) &lt; row_no: occupied_squares[index] = make_point(point_x(occupied_squares[index]), point_y(occupied_squares[index]) + sqrsize, point_color(occupied_squares[index])) ############################################################################## ############################################################################## def legal(tet_shape): """input&lt;-tetrominoe piece output-&gt;bool checks that a tetromone is in a legal portion of the board""" tet_block_points = block_points(tet_shape) filled_coords = [(point_x(pt), point_y(pt)) for pt in occupied_squares] for point in tet_block_points: new_x, new_y = point_x(point), point_y(point) if ((new_x, new_y) in filled_coords or (new_y &gt;= height or (new_x &gt;= width or new_x &lt; top_x))): return False return True ############################################################################## ############################################################################## def move(shape, direction, undo=False): """input&lt;- a tetrominoe shape output&lt;- a terominoe shape function moves a tetrominoe shape by moving all constituent blocks by a fixed amount in a direction given by 'direction' argument""" no_move = 0 directions = {'down':(no_move, sqrsize), 'left':(-sqrsize, no_move), 'right':(sqrsize, no_move), 'pause': (no_move, no_move)} delta_x, delta_y = directions[direction] if undo: delta_x, delta_y = -delta_x, -delta_y new_blocks = [delta_point (block, delta_x, delta_y) for block in get_blocks(shape)] return (make_tetrominoe(new_blocks[0], new_blocks[1], new_blocks[2], new_blocks[3], get_tetname(shape))) ############################################################################## ############################################################################## def tetrominoe_shape(shape, start_x=80, start_y=0): """function returns a random tetrominoe piece""" shapes = {'S': make_tetrominoe(make_block(make_point(start_x + 1*sqrsize, start_y + 2*sqrsize, (0, 0, 0)), sqrsize, sqrsize), make_block(make_point(start_x, start_y, (0, 0, 0)), sqrsize, sqrsize), make_block(make_point(start_x, start_y + 1*sqrsize, (0, 0, 0)), sqrsize, sqrsize), make_block(make_point(start_x + 1*sqrsize, start_y + 1*sqrsize, (0, 0, 0)), sqrsize, sqrsize) , 'S'), 'O': make_tetrominoe(make_block(make_point(start_x + 1*sqrsize, start_y + 1*sqrsize, (200, 200, 200)), sqrsize, sqrsize), make_block(make_point(start_x, start_y, (200, 200, 200)), sqrsize, sqrsize), make_block(make_point(start_x, start_y + 1*sqrsize, (200, 200, 200)), sqrsize, sqrsize), make_block(make_point(start_x + 1*sqrsize, start_y, (200, 200, 200)), sqrsize, sqrsize), 'O'), 'I': make_tetrominoe(make_block(make_point(start_x, start_y + 3*sqrsize, (0, 255, 0)), sqrsize, sqrsize), make_block(make_point(start_x, start_y, (0, 255, 0)), sqrsize, sqrsize), make_block(make_point(start_x, start_y + 2*sqrsize, (0, 255, 0)), sqrsize, sqrsize), make_block(make_point(start_x, start_y + 1*sqrsize, (0, 255, 0)), sqrsize, sqrsize), 'I'), 'L':make_tetrominoe(make_block(make_point(start_x + 1*sqrsize, start_y + 2*sqrsize, (0, 0, 255)), sqrsize, sqrsize), make_block(make_point(start_x, start_y, (0, 0, 255)), sqrsize, sqrsize), make_block(make_point(start_x, start_y + 2*sqrsize, (0, 0, 255)), sqrsize, sqrsize), make_block(make_point(start_x, start_y + 1*sqrsize, (0, 0, 255)), sqrsize, sqrsize), 'L'), 'T':make_tetrominoe(make_block(make_point(start_x + 1*sqrsize, start_y + 1*sqrsize, (255, 0, 0)), sqrsize, sqrsize), make_block(make_point(start_x, start_y, (255, 0, 0)), sqrsize, sqrsize), make_block(make_point(start_x - 1*sqrsize, start_y + 1*sqrsize, (255, 0, 0)), sqrsize, sqrsize), make_block(make_point(start_x, start_y + 1*sqrsize, (255, 0, 0)), sqrsize, sqrsize), 'T') } return shapes[shape] ##### ##### def random_shape(start_x=80, start_y=0): """return a random tetrominoe shape""" tets = ['S', 'O', 'I', 'L', 'T'] return tetrominoe_shape(tets[random.randint(0, 4)], start_x, start_y) ############################################################################## ############################################################################## def rotate(tetrominoe): """input&lt;- tetrominoe shape ouput-&gt; tetrominoe shape rotates a tetrominoe shape if possible about a reference block.""" #global occupied_squares if get_tetname(tetrominoe) == 'O': return tetrominoe else: ref_point = get_point(get_refblock(tetrominoe)) x_coord = point_x(ref_point) y_coord = point_y(ref_point) tetblock_coords = block_points(tetrominoe) new_tet = make_tetrominoe(make_block(make_point(x_coord + y_coord-point_y(tetblock_coords[0]), y_coord - (x_coord - point_x(tetblock_coords[0])), point_color(ref_point)), sqrsize, sqrsize, ), make_block(make_point(x_coord + y_coord - point_y(tetblock_coords[1]), y_coord - (x_coord - point_x(tetblock_coords[1])), point_color(ref_point)), sqrsize, sqrsize), make_block(make_point(x_coord + y_coord - point_y(tetblock_coords[2]), y_coord - (x_coord - point_x(tetblock_coords[2])), point_color(ref_point)), sqrsize, sqrsize), make_block(make_point(x_coord, y_coord, point_color(ref_point)), sqrsize, sqrsize), get_tetname(tetrominoe)) #if legal(new_tet): return new_tet #else: # return tetrominoe #### #### def drop_shape(shape): """drop a shape into postion on a column""" new_shape = move(shape, 'down') prev_shape, new_shape = shape, new_shape while legal(new_shape): prev_shape, new_shape = new_shape, move(new_shape, 'down') return prev_shape #### #### def bubble_count(shape): """returns number of new empty spots generated when a shape is placed at a legal point""" count = 0 points = [(point_x(pt), point_y(pt)) for pt in block_points(shape)] board = [(point_x(pt), point_y(pt)) for pt in occupied_squares] for pt in points: for i in range(point_y(pt) + sqrsize, height, sqrsize): if (pt[0], i) in board or (pt[0], i) in points: break else: count += 1 return count #### ### def shape_lowest_row(shape): """return the lowest row of a shape""" points = [(point_x(pt), point_y(pt)) for pt in block_points(shape)] points = sorted(points, key=lambda point: point[1], reverse=True) return points[0] ##### ##### def row_filln_column(shape): """return a list of columns, rows filled tuple for each column on the board if there are n columns for which a shape dropped in column fills a row""" rows_filled = [] shape_rotates = {'S':2, 'I':1, 'O':0, 'L':3, 'T':3} rotate_count = shape_rotates[shape] curr_cnt = 0 while True: for col in range(0, width, sqrsize): board = copy.deepcopy(occupied_squares) tet_shape = tetrominoe_shape(shape, start_x=col, start_y=0) cnt = curr_cnt while cnt &gt; 0: tet_shape = rotate(tet_shape) cnt -= 1 if not legal(tet_shape): # check shape is in board sideways continue tet_shape = drop_shape(tet_shape) board.extend(block_points(tet_shape)) rows = 0 for row in range(height, 0, -sqrsize): if row_filled(row, board=board): rows += 1 if rows &gt; 0: rows_filled.append((col, rows, curr_cnt)) tet_shape = rotate(tet_shape) if rotate_count == curr_cnt: break curr_cnt += 1 if rows_filled: return rows_filled return None #### #### def next_best_columns(shape): """return list of columns which a shape can go into if the shape cannot fill any rows""" next_best = [] shape_rotates = {'S':2, 'I':1, 'O':0, 'L':3, 'T':3} rotate_count = shape_rotates[shape] curr_cnt = 0 while True: for col in range(0, width, sqrsize): board = copy.deepcopy(occupied_squares) tet_shape = tetrominoe_shape(shape, start_x=col, start_y=0) cnt = curr_cnt while cnt &gt; 0: tet_shape = rotate(tet_shape) cnt -= 1 if not legal(tet_shape): continue tet_shape = drop_shape(tet_shape) board.extend(block_points(tet_shape)) bubble_cnt = bubble_count(tet_shape) next_best.append((col, bubble_cnt, shape_lowest_row(tet_shape)[1], curr_cnt)) #print col, bubble_cnt if rotate_count == curr_cnt: break curr_cnt += 1 return next_best ##### ##### def find_column(shape): """find column of best fit to drop down a tetrominoe shape from""" # search for if any rows can be filled up by shape rows_filled = row_filln_column(shape) if not rows_filled: next_best = next_best_columns(shape) next_best = sorted(next_best, key=lambda col: col[2], reverse=True) cols = sorted(next_best, key=lambda col: col[1]) return cols[0] rows_filled = sorted(rows_filled, key=lambda row_filled: row_filled[1]) return rows_filled[-1] #col with most rows filled if __name__ == '__main__': tetris() </code></pre>
[]
[ { "body": "<p>A few general comments:</p>\n\n<ul>\n<li><p>Python constants should be capitals, for e.g width, height etc should be capitalized in your code since they are constants (declared at the beginning).</p></li>\n<li><p>The places where you have indicated \"constructors and selectors\" probably indicate that they aught to be in a separate class.</p></li>\n<li><p>As a general thumb rule, more than one loop statement in a method is probably indicating that the method can be refactored. The method \"tetris\" is ripe for refactoring.</p></li>\n<li><p>Same way, I would say more than 3 levels of indentation is probably a <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">code-smell</a>.</p></li>\n<li><p>The method \"tetrominoe_shape\" may be refactored rather heavily. The difference between each shapes seems to be just one or two numbers. They may be factored out.</p></li>\n<li><p>Try to factor out the objects for block,shape,point, controller etc, and your code will become much more tractable.</p></li>\n<li><p>Also add a bit of information as to what each method does. Right now, it is rather hard to figure out what each method does.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T04:54:35.977", "Id": "12209", "ParentId": "12175", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T18:15:23.927", "Id": "12175", "Score": "13", "Tags": [ "python", "game", "pygame", "tetris" ], "Title": "Self-playing Tetris game" }
12175
<p>I have a Windows application and want to self-host a WCF in it. This <a href="http://msdn.microsoft.com/en-us/library/ms731758.aspx" rel="nofollow">MSDN article</a> walks you through how to self-host WCF in a console. <a href="http://www.codeproject.com/Articles/18789/A-Quick-and-Dirty-WCF-Service-and-Client-Using-WCF" rel="nofollow">Jason Henderson's article</a> demonstrates how to call the service. But the problem is, I don't want to host my service in another Windows process. I want to host it in my client application.</p> <p>Here is my workaround:</p> <ol> <li><kbd>Ctrl</kbd><kbd>F5</kbd> to run the service</li> <li>Add service reference to my client application</li> </ol> <p>Then I can start my service in my client like this:</p> <pre><code>static void Main() { ServiceHost host = new ServiceHost(typeof(MyService)); host.Open(); Application.Run(new Form1()); host.Close(); } </code></pre> <p>It works, but I wonder if there are any simpler ways to do this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T05:59:25.737", "Id": "19516", "Score": "1", "body": "That looks pretty simple to me... what exactly do you expect us to _review_?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T14:01:21.033", "Id": "19533", "Score": "0", "body": "i'm looking for a better solution, not my ugly workaround :)" } ]
[ { "body": "<p>You can also start host in another thread:</p>\n\n<pre><code>Task.Factory.StartNew(() =&gt;\n {\n ServiceHost host = new ServiceHost(typeof(MyService));\n host.Open();\n };\n</code></pre>\n\n<p>(or using classic Thread and ThreadStart).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-27T06:02:05.430", "Id": "179828", "Score": "1", "body": "You should consider marking this Task with the `TaskCreationOptions.LongRunning` option" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T07:52:58.313", "Id": "12184", "ParentId": "12180", "Score": "3" } } ]
{ "AcceptedAnswerId": "12184", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T03:45:10.963", "Id": "12180", "Score": "0", "Tags": [ "c#", "winforms", "wcf" ], "Title": "Self-hosting WCF in Windows Forms without another Windows process" }
12180
<p>I have a code snippet below and because of habit from other programming languages I wanted to use a <code>do-while</code> loop instead. But Python offers only the construct which I show as a second code snippet instead of a <code>do-while*</code>loop. What is the best pythonic way to code this?</p> <pre><code>ch = getch() while ch != "q": do_something() ch = getch() while True: ch = getch() do_something() if ch == "q": break </code></pre>
[]
[ { "body": "<p>I found a way to do this with <a href=\"http://docs.python.org/tutorial/datastructures.html\" rel=\"nofollow\">Python List Comprehension</a> (chapter 5.1.4) as follows:</p>\n\n<p>(Notice that I used <code>sys.stdin.read(1)</code> instead of <code>getch()</code>)</p>\n\n<pre><code>&gt;&gt;&gt; import sys\n&gt;&gt;&gt; while [x for x in sys.stdin.read(1) if x != 'q']:\n... print x # substitute this with your do_something()\n... \n\n\na\na\n\n\nb\nb\n\n\nc\nc\n\n\nq\n&gt;&gt;&gt;\n</code></pre>\n\n<p>You could also use, which is a bit uglier to me:</p>\n\n<pre><code>&gt;&gt;&gt; while [] != [x for x in sys.stdin.read(1) if x != 'q']:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T09:13:12.593", "Id": "19632", "Score": "0", "body": "Both of these are neat hacks, but the fact that 'x' is visible outside the list comprehension is arguably a wart in Python. I think that both alternatives in the original question express the intent better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T11:15:00.387", "Id": "19634", "Score": "0", "body": "@akaihola, ya when I was playing around with it, I was surprised I could get at 'x'. I'll try to think of another alternative that returns and uses a list instead, thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T09:28:43.483", "Id": "12187", "ParentId": "12183", "Score": "4" } }, { "body": "<p>Another way would be using a generator expression. This has the effect of separating the 'control logic' and the 'action logic' (and are extremely useful!).</p>\n\n<pre><code>def getchar_until_quit():\n while True:\n ch = getch()\n if ch != \"q\": \n yield ch\n else:\n raise StopIteration\n\nfor ch in getchar_until_quit():\n do_something()\ndo_something() # to process the 'q' at the end\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T09:16:11.903", "Id": "19633", "Score": "0", "body": "I don't think it's necessary to raise a StopIteration explicitly. Maybe just break on \"q\", else yield." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T09:37:37.723", "Id": "12189", "ParentId": "12183", "Score": "6" } } ]
{ "AcceptedAnswerId": "12187", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-05-31T07:48:36.970", "Id": "12183", "Score": "5", "Tags": [ "python" ], "Title": "Reading a controll character in a loop in Python" }
12183
<p>I am creating a skeleton application to demonstrate use of the Strategy design pattern and inversion of control inside a Strategy.</p> <p>The application is the backend of a simple board game, which also has the capability to save and load the board. Since we can have different types of data stores for saving, I have used an interface PersistenceStrategy and concrete implementations of it like the FilePersistenceStrategy.</p> <p>I have listed the code below. However, I am stuck in one place. Inside the FilePersistenceStrategy class, the save() as well as load() methods need to communicate with a file. I do not want these methods to create a file handle (Reader/Writer) themselves, since this will be bad for testability.</p> <p>I know there are several ways for these methods to get hold of FileReader and FileWriter objects - like getting them from a factory, or getting the FQN from a properties file and instantiating them using reflection. </p> <p>The most common method of solving this problem - Dependency Injection, cannot be used here because the load() and save() methods come from an interface and we cannot add Strategy specific parameters to the interface.</p> <p>How would you solve this problem, and what in your opinion are the pros and cons of different approaches ?</p> <p>Code follows:</p> <p><strong>Board.java</strong></p> <pre><code>package com.diycomputerscience.example.sanddi; public class Board { private PersistenceStrategy persistenceStrategy; private BoardState state; public Board(PersistenceStrategy persistenceStrategy) { this.persistenceStrategy = persistenceStrategy; } //various methods of playing the board game public void load() throws PersistenceException { this.state = this.persistenceStrategy.load(); } public void save() throws PersistenceException { this.persistenceStrategy.save(this.state); } } </code></pre> <p><strong>BoardState.java</strong></p> <pre><code>package com.diycomputerscience.example.sanddi; public class BoardState { } </code></pre> <p><strong>PersistenceStrategy</strong></p> <pre><code>package com.diycomputerscience.example.sanddi; public interface PersistenceStrategy { public void save(BoardState state) throws PersistenceException; public BoardState load() throws PersistenceException; } </code></pre> <p><strong>FilePersistenceStrategy.java</strong></p> <pre><code>package com.diycomputerscience.example.sanddi; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; public class FilePersistenceStrategy implements PersistenceStrategy { @Override public void save(BoardState state) throws PersistenceException { FileWriter writer = getFileWriter(); //logic to save the state if(writer != null) { try { writer.close(); } catch(IOException ioe) { String msg = "Could not close FileWriter"; throw new PersistenceException(msg, ioe); } } } @Override public BoardState load() throws PersistenceException { FileReader reader = getFileReader(); BoardState state = parseFileForBoardState(reader); return state; } private BoardState parseFileForBoardState(FileReader reader) { // TODO Auto-generated method stub return null; } /** * HOW DO I USE INVERSION OF CONTROL HERE FOR BETTER TESTABILITY ? * @return */ private FileReader getFileReader() { // Create a FileReader from a well known file name... // perhaps a hardcoded name or read name from a config file return null; } /** * HOW DO I USE INVERSION OF CONTROL HERE FOR BETTER TESTABILITY ? * @return */ private FileWriter getFileWriter() { // Create a FileWriter from a well known file name... // perhaps a hardcoded name or read name from a config file return null; } } </code></pre> <p><strong>PersistenceException.java</strong></p> <pre><code>package com.diycomputerscience.example.sanddi; public class PersistenceException extends Exception { //Override all constructors from the superclass public PersistenceException(String msg, Throwable cause) { super(msg, cause); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T11:21:07.873", "Id": "19523", "Score": "0", "body": "Thanks for your question! I'm not sure whether this is on-topic or not. Code should already be working according to the faq." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T11:29:22.980", "Id": "19524", "Score": "0", "body": "@Cygal I see what you mean, but the design is working. The methods which return null, do so only for brevity. I can change them to return actual readers and writers if required." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T13:27:17.087", "Id": "19528", "Score": "1", "body": "I wasn't sure, which is why I didn't vote for a close. Thanks for the clarifications." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T16:13:08.200", "Id": "19538", "Score": "0", "body": "I suppose if you really needed the flexibility, you could inject some sort of `FileLocator` / `FileNamer` / `WriterFactory` or similar strategy. But do you really need that kind of flexibility? You're going to have to stop and test the writes at some point, and I would have expected it to be at the `FilePersistenceStrategy` level (that is, you're mocking `PersistenceStrategy` objects for testing the _rest_ of your code, right?)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T22:19:47.770", "Id": "29531", "Score": "0", "body": "How is the strategy created?" } ]
[ { "body": "<p>For me the question is how the strategy is created. Is it possible to inject the file name during construction of the strategy? That would be the way I would do it.</p>\n\n<p>Else you can create callbacks that are created and injected. When you need the file call this callback and let this decide (eg asking the user).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T22:18:54.997", "Id": "29530", "Score": "0", "body": "I think I agree. Something somewhere must know about the different strategies. Depends on if this something could be altered accordingly" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T19:46:02.013", "Id": "18511", "ParentId": "12190", "Score": "2" } }, { "body": "<p>Inject the file information into the constructor. You are going to end up with something (a factory, an IoC container, etc) that knows which strategy to use; it can also know the file information.</p>\n\n<p>I like to wrap file access in a mockable class too, but that might be a problem that is specific to C#.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-16T03:16:17.630", "Id": "18691", "ParentId": "12190", "Score": "2" } } ]
{ "AcceptedAnswerId": "18511", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T10:44:48.700", "Id": "12190", "Score": "2", "Tags": [ "java", "design-patterns", "unit-testing" ], "Title": "How to use inversion of control within a strategy when using the strategy pattern" }
12190
<p>The idea is to take the common-known (and awfully bad performing) Fibonacci(n) recursive method:</p> <pre><code># recursively computate fibonacci(n) def fib(n) n &lt;= 2 ? 1 : fib(n-2) + fib(n-1) end </code></pre> <p>and to optimize it with some Ruby reflection:</p> <pre><code>require 'benchmark' def fib(n) # if n&lt;= 2 fib(n) = 1 return 1 if n &lt;= 2 # if @fib_n is defined it means that another instance of this method # has already computed it, so I just return its value return instance_variable_get("@fib_#{n}") if instance_variable_get("@fib_#{n}") # else I have to set fib_n and return its value instance_variable_set("@fib_#{n}", ( fib(n-2) + fib(n-1) ) ) end Benchmark.bm(30) do |x| x.report("fibonacci(#{ARGV[0]}) computation time:") {$fib = fib(ARGV[0].to_i)} end puts "fib(#{ARGV[0]}) = #{$fib}" </code></pre> <p>Since the execution time for <code>fib(36)</code> drops from about 4 sec to 0.000234 sec, I guess it's working! But since I'm a Ruby novice (and since this is my first attempt with reflection), I'd still like to have my code peer-reviewed. </p> <ol> <li>Is my choice to use '@fib_n' instance variables correct or there is a better choice?</li> <li>Does anyone know a better Ruby optimization for the <em>recursive</em> computation of Fibonacci members? (I know, the most efficient computation for Fibonacci is the iterative one, but here I'm strictly interested in the recursive one).</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T18:26:42.940", "Id": "19559", "Score": "2", "body": "I would suggest using an array instead of instance variables" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T19:44:08.213", "Id": "19564", "Score": "0", "body": "How and why? How about a comprehensive answer? I'm still waiting for one to accept." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T08:20:08.643", "Id": "19577", "Score": "0", "body": "I gave your suggestion a try but I used... an instance array. See the update: it is 5 times faster, thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-20T03:23:01.900", "Id": "88344", "Score": "0", "body": "Recursion isn't my bottleneck... Check it out: http://stackoverflow.com/questions/23749877/wheres-the-bottleneck-performance-disparities-project-euler-12" } ]
[ { "body": "<p>One possible solution with <code>lambda</code>:</p>\n\n<pre><code>fibp =\n lambda do\n a = [0, 1]\n lambda do |n|\n if n &gt; 1\n a[n] ||= fibp[n - 2] + fibp[n - 1]\n else\n n\n end\n end\n end \\\n .call\n\np fibp[1000]\n</code></pre>\n\n<p>Still prone to stack overflow as any recursive method in Ruby.</p>\n\n<p><strong>UPDATE:</strong> In fact memoizing is not necessary if all you need is just one result:</p>\n\n<pre><code>fibp =\n lambda do |n|\n if n &gt; 1\n p1, p2 = fibp[n - 1]\n [p2, p1 + p2]\n else\n [0, n]\n end\n end\n\np fibp[1000].last\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T08:18:02.857", "Id": "19576", "Score": "0", "body": "You're right: using an array is faster than using single variables but I found this lambda solution being less convenient than the others. It is faster than my first one but slower than my second one (partially based on your suggestion), and overflows the stack a lot before the other approaches does." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T20:21:49.663", "Id": "12204", "ParentId": "12194", "Score": "1" } }, { "body": "<p>considering that this is Code Review, I have to say that you probably don't want to use an instance variable. You expose the internal data, and any user could destroy the workings of your method inadvertently. In Ruby 1.9, Ruby added a very interesting feature for just these types of situations that involve infinite sequences. It's called a <code>Fiber</code>.</p>\n\n<p>It's true that <code>Fiber</code>s aren't perfect for situations where you have to go backwards in the sequence in addition to forward. </p>\n\n<p>Another option for this is to put the data in a module:</p>\n\n<pre><code>module Fibonacci\n @fib=[0,1,1]\n def self.fib_array(n) \n @fib[n] ||= fib_array(n-2) + fib_array(n-1)\n end\nend\n</code></pre>\n\n<p>And use it like so:</p>\n\n<pre><code>Fibonacci.fib_array(42)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-11T00:20:02.040", "Id": "12453", "ParentId": "12194", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T16:04:43.890", "Id": "12194", "Score": "4", "Tags": [ "beginner", "ruby", "recursion", "reflection", "fibonacci-sequence" ], "Title": "Ruby Fibonacci(n) recursive computation optimized with reflection" }
12194
<p>I am looking into splay trees and I implemented a version. It seems correct. Could someone please let me know if this indeed correct and how to improve it?<br> I will just show the <code>insert</code> item and <code>splay</code>. It should be enough.</p> <p>The code is not that big as it seems in the first look. Briefly, I try to implement the splay tree according to algorithm storing the nodes in the access path in a stack (<code>thePath</code>) as I go up.</p> <pre><code>private Deque&lt;BinaryNode&lt;AnyType&gt;&gt; thePath = new LinkedList&lt;BinaryNode&lt;AnyType&gt;&gt;(); public enum ZIGZAGTYPE{ ZIG_ZAG_LEFT,ZIG_ZAG_RIGHT, ZIG_LEFT,ZIG_RIGHT, ZIG_ZIG_LEFT,ZIG_ZIG_RIGHT } public enum CHILDTYPE{LEFT, RIGHT}; public void insert(AnyType x) { thePath.clear(); BinaryNode&lt;AnyType&gt; theRoot = root; if(theRoot == null){ theRoot = new BinaryNode&lt;AnyType&gt;(x); root = theRoot; return; } while(theRoot != null){ int cmp = x.compareTo(theRoot.value); if(cmp &lt; 0){ thePath.push(theRoot); theRoot = theRoot.leftChild; } else{ thePath.push(theRoot); theRoot = theRoot.rightChild; } } BinaryNode&lt;AnyType&gt; newNode = new BinaryNode&lt;AnyType&gt;(x); if(thePath.peek().value.compareTo(x) &lt; 0){ thePath.peek().rightChild = newNode; } else { thePath.peek().leftChild = newNode; } thePath.push(newNode); splay(); } private void splay(){ if(thePath.isEmpty()){ throw new IllegalStateException(); } CHILDTYPE childType; BinaryNode&lt;AnyType&gt; parent; BinaryNode&lt;AnyType&gt; grandParent; BinaryNode&lt;AnyType&gt; current; while(thePath.size() &gt; 1){ current = thePath.pop(); parent = thePath.pop(); ZIGZAGTYPE type ; if(thePath.isEmpty()){ //we are at root--&gt; ZIG type = type(null, parent, parent); if(type == ZIG_LEFT){ parent = Rotations.rotateWithLeftChild(parent); } else{ parent = Rotations.rotateWithRightChild(parent); } thePath.push(parent); root = parent; } else{ grandParent = thePath.pop(); if(!thePath.isEmpty() &amp;&amp; grandParent == thePath.peek().leftChild){ childType = CHILDTYPE.LEFT; } else{ childType = CHILDTYPE.RIGHT; } type = type(grandParent, parent, current); if(type == ZIG_ZAG_LEFT){ //ZIG ZAG grandParent = Rotations.zigzagLeft(grandParent); } else if(type == ZIG_ZAG_RIGHT){ //ZIG ZAG grandParent = Rotations.zigzagRight(grandParent); } else if(type == ZIG_ZIG_RIGHT){ //ZIG ZAG grandParent = Rotations.zigzigRight(grandParent); } else if(type == ZIG_ZIG_LEFT){ //ZIG ZAG grandParent = Rotations.zigzigLeft(grandParent); } if(!thePath.isEmpty()){ if(childType == CHILDTYPE.LEFT){ thePath.peek().leftChild = grandParent; } else{ thePath.peek().rightChild = grandParent; } thePath.push(grandParent); } root = grandParent; } } } private ZIGZAGTYPE type(BinaryNode&lt;AnyType&gt; grandParent, BinaryNode&lt;AnyType&gt; parent, BinaryNode&lt;AnyType&gt; x){ if(grandParent == null){ return parent.leftChild == x?ZIG_LEFT:ZIG_RIGHT; } else if((grandParent.leftChild == parent &amp;&amp; parent.rightChild == x)){ return ZIG_ZAG_LEFT; } else if((grandParent.rightChild == parent &amp;&amp; parent.leftChild == x)){ return ZIG_ZAG_RIGHT; } else{ if((grandParent.leftChild == parent &amp;&amp; parent.leftChild == x)){ return ZIG_ZIG_LEFT; } else{ return ZIG_ZIG_RIGHT; } } } private static class Rotations &lt;AnyType&gt;{ public final static&lt;AnyType&gt; BinaryNode&lt;AnyType&gt; rotateWithLeftChild(BinaryNode&lt;AnyType&gt; r){ BinaryNode&lt;AnyType&gt; lc = r.leftChild; r.leftChild = lc.rightChild; lc.rightChild = r; return lc; } public final static&lt;AnyType&gt; BinaryNode&lt;AnyType&gt; rotateWithRightChild(BinaryNode&lt;AnyType&gt; r){ BinaryNode&lt;AnyType&gt; rc = r.rightChild; r.rightChild = rc.leftChild; rc.leftChild = r; return rc; } public final static&lt;AnyType&gt; BinaryNode&lt;AnyType&gt; zigzagLeft(BinaryNode&lt;AnyType&gt; g){ BinaryNode&lt;AnyType&gt; p = g.leftChild; g.leftChild = rotateWithRightChild(p); g = rotateWithLeftChild(g); return g; } public final static&lt;AnyType&gt; BinaryNode&lt;AnyType&gt; zigzagRight(BinaryNode&lt;AnyType&gt; g){ BinaryNode&lt;AnyType&gt; p = g.rightChild; g.rightChild = rotateWithLeftChild(p); g = rotateWithRightChild(g); return g; } public final static&lt;AnyType&gt; BinaryNode&lt;AnyType&gt; zigzigLeft(BinaryNode&lt;AnyType&gt; g){ g = rotateWithLeftChild(g); g = rotateWithLeftChild(g); return g; } public final static&lt;AnyType&gt; BinaryNode&lt;AnyType&gt; zigzigRight(BinaryNode&lt;AnyType&gt; g){ g = rotateWithRightChild(g); g = rotateWithRightChild(g); return g; } </code></pre>
[]
[ { "body": "<p>I did not check if the tree is indeed correct, but some comments in your design.</p>\n\n<ul>\n<li><p><code>rotateWithLeftChild</code> and <code>rotateWithRightChild</code> should be collapsed into some thing like</p>\n\n<pre><code>public final static&lt;AnyType&gt; BinaryNode&lt;AnyType&gt; rotateWithChild(BinaryNode&lt;AnyType&gt; r, Direction d){ \n BinaryNode&lt;AnyType&gt; c;\n switch(d) {\n case Left:\n c = r.leftChild; \n r.leftChild = c.rightChild; \n c.rightChild = r; \n return c; \n case Right:\n c = r.rightChild; \n r.rightChild = c.leftChild; \n c.leftChild = r; \n return c;\n } \n} \n</code></pre></li>\n<li><p><code>zigzagLeft</code>, <code>zigzagRight</code>, <code>zigzagRight</code>, <code>zigzagLeft</code> all should be collapsed into one method that takes an option value, and should do the zig/zag based on it.</p>\n\n<pre><code>public final static&lt;AnyType&gt; BinaryNode&lt;AnyType&gt; zigzag(BinaryNode&lt;AnyType&gt; g, ZIGZAGTYPE zz){ \n swtich(zz) {\n case ZigzagLeft:\n g.leftChild = rotateWithChild(g.leftChild, Right); \n return rotateWithChild(g,Left); \n case ZigzagRight:\n g.rightChild = rotateWithChild(g.rightChild, Left); \n return rotateWithChild(g,Right); \n case ZigzigLeft:\n g = rotateWithChild(g,Left); \n return rotateWithChild(g,Left); \n case ZigzigRight:\n g = rotateWithChild(g,Right); \n return rotateWithChild(g,Right); \n} \n</code></pre></li>\n</ul>\n\n<p>The advantage is that, rather than</p>\n\n<pre><code> if(type == ZIG_ZAG_LEFT){ \n //ZIG ZAG\n grandParent = Rotations.zigzagLeft(grandParent); \n\n } \n else if(type == ZIG_ZAG_RIGHT){ \n //ZIG ZAG\n grandParent = Rotations.zigzagRight(grandParent); \n\n } \n else if(type == ZIG_ZIG_RIGHT){ \n //ZIG ZAG \n grandParent = Rotations.zigzigRight(grandParent); \n\n } \n else if(type == ZIG_ZIG_LEFT){ \n //ZIG ZAG \n grandParent = Rotations.zigzigLeft(grandParent); \n\n } \n</code></pre>\n\n<p>You can just call</p>\n\n<pre><code> grandParent = Rotations.(grandParent, type); \n</code></pre>\n\n<p>For the function insert</p>\n\n<pre><code>public void insert(AnyType x) { \n thePath.clear(); \n</code></pre>\n\n<p>Avoid temptation to use redundant variables.</p>\n\n<pre><code> if(root == null){ \n root = new BinaryNode&lt;AnyType&gt;(x);\n return;\n }\n BinaryNode&lt;AnyType&gt; theRoot = root;\n</code></pre>\n\n<p>Pull out statements that are common in if and else clause\nTernaries help to simplify the if conditions when the variation is in a single place.</p>\n\n<pre><code> while(theRoot != null) {\n thePath.push(theRoot);\n theRoot = x.compareTo(theRoot.value) &lt; 0 ? theRoot.leftChild\n : theRoot.rightChild;\n }\n</code></pre>\n\n<p>I recommend that rather than using two members <code>leftChild</code> and <code>rightChild</code>, add a 2 element member array child, and refer to each as <code>child[Left]</code> and <code>child[Right]</code>. The advantage is that your code can be considerably simplified.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T05:06:22.627", "Id": "12210", "ParentId": "12195", "Score": "1" } }, { "body": "<p>I took a slightly different approach to reviewing this code. I set out to write the missing code and creating a working implementation. Without access to your BinaryNode class I took <a href=\"http://users.cis.fiu.edu/~weiss/dsj3/code/BinaryNode.java\" rel=\"nofollow\">this one</a> and worked to clean up my <code>SplayTree&lt;AnyType&gt;</code> class that included your code. Here are some changes I made and some notes about how they might help you.</p>\n\n<p>I switched over from public fields like <code>value</code>, <code>leftChild</code> and <code>rightChild</code> to <code>getElement()</code>, <code>setLeft()</code> etc. There are a lot of arguments for and against. <a href=\"http://schneide.wordpress.com/2010/10/25/statement-against-public-fields-in-java/\" rel=\"nofollow\">Here is one</a> that influenced me, make up your own mind.</p>\n\n<p>You are using a generic type (<code>AnyType</code>), but you are calling <code>compareTo()</code>. You will need to make sure you add <code>extends Comparable&lt;AnyType&gt;&gt;</code> to your SplayTree class and related methods (I'm assuming you know this because it wouldn't compile, so this note is more for others who follow you).</p>\n\n<p>Finally, You can reduce your zigzig and zagzag function in a small way (it's debatable if it's more readable, but it is some tiny amount more efficient, and to me it looks cleaner)</p>\n\n<pre><code>public final static &lt;AnyType extends Comparable&lt;AnyType&gt;&gt; BinaryNode&lt;AnyType&gt; zigzigLeft(BinaryNode&lt;AnyType&gt; g) {\n return rotateWithLeftChild(rotateWithLeftChild(g));\n}\n</code></pre>\n\n<p>I like rahul's idea that you can simplify the left/right methods by storing the child nodes in an array and passing a <code>LEFT</code> or <code>RIGHT</code> index.</p>\n\n<p>I'm going to have fun implementing a <code>find()</code> method and checking out if this code is correct.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T21:24:52.667", "Id": "18563", "ParentId": "12195", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T16:16:55.630", "Id": "12195", "Score": "2", "Tags": [ "java", "algorithm", "tree", "binary-search" ], "Title": "Splay tree implementation" }
12195
<p>The Demo for what I have made is located here: <a href="http://jsfiddle.net/maniator/H5LKy/181/" rel="nofollow noreferrer">http://jsfiddle.net/maniator/H5LKy/181/</a></p> <p>Basically I am trying to make a Wheel of Fortune type game.</p> <p>Is there anything I could improve on in the code?</p> <pre><code>var WOF = (function() { Array.prototype.randomize = function() { this.sort(function(a, b) { return Math.round(Math.random()); }); }; var prefix = (function() { if (document.body.style.MozTransform !== undefined) { return "MozTransform"; } else if (document.body.style.WebkitTransform !== undefined) { return "WebkitTransform"; } else if (document.body.style.OTransform !== undefined) { return "OTransform"; } else { return ""; } }()), degToRad = function(deg) { return deg / (Math.PI * 180); }, rotateElement = function(element, degrees) { var val = "rotate(-" + degrees + "deg)"; if (element.style[prefix] != undefined) element.style[prefix] = val; var rad = degToRad(degrees % 360), filter = "progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=" + rad + ", M12=-" + rad + ", M21=" + rad + ", M22=" + rad + ")"; if (element.style["filter"] != undefined) element.style["filter"] = filter; element.setAttribute("data-rotation", degrees); }, oc = function(a) { //object converter (changes array to an object) var o = {}; for (var i = 0; i &lt; a.length; i++) { o[a[i]] = ''; } return o; }, GAMECLASS = (function() { //static int var round = 0, //in the future this could be from an external server puzzles = [ "THE DARK KNIGHT RISES", "TO BE OR NOT TO BE", "PEANUT BUTTER JELLY TIME", "WILLY WONKA AND THE CHOCOLATE FACTORY", "SMASHMOUTH", "WHEEL OF FORTUNE", "TIME IS RELATIVE" ], vowels = ['A', 'E', 'I', 'O', 'U'], cards = ["200", "400", "-1", "750", "400", "150", "600", "400", "200", "1000", "800", "250", "500", "300", "250", "-2", "400", "200", "900", "500", "200", "0", "700", "450"], //br = 0, free spin = -1, lat = -2 currentMoney = 0, spinWheel = document.getElementById('spin'), buyVowel = document.getElementById('vowel'), displayArea = document.getElementById('display'), wheel = document.getElementById('wheel'), newButton = document.getElementById('newpuzzle'), money = document.getElementById('money'), solve = document.getElementById('solve'), spinTimeout = false, spinModifier = function() { return Math.random() * 10 + 20; }, modifier = spinModifier(), slowdownSpeed = 0.5; return function GAME() { puzzles.randomize(); var currentPuzzleArray = [], lettersInPuzzle = [], guessedArray = [], puzzleSolved = false, createBoard = function(currentPuzzle) { guessedArray = []; lettersInPuzzle = []; lettersGuessed = 0; puzzleSolved = false; currentPuzzleArray = currentPuzzle.split(""); var word = document.createElement('div'); displayArea.appendChild(word); word.className = "word"; for (var i = 0; i &lt; currentPuzzleArray.length; ++i) { var span = document.createElement('div'); span.className = "wordLetter "; if (currentPuzzleArray[i] != " ") { span.className += "letter"; if (!(currentPuzzleArray[i] in oc(lettersInPuzzle))) { lettersInPuzzle.push(currentPuzzleArray[i]); } word.appendChild(span); } else { span.className += "space" word = document.createElement('div'); displayArea.appendChild(word); word.className = "word"; word.appendChild(span); word = document.createElement('div'); displayArea.appendChild(word); word.className = "word"; } span.id = "letter" + i; } var clear = document.createElement('div'); displayArea.appendChild(clear); clear.className = "clear"; }, solvePuzzle = function() { if (!puzzleSolved &amp;&amp; !createGuessPromt("SOLVE THE PUZZLE?", null, true)) { alert("Puzzle NOT solved..."); } }, guessLetter = function(guess, isVowel, solvingPuzzle) { var timesFound = 0; isVowel = isVowel == undefined ? false : true; solvingPuzzle = solvingPuzzle == undefined ? false : true; //find it: if (guess.length &amp;&amp; !puzzleSolved) { if ((guess in oc(vowels)) &amp;&amp; !isVowel &amp;&amp; !solvingPuzzle) { alert("Cannot guess a vowel right now!"); return false; } if (isVowel &amp;&amp; !(guess in oc(vowels)) &amp;&amp; !solvingPuzzle) { alert("Cannot guess a consanant right now!"); return false; } for (var i = 0; i &lt; currentPuzzleArray.length; ++i) { if (guess == currentPuzzleArray[i]) { var span = document.getElementById("letter" + i); if (span.innerHTML != guess) { //found it ++timesFound; } span.innerHTML = guess; if (guess in oc(lettersInPuzzle) &amp;&amp; !(guess in oc(guessedArray))) { guessedArray.push(guess); } } } if (guessedArray.length == lettersInPuzzle.length) { alert("PUZZLE SOLVED!"); puzzleSolved = true; } return timesFound; } return false; }, nextRound = function() { ++round; if (round &lt; puzzles.length) { while (displayArea.hasChildNodes()) { //remove old puzzle displayArea.removeChild(displayArea.firstChild); } createBoard(puzzles[round]); } else alert("No more puzzles!"); }, updateMoney = function() { money.innerHTML = currentMoney; }, spinWheelfn = function(amt) { clearTimeout(spinTimeout); if (!puzzleSolved) { modifier -= slowdownSpeed; if (amt == undefined) { amt = parseInt(wheel.getAttribute('data-rotation')); } rotateElement(wheel, amt); if (modifier &gt; 0) { spinTimeout = setTimeout(function() { spinWheelfn(amt + modifier); }, 1000 / 5); } else { modifier = spinModifier(); var card = cards[Math.floor(Math.round(parseInt(wheel.getAttribute('data-rotation')) % 360) / 15)]; switch (parseInt(card)) { case 0: alert("BANKRUPT!"); currentMoney = 0; break; case -1: alert("FREE SPIN!"); break; case -2: alert("LOSE A TURN"); break; default: var timesFound = createGuessPromt("YOU SPUN A " + card + " PLEASE ENTER A LETTER"); currentMoney += (parseInt(card) * timesFound); } updateMoney(); } } }, guessTimes = 0, createGuessPromt = function(msg, isVowel, solvingPuzzle) { solvingPuzzle = solvingPuzzle == undefined ? false : true; if (!puzzleSolved) { var letter = prompt(msg, ""); if (letter) { var guess = ''; if (!solvingPuzzle) { guess = letter.toUpperCase().charAt(0) } else { guess = letter.toUpperCase().split(""); function arrays_equal(a, b) { return !(a &lt; b || b &lt; a); }; if (arrays_equal(guess, currentPuzzleArray)) { for (var i = 0; i &lt; guess.length; ++i) { guessLetter(guess[i], isVowel, solvingPuzzle); } } return puzzleSolved; } var timesFound = guessLetter(guess, isVowel, solvingPuzzle); if (timesFound === false) { ++guessTimes; if (guessTimes &lt; 5) { return createGuessPromt(msg, isVowel, solvingPuzzle); } } guessTimes = 0; return timesFound; } else { ++guessTimes; if (guessTimes &lt; 5) { return createGuessPromt(msg, isVowel, solvingPuzzle); } } } return false; }; //CLICK EVENTS function bindEvent(el, eventName, eventHandler) { if (el.addEventListener) { el.addEventListener(eventName, eventHandler, false); } else if (el.attachEvent) { el.attachEvent('on' + eventName, eventHandler); } } bindEvent(buyVowel, "click", function() { if (currentMoney &gt; 200) { if (createGuessPromt("PLEASE ENTER A VOWEL", true) !== false) currentMoney -= 200; } else { alert("You need more than $200 to buy a vowel"); } updateMoney(); }); bindEvent(newButton, "click", nextRound); bindEvent(spinWheel, "click", function() { spinWheelfn(); }); bindEvent(wheel, "click", function() { spinWheelfn(); }); bindEvent(solve, "click", function() { solvePuzzle(); }); this.start = function() { createBoard(puzzles[round]); }; } })(), game = new GAMECLASS; return game; })(); WOF.start();​ </code></pre> <p>I know that <a href="https://stackoverflow.com/q/10806007/561731">the wheel doesn't spin right in IE</a></p>
[]
[ { "body": "<p>Your array <code>.randomize()</code> isn't really that good. Consider:</p>\n\n<pre><code>var l = 100000, o = {}, a;\n\nwhile( l-- ) {\n a = [1,2,3,4,5,6,7,8,9,10];\n a.randomize();\n if( !o[a[0]] ) {\n o[a[0]] = 0\n }\n\n o[a[0]]++;\n}\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>Object\n1: 29047\n2: 28811\n3: 19420\n4: 10982\n5: 5873\n6: 2979\n7: 1548\n8: 745\n9: 396\n10: 199\n</code></pre>\n\n<p>See how often the number <code>1</code> ends up being in the first position? They should all end up in all positions 10000 <em>(100000/10)</em> times.</p>\n\n<p>Now try:</p>\n\n<pre><code>var l = 100000, o = {}, a;\n\n while( l-- ) {\n a = [1,2,3,4,5,6,7,8,9,10];\n fisherYates( a );\n if( !o[a[0]] ) {\n o[a[0]] = 0\n }\n\n o[a[0]]++;\n }\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>Object\n1: 9994\n2: 10032\n3: 10080\n4: 10007\n5: 9992\n6: 10242\n7: 9975\n8: 9846\n9: 9845\n10: 9987\n</code></pre>\n\n<p>Implementation for fisherYates:</p>\n\n<pre><code>function fisherYates ( myArray ) {\n var i = myArray.length;\n if ( i == 0 ) return false;\n while ( --i ) {\n var j = Math.floor( Math.random() * ( i + 1 ) );\n var tempi = myArray[i];\n var tempj = myArray[j];\n myArray[i] = tempj;\n myArray[j] = tempi;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T17:42:18.027", "Id": "19552", "Score": "5", "body": "`var randomize = (function() { return 1; }());` would be better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T17:56:15.967", "Id": "19555", "Score": "0", "body": "@FlorianMargaine oy..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T14:39:16.010", "Id": "45613", "Score": "0", "body": "@Esailija -- update: http://codereview.stackexchange.com/q/28973/3163" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T17:31:31.033", "Id": "12200", "ParentId": "12197", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T16:47:01.980", "Id": "12197", "Score": "1", "Tags": [ "javascript", "game" ], "Title": "Wheel of Fortune game" }
12197
<p>I need a way to store and retrieve callbacks in Ruby, so I made a <code>Callbacks</code> class. Any suggestions would be greatly appreciated.</p> <pre><code>class Callbacks def initialize # name: name of callback # event: event of which it belongs # callback: block to call @callbacks = [] end def add name, event, &amp;block if block_given? @callbacks &lt;&lt; { name: name, event: event, callback: block } end end def get options={} name = options[:name] event = options[:event] @callbacks.each do |h| if name and event return h if h[:name] == name and h[:event] == event else return h if h[:name] == name or h[:event] == event end end nil end end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T18:16:35.467", "Id": "19556", "Score": "0", "body": "Just to be sure, you are returning the callback even if one of the properties does not match. Is this intensional?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T18:24:02.743", "Id": "19557", "Score": "0", "body": "Yes, it is returning a callback even if one of the options is not defined." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T18:26:12.660", "Id": "19558", "Score": "0", "body": "In your code, it would match even if both the options are defined but say the name does not match. Surely this is not the correct behavior then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T18:34:21.187", "Id": "19560", "Score": "0", "body": "That doesn't sound right. If `:name` and `:event` are defined, it searches for a callback that matches **both** `:name` and `:event`. Otherwise, it matches one or the other." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T18:43:52.640", "Id": "19561", "Score": "0", "body": "Oh ok, my mistake." } ]
[ { "body": "<p>Why not use a hashmap as the main DS? That way, you optimize for when name and event are defined, and suffer only a constant penalty and degrades to linear for other cases. (In your solution the cost is always linear). (As below)</p>\n\n<pre><code>class Callbacks\n def initialize\n @callbacks = {}\n end\n\n def add(name, event, &amp;block)\n key = {:name =&gt; name, :event =&gt; event}\n @callbacks[key] = block if block_given?\n</code></pre>\n\n<p>shouldn't we throw an exception if block is not given?</p>\n\n<pre><code> end\n\n def get(o={})\n</code></pre>\n\n<p>We can use values_at to extract multiple values from a hash.</p>\n\n<pre><code> name,event = o.values_at(:name,:event)\n</code></pre>\n\n<p>We don't need to check if name and event separately because equality checking does it for us.</p>\n\n<pre><code> return @callbacks[o] if name and event\n @callbacks.each do |k,v|\n return v if k[:name] == name or k[:event] == event\n end\n nil\n end\nend\n</code></pre>\n\n<p>And shouldn't you provide a way to unregister from callback?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T22:15:36.447", "Id": "12207", "ParentId": "12201", "Score": "1" } } ]
{ "AcceptedAnswerId": "12207", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T17:53:00.750", "Id": "12201", "Score": "3", "Tags": [ "ruby", "callback" ], "Title": "Ruby Callback System" }
12201
<p>I am interested in printing all numbers that do not have a match in an array.<br> Example: <code>1,3,4,5,3,4,5,5,6</code> result <code>1,5,6</code><br> Please review my solution bellow. What would be a much better way for this? Any input on how to improve this is welcome</p> <pre><code>public static Integer[] outputSinglePair(Integer[] numbers){ if(numbers == null) throw new IllegalArgumentException(); Arrays.sort(numbers); ArrayList&lt;Integer&gt; result = new ArrayList&lt;Integer&gt;(); for(int i = 0; i &lt; numbers.length - 1; ){ if(numbers[i] != numbers[i + 1]){ result.add(numbers[i]); i++; } else i+=2; if(i == numbers.length - 1)result.add(numbers[i]);//we hit last element of array which is unpaired } return result.toArray(new Integer[0]); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-13T15:26:51.203", "Id": "20195", "Score": "1", "body": "Are you sure that you have phrased this question correctly? \"am interested in printing all numbers that do not have a match in an array.\" Based on your input, 1 appears once, 3 appears twice, 4 appears twice, 5 appears thrice, and 6 appears once. I would expect that only numbers 1 and 6 appear in the result set yet you have included 5. Can you please clarify?" } ]
[ { "body": "<p>I think this is the sort of thing for which <code>HashSet</code> is perfect. Your implementation would look something like I have shown below. The advantage is that you don't need a sort so your running time is strictly linear.</p>\n\n<p>(Updated to fix syntax errors)</p>\n\n<pre><code>public static Integer[] outputSinglePair(Integer[] numbers){ \n if(numbers == null)\n throw new IllegalArgumentException();\n\n HashSet&lt;Integer&gt; result = new HashSet&lt;Integer&gt;();\n for (int next: numbers) {\n if (result.contains(next)) {\n result.remove(next);\n }\n else {\n result.add(next);\n }\n }\n return result.toArray(new Integer[result.size()]);\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T04:25:11.170", "Id": "19570", "Score": "0", "body": "It doesn't work if number exists in the array 3, 5, and etc (odd number) times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T04:50:49.977", "Id": "19573", "Score": "0", "body": "Actually, it *does* work for odd number times. When you have three of something - first one goes into result, second one takes it out, third puts it back in. I tested it just to make sure (and fix a couple of syntax errors)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T21:23:29.143", "Id": "12206", "ParentId": "12203", "Score": "8" } } ]
{ "AcceptedAnswerId": "12206", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T20:07:53.067", "Id": "12203", "Score": "6", "Tags": [ "java", "algorithm", "array" ], "Title": "Find all single elements in an array" }
12203
<p>I've written a class for loading a template file and replacing the variables with actual data. Please review my code and suggest improvements.</p> <pre><code>&lt;?php /** * This class will helpful for variable replacement from a loaded file * * @author V V R * @version 1.0 */ class Parser { public $dir = ""; public $text = ""; /** * To get directory location * @param $dir */ function __construct($dir = "home/template") { $this-&gt;dir = $dir; } /** * To load the specified file from directory * @param $file */ function loadFile($file) { try { if (file_exists ( $this-&gt;dir . "/" . $file )) { $this-&gt;text = file_get_contents ( $this-&gt;dir . "/" . $file ); } else { throw new Exception ( $this-&gt;dir . "/" . $file . " does not exist" ); } } catch ( Exception $e ) { error_log ( $e-&gt;getMessage () ); die (); } } /** * To get the text from a file * @return text */ function getText() { return $this-&gt;text; } /** * To replace the variables * @param unknown_type $var * @param unknown_type $text */ function replace($var, $text) { $this-&gt;text = str_replace ( "{\$$var}", $text, $this-&gt;text ); } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T07:19:34.340", "Id": "19574", "Score": "0", "body": "Have you considered using an existing solution, such as [Mustache PHP](https://github.com/bobthecow/mustache.php)?" } ]
[ { "body": "<p><strong>Note:</strong> I'm sorry if this is completely irrelevant but I'm not entirely sure what you are trying to accomplish. If I'm way off base please let me know.</p>\n\n<p>When I create a template loader I generally use <a href=\"http://php.net/manual/en/book.outcontrol.php\">output buffering</a> with php <code>include</code>. This allows you to run the page as a php file without displaying its content before you are ready. The advantage to \"parsing\" your php files this way is that you can still run loops and functions.</p>\n\n<p>This is how your <code>loadFile</code> method would look.</p>\n\n<pre><code>&lt;?php\n\nfunction loadFile($file, array $variables = null) {\n try {\n if (file_exists ( $this-&gt;dir . \"/\" . $file )) {\n\n // start output buffering\n ob_start();\n\n // create variables from the key/value pairs in the array\n if( is_array($variables) ) {\n extract($variables);\n }\n\n include_once $this-&gt;dir . \"/\" . $file;\n\n // store the output\n $this-&gt;text = ob_get_clean();\n\n // $this-&gt;text = file_get_contents ( $this-&gt;dir . \"/\" . $file );\n } else {\n throw new Exception ( $this-&gt;dir . \"/\" . $file . \" does not exist\" );\n }\n } catch ( Exception $e ) {\n error_log ( $e-&gt;getMessage () );\n die ();\n }\n}\n\n?&gt;\n</code></pre>\n\n<p>As I said before, I'm not sure what kind of templates you are trying to load, but hopefully this will help.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T13:36:43.130", "Id": "19607", "Score": "2", "body": "I don't think its off topic at all. He asked for suggestions for better code and you provided it. +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T12:09:31.357", "Id": "12216", "ParentId": "12211", "Score": "6" } }, { "body": "<p><strong>Properties</strong></p>\n\n<p>Your class properties probably shouldn't be visible outside of the class once they are set unless you do so with a getter method, like you have for the <code>$text</code> property. This is to say, the <code>$dir</code> and <code>$text</code> properties should not be public but private to prevent outside manipulations.</p>\n\n<p><strong>Public or Private</strong></p>\n\n<p>Your methods are not defined as either public or private. By default they will all be public, but it is better practice to just define them as such manually. Doubtful, but what if the default changes to private in a later version? Or what if PHP deprecates calling methods in this way? Your class will break. Always code with the future in mind.</p>\n\n<p><strong>loadFile()</strong></p>\n\n<p>As Baylor Rae said, it is more conventional to use output buffering when loading templates. He has given a good example, so I won't linger on it. Instead I will tell you how I would change your current <code>loadFile()</code> method to reuse less code. This can be used on Baylor's example as well.</p>\n\n<pre><code>function loadFile($filename) {\n $file = $this-&gt;dir . '/' . $filename;\n\n try {\n if (file_exists ( $file )) {\n $this-&gt;text = file_get_contents ( $file );\n } else {\n throw new Exception ( \"$file does not exist\" );\n }\n } catch ( Exception $e ) {\n error_log ( $e-&gt;getMessage () );\n die ();\n }\n}\n</code></pre>\n\n<p>You shouldn't use <code>die()</code> in your scripts unless it is for debugging purposes. It is not very elegant and will leave your customers scratching their heads wondering where the rest of their content went. Instead I would have your <code>loadFile()</code> method return TRUE on success and FALSE on failure and then handle each individually in the controller.</p>\n\n<p><strong>Strings</strong></p>\n\n<p>Last thing I wish to leave you with. I see that you are using double quotes for all of your strings. This is a minor thing, but it is telling PHP that it should look in that string for variables to parse. If the string does not require parsing it should only use single quotes. Admittedly, this doesn't make a noticeable impact on your code, but it is something to keep in mind :)</p>\n\n<p>Good luck!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T13:38:47.577", "Id": "12217", "ParentId": "12211", "Score": "3" } } ]
{ "AcceptedAnswerId": "12216", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T06:28:57.453", "Id": "12211", "Score": "5", "Tags": [ "php", "php5" ], "Title": "Replacing variables with actual data" }
12211
<p>Callback is a piece of code that is stored or registered in a higher layer or a different object such that the piece of code being stored has access to the information available in the current context. The registrar has the ability to invoke the code later in response to some event so that the action performed has access to all the environment available at the time of creation of callback (Thus calling back to the original code).</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T15:53:49.267", "Id": "12218", "Score": "0", "Tags": null, "Title": null }
12218
Callback is facility to save a piece of code so that it may be invoked later in the current environment (Typically in response to an event)
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T15:53:49.267", "Id": "12219", "Score": "0", "Tags": null, "Title": null }
12219
<p>I did a quick google search, and it didn't show up.</p> <p>I haven't noticed it posted in pylint.py, or PEP8.py.</p> <p>My emacs mode doesn't warn me if my <code>import</code>s are listed arbitrarily...does anyone do this?</p> <pre><code>import longest.modulename.first import medium.sizename import short import sys import os from imports import go_at_the_bottom from length import does_matter from still import cascading </code></pre> <p>This is typically how I do it. But after a while, the list gets big!</p> <p>I think this might work better, but it's kind of ugly:</p> <pre><code>import longest.modulename.first import medium.sizename import os import short import sys from BeautifulSoup import BeautifulSoup as BS from BeautifulSoup import BeautifulStoneSoup as BSS #froms are sorted by import from imports import go_at_the_bottom from length import does_matter from mechanize import Browser as br from still import cascading </code></pre> <p>What's the standard for this? I like the look of the cascading imports, but I also like the utility of searching for what's being used in the script quickly.</p> <p>Is there another approach to this that I didn't cover that you use?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T23:27:38.393", "Id": "19763", "Score": "0", "body": "Interesting ... StyleCop can handle this for C#, and yes - system imports come first." } ]
[ { "body": "<p>With a lot of import statements, I usually group imports by use case and origin.</p>\n\n<pre><code>#Standard library modules, grouped by use case\nimport os\nimport sys\n\nimport datetime\nimport time\n\nimport json\n\n\n\n#Third party modules, also grouped by use case\nimport tornado.web\nimport tornado.ioloop\n\n\n\n#My modules\nfrom mymodule import something\nfrom myothermodule import something else\n\n\n#Modules used for debugging, testing etc.. \n#Stuff that will be removed before a release\nimport logging\nimport pprint\n\n\n\n#CODE\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T17:07:44.567", "Id": "22137", "Score": "0", "body": "I like this. The extra spaces are very much my style as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T17:38:43.663", "Id": "12222", "ParentId": "12220", "Score": "3" } }, { "body": "<p>I tend to do it like so:</p>\n\n<pre><code>#Full Standard modules by length\nimport os\nimport sys\nimport smtp\nimport datetime\n\n#Specific Funct afterword\nfrom email.mime.text import MIMEText\nfrom mymodule import myfunct1, myfunct2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T12:41:28.490", "Id": "19669", "Score": "1", "body": "+1 this looks very readable to me. In the absence of a standard, I like this idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-26T10:05:02.413", "Id": "242092", "Score": "0", "body": "But it is not very easy to find whether a module is already in the list, whereas sorting alphabetically helps with that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T18:36:19.023", "Id": "12224", "ParentId": "12220", "Score": "3" } }, { "body": "<p>PEP-8 <a href=\"http://www.python.org/dev/peps/pep-0008/#imports\">says</a>:</p>\n\n<blockquote>\n <p>Imports should be grouped in the following order:</p>\n \n <ol>\n <li>standard library imports</li>\n <li>related third party imports</li>\n <li>local application/library specific imports</li>\n </ol>\n \n <p>You should put a blank line\n between each group of imports.</p>\n</blockquote>\n\n<p>I follow it and then sort modules alphabetically within each group without separating <code>from</code> from the other <code>import</code>s, like this:</p>\n\n<pre><code>import re\nimport os\nfrom pprint import pprint\nimport traceback\n\nimport lxml\n\nfrom readers import SomeReader\nfrom util.stuff import (stuff_init, stuff_close, StdStuff,\n OtherStuff, BlahBlah)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T13:01:22.567", "Id": "19670", "Score": "0", "body": "+1 for quoting pep-8, useful for others to see who come across this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T23:14:55.633", "Id": "463040", "Score": "0", "body": "Because `pprint` the module and `pprint` the function are represented by identical strings, it's not clear whether you're alphabetizing on the module from which you're importing or the name you're actually importing. In other words, if you were importing something called `mprint` from `pprint` (i.e., importing something that comes alphabetically before `os`), would you place that before or after your `import os`?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T10:11:24.177", "Id": "12258", "ParentId": "12220", "Score": "12" } } ]
{ "AcceptedAnswerId": "12258", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T16:04:00.827", "Id": "12220", "Score": "4", "Tags": [ "python" ], "Title": "Alphabetizing `import` Statements" }
12220
<p>I have this custom <code>IComparer</code> I use to sort a list of <code>SurveyResponse</code> objects, but it seems really inefficient, both in terms of runtime performance, and code elegance and maintainability. I thought of implementing <code>IComparable</code> for each of these components, and each <code>CompareTo</code> knowing its "parent" to compare, but the sort order for this report I'm making won't necessarily be the same as other sort orders, so that may not work.</p> <p>It looks like the sort of problem that should be solvable using recursion, but maybe I'm just over-analyzing it?</p> <p>Are there any best practices that would make this faster and more maintainable?</p> <pre><code>private class CommentComparer : IComparer&lt;SurveyResponse&gt; { public int Compare(SurveyResponse x, SurveyResponse y) { // Sort by Application Name... int result = x.Question.Survey.Feature.Application.Name.CompareTo( y.Question.Survey.Feature.Application.Name); if (result != 0) { return result; } // ...then Feature Name... result = x.Question.Survey.Feature.Name.CompareTo( y.Question.Survey.Feature.Name); if (result != 0) { return result; } // ...then SurveyTime... result = x.Question.Survey.TimeTaken.CompareTo(y.Question.Survey.TimeTaken); if (result != 0) { return result; } // ...then ID... result = x.Question.Survey.ID.CompareTo(y.Question.Survey.ID); if (result != 0) { return result; } // ...then Position. return x.Question.Position.CompareTo(y.Question.Position); } } </code></pre>
[]
[ { "body": "<p>You can use types from <a href=\"https://github.com/jehugaleahsa/ComparerExtensions\" rel=\"nofollow\">ComparerExtensions</a> to make your code more maintainable:</p>\n\n<pre><code>IComparer&lt;SurveyResponse&gt; comparer = KeyComparer&lt;SurveyResponse&gt;\n .OrderBy(sr =&gt; sr.Question.Survey.Feature.Application.Name)\n .ThenBy(sr =&gt; sr.Question.Survey.Feature.Name)\n .ThenBy(sr =&gt; sr.Question.Survey.TimeTaken)\n .ThenBy(sr =&gt; sr.Question.Survey.ID)\n .ThenBy(sr =&gt; sr.Question.Position);\n</code></pre>\n\n<p>But I don't think you can actually make your comparer more efficient, it should be already very fast (it's just a few simple instructions). Are you sure your performance problem is caused by this comparer?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T18:39:40.857", "Id": "19748", "Score": "1", "body": "I've been pulled off that project, but any performance delay was probably more likely caused by the fact that the SurveyResponse objects are NHibernate-mapped, lazily-initialized objects. I probably need to explicitly pre-fill all the data I might need to compare when originally populating the list. I didn't get a chance to eliminate that delay yet, and thought I'd check on the performance, here, while reviewing the ugliness of the code, too. Thanks! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T23:45:46.460", "Id": "19981", "Score": "0", "body": "Very elegant! But this code might actually have worse performance than the OP's code simply because the OP's has short-circuiting. That is, if any of the `CompareTo`s finds a difference, it returns immediately. Does this code do the same? I would guess not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T00:04:52.253", "Id": "19983", "Score": "0", "body": "@Pat It does use short-circuiting (see [`CompoundComparer<T>.Compare()`](http://nlist.codeplex.com/SourceControl/changeset/view/76029#1703429) and notice the condition in `for`). But the performance might be actually worse, because of delegate invocations." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T17:59:28.803", "Id": "12223", "ParentId": "12221", "Score": "8" } }, { "body": "<p>+1 to @svick of course. Here is another solution without NList, LINQ, etc., maybe somebody find it interesting. Creating a separate <code>IComparer</code> for every comparison also could work, for example:</p>\n\n<pre><code>private class ApplicationNameComparer : IComparer&lt;SurveyResponse&gt; {\n public int Compare(SurveyResponse x, SurveyResponse y) {\n return x.Question.Survey.Feature.Application.Name.\n CompareTo(y.Question.Survey.Feature.Application.Name);\n }\n}\n</code></pre>\n\n<p>then put them into a list:</p>\n\n<pre><code>var comparers = new List&lt;IComparer&lt;SurveyResponse&gt;&gt;();\ncomparers.Add(new ApplicationNameComparer());\ncomparers.Add(new FeatureNameComparer());\ncomparers.Add(new SurveyTimeComparer());\ncomparers.Add(new IdComparer());\ncomparers.Add(new PositionComparer());\n</code></pre>\n\n<p>finally iterate through the list:</p>\n\n<pre><code>foreach (var comparer in comparers) {\n int result = comparer.Compare(x, y); \n if (result != 0) {\n return result;\n }\n}\nreturn 0;\n</code></pre>\n\n<p>It removes the logic repetition of <code>if (result != 0) { return result; }</code> but it uses more classes. On the other hand every class has single responsibility and they do something more complex together.</p>\n\n<p>References: </p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Single_responsibility_principle</a></li>\n<li><a href=\"http://c2.com/cgi/wiki?FearOfAddingClasses\" rel=\"nofollow\">http://c2.com/cgi/wiki?FearOfAddingClasses</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T18:34:43.487", "Id": "19746", "Score": "0", "body": "Thanks for your insight. I can't vote up on CR yet, but I would if I could. I think your solution would be more suitable if this wasn't a quick one-off problem I needed to solve :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T18:53:03.207", "Id": "19749", "Score": "0", "body": "@mo. You can now :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T18:55:39.053", "Id": "19750", "Score": "0", "body": "I don't like this solution much because it's even more repetition than the original code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T19:11:22.763", "Id": "19751", "Score": "0", "body": "@svick: Thanks for the edit! What kind of repetition do you think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T19:15:01.603", "Id": "19752", "Score": "0", "body": "@palacsint The code you have to write for each comparer. In your version, it's about 7 lines per comparer, in the question it was only 3, but still with a lot of repetition. In my version, it's only 1 line per comparer. (Of course LOC is a very rough measure, but it does say something.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T20:11:19.880", "Id": "19758", "Score": "0", "body": "@svick: NList definitely the best solution. This removes some logic duplication of the original code. I think removing logic duplication is more important than the number of lines. Check the update, please." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-13T20:40:07.770", "Id": "20231", "Score": "1", "body": "As the creator of NList, I can confirm that @palacsint's solution is how NList is implemented internally." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T17:26:23.703", "Id": "12273", "ParentId": "12221", "Score": "3" } }, { "body": "<p>As the creator of NList, I can confirm that @palacsint's solution is how NList is implemented internally.</p>\n\n<p>Another way to implement it is using the chain-of-command pattern.</p>\n\n<pre><code>public class CompoundComparer&lt;T&gt; : IComparer&lt;T&gt;\n{\n private readonly IComparer&lt;T&gt; first;\n private readonly IComparer&lt;T&gt; second;\n\n public CompoundComparer(IComparer&lt;T&gt; first, IComparer&lt;T&gt; second)\n {\n this.first = first;\n this.second = second;\n }\n\n public int Compare(T x, Ty)\n {\n int result = first(x, y);\n if (result != 0)\n {\n return result;\n }\n return second(x, y);\n }\n}\n</code></pre>\n\n<p>Once you've created this class, you can compose them together to build more complex comparisons.</p>\n\n<pre><code>IComparer&lt;T&gt; comparer = new CompoundComparer&lt;T&gt;(\n comparison1,\n new CompoundComparison(\n comparison2,\n comparison3));\n</code></pre>\n\n<p>Some helper functions can make this easier to read/write. At that point, though, it is probably just easier to steal code from NList. I wrote it so you don't have to.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-13T20:40:07.770", "Id": "12563", "ParentId": "12221", "Score": "2" } } ]
{ "AcceptedAnswerId": "12223", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T16:48:50.093", "Id": "12221", "Score": "9", "Tags": [ "c#", "performance", "sorting" ], "Title": "Multi-tiered sorting using custom IComparer" }
12221
<p>I much prefer the Java enhanced for each loop, but I often find there are certain times where I need to break from a loop, take the following contrived example:</p> <pre><code>final List&lt;String&gt; strings = new ArrayList&lt;&gt;( Arrays.asList(new String[] { "test", "new", "break", "notThere","last" })); boolean found; for(String s : strings) { found = s.equals("break"); if (found) { break; } } </code></pre> <p>Needs to be rewritten as the following to avoid the break statement:</p> <pre><code>int i; boolean found; for (found = false, i = 0; i &lt; strings.size() &amp;&amp; !found; i++) { found = strings.get(i).equals("break"); } </code></pre> <p>Which would you prefer to come across? I very much prefer the second format (in the case where I need to break), but I have a feeling I'm in the minority.</p> <p>Edit: I do need to keep track of where the item was located.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-07T10:40:57.023", "Id": "19830", "Score": "0", "body": "May I ask what's wrong with just using the `break` statement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T17:09:53.183", "Id": "19949", "Score": "0", "body": "Anything more then a for(String s : strings) {} or for(int i = 0; i < strings.size(); i++) {} is not something I usually find in code, and it takes a longer time to understand what it is doing, and what it's conditions are." } ]
[ { "body": "<p>I suppose you feel that foreach is a kind of a map, and that inhibits you from exiting in the middle. In most code that I have seen, the first form is preferred except in the cases where we need to get the index where the break happened.</p>\n\n<p>i.e This is ugly.</p>\n\n<pre><code>int found = 0;\nfor(String s : strings) {\n if (s.equals(\"break\")) break;\n found++;\n}\n</code></pre>\n\n<p>I myself prefer the first form because it avoids the need to declare an extra variable, and in my (highly subjective) opinion, extra variables tend to clutter up program, and inhibits comprehension.</p>\n\n<p>In your updated example, I will jump in your boat if you change the for statement to while and remove found :).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T20:39:05.860", "Id": "19625", "Score": "0", "body": "My contrived example forgot to mention that I need access to where I located the item. Adding that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T09:30:04.760", "Id": "19891", "Score": "1", "body": "Modesty is a nice trait but your preference here is distinctly *non*-subjective. Less variables *do* reduce the complexity of the code, that’s an *objective* advantage." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T20:34:09.023", "Id": "12226", "ParentId": "12225", "Score": "4" } }, { "body": "<p>I'd use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/List.html#indexOf%28java.lang.Object%29\"><code>List.indexOf(Object o)</code></a>. From the documentation:</p>\n\n<blockquote>\n <p>Returns the index of the first occurrence of the specified element in this list, or <code>-1</code> if this list does not contain the element. More formally, returns the lowest index <code>i</code> such that <code>(o==null ? get(i)==null : o.equals(get(i)))</code>, or <code>-1</code> if there is no such index. </p>\n</blockquote>\n\n<p>If you need a more complex examination you still can extract out the loop to a method with multiple <code>return</code> statements:</p>\n\n<pre><code>public int getFirstIndexOfSomething(final List&lt;String&gt; input) {\n int i = 0; \n for (String s: input) {\n if (... check s here ...) {\n return i;\n }\n i++;\n }\n return -1;\n}\n</code></pre>\n\n<p>If you want a really bulletproof solution you can use a custom <code>SearchResult</code> object to store the result and its index (if there is any result):</p>\n\n<pre><code>public class SearchResult {\n private final boolean found;\n private final int index;\n\n private SearchResult(final boolean found) {\n this.found = false;\n this.index = -1;\n }\n\n private SearchResult(final int index) {\n if (index &lt; 0) {\n throw new IllegalArgumentException(\"index cannot be less than zero\");\n }\n found = true;\n this.index = index;\n }\n\n public static SearchResult createFound(final int index) {\n return new SearchResult(index);\n }\n\n public static SearchResult createNotFound() {\n return new SearchResult(false);\n }\n\n public boolean isFound() {\n return found;\n }\n\n public int getIndex() {\n if (!found) {\n throw new IllegalStateException();\n }\n return index;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>public SearchResult getFirstIndexOfSomething(final List&lt;String&gt; input) {\n int i = 0; \n for (String s: input) {\n if (... check is here ...) {\n return SearchResult.createFound(i);\n }\n i++;\n }\n return SearchResult.createNotFound();\n}\n</code></pre>\n\n<p>It does not let client codes to get invalid indexes since the <code>getIndex</code> method throws an exception when the for loop do not find any result.</p>\n\n<p>A more sophisticated solution is using polymorphism to separate the two states to two simpler classes with a common interface:</p>\n\n<pre><code>public interface SearchResult {\n\n boolean isFound();\n\n int getIndex();\n}\n\npublic class NoResult implements SearchResult {\n\n public NoResult() {\n }\n\n @Override\n public boolean isFound() {\n return false;\n }\n\n @Override\n public int getIndex() {\n throw new IllegalStateException();\n }\n}\n\npublic class Result implements SearchResult {\n\n private final int index;\n\n public Result(final int index) {\n if (index &lt; 0) {\n throw new IllegalArgumentException(\"index cannot be less than zero\");\n }\n this.index = index;\n }\n\n @Override\n public boolean isFound() {\n return true;\n }\n\n @Override\n public int getIndex() {\n return index;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>public SearchResult getFirstIndexOfSomething(final List&lt;String&gt; input) {\n int i = 0; \n for (String s: input) {\n if (... check is here ...) {\n return new Result(i);\n }\n i++;\n }\n return new NoResult();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T10:45:56.093", "Id": "12230", "ParentId": "12225", "Score": "5" } }, { "body": "<p>I would use</p>\n\n<pre><code> if (list.contains(\"break\")) { \n ...\n }\n</code></pre>\n\n<p>If inavoidable, the enhanced one I personally find more readable</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T05:24:12.110", "Id": "12374", "ParentId": "12225", "Score": "1" } } ]
{ "AcceptedAnswerId": "12230", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T20:23:43.820", "Id": "12225", "Score": "4", "Tags": [ "java" ], "Title": "Enhanced for loop" }
12225
<p>What I'm asking for is the review of a particular implementation of the haversine formula, found under: <a href="http://blog.julien.cayzac.name/2008/10/arc-and-distance-between-two-points-on.html" rel="nofollow">http://blog.julien.cayzac.name/2008/10/arc-and-distance-between-two-points-on.html</a> This site is linked under the wikipedia article: <a href="http://en.wikipedia.org/wiki/Haversine_formula" rel="nofollow">http://en.wikipedia.org/wiki/Haversine_formula</a></p> <p>Problem: I get the wrong distance for the points:</p> <pre><code>lat/lon, lat2/lon2 36.987814/-122.107887, 38.989185/-122.116728 </code></pre> <p>I get a distance of 4336622.8812906 (meters) however according to <a href="http://www.movable-type.co.uk/scripts/latlong.html" rel="nofollow">http://www.movable-type.co.uk/scripts/latlong.html</a> it should be about 222.5 km.</p> <p>If somebody could point out the error in this implementation, that would be great:</p> <pre><code>inline double getDist(double *gp) { /// @brief The usual PI/180 constant static const double DEG_TO_RAD = 0.017453292519943295769236907684886; /// @brief Earth's quatratic mean radius for WGS-84 static const double EARTH_RADIUS_IN_METERS = 6372797.560856; double latitudeArc = (gp[0] - gp[2]) * DEG_TO_RAD; double longitudeArc = (gp[1] - gp[3]) * DEG_TO_RAD; double latitudeH = sin(latitudeArc * 0.5); latitudeH *= latitudeH; double lontitudeH = sin(longitudeArc * 0.5); lontitudeH *= lontitudeH; double tmp = cos(gp[0]*DEG_TO_RAD) * cos(gp[2]*DEG_TO_RAD); return EARTH_RADIUS_IN_METERS*2.0 * asin(sqrt(latitudeH + tmp*lontitudeH)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T16:23:36.290", "Id": "19638", "Score": "0", "body": "This is also a good time to point out that your code should compile and run and generate the results you claim. It was a good guess by @acraig but you definitely made the situation harder to solve by not providing compilable working code. Also this is the wrong forum for code that does not work you should have asked this on stackoverflow." } ]
[ { "body": "<p>There's nothing wrong with your implementation. There must therefore be something wrong with how you're declaring or populating <code>gp</code>.\nDoing it like this:</p>\n\n<pre><code>double gp[4] = {36.987814, -122.107887, 38.989185, -122.116728};\nprintf(\"%.6f\\n\", getDist(gp));\n</code></pre>\n\n<p>gives the expected answer of <code>222606.439993</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T09:11:28.300", "Id": "19631", "Score": "0", "body": "thanks a lot for the verification. the problem was further up in the code, with the initialization of gp[0]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T16:21:40.957", "Id": "19637", "Score": "0", "body": "Prefer to use `double gp[] = {/*STUFF*/};` By explicitly leaving the `[]` empty you are asking the compiler to calculate the size of the array based on the initialize. Doing it this way prevents initial counting errors and problems when the array size changes during maintenance." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T07:37:31.913", "Id": "12229", "ParentId": "12227", "Score": "2" } } ]
{ "AcceptedAnswerId": "12229", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T20:56:37.107", "Id": "12227", "Score": "1", "Tags": [ "c++" ], "Title": "Distance calculation implementation" }
12227
<p>My co-worker claims that using a parameterized Like statement is equivalent to dynamic sql and won't have its execution plan cached for reuse. He says that using <code>sp_executesql</code> will allow the execution plan to be cached, increasing the performance of identical searches. However, in the context of this query, the argument doesn't seem to make sense. </p> <p>Any way to prove one way or the other? </p> <pre><code>CREATE PROCEDURE [dbo].[SP_Get_Person] @SearchText varchar(50) AS BEGIN SET NOCOUNT ON; ------------------------------------------------------------------------------------ Declare @SQLString nvarchar(500) Declare @ParmDefinition nvarchar(500) SET @ParmDefinition = N'@SearchText varchar(50)'; SET @SQLString = N'Select * FROM PERSON Where LASTNAME Like ''%'' + @SearchText + ''%'''; EXECUTE sp_executesql @SQLString, @ParmDefinition, @SearchText = @SearchText; ------------------------------------------------------------------------------------ --OR ------------------------------------------------------------------------------------ Select * FROM PERSON Where LASTNAME Like '%' + @SearchText + '%' ------------------------------------------------------------------------------------ END </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T06:12:34.733", "Id": "19629", "Score": "1", "body": "This looks like SQL Server, right? Which version?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T13:29:51.450", "Id": "19635", "Score": "0", "body": "@CheranS - Sql Server 2005" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T14:22:07.617", "Id": "19640", "Score": "1", "body": "Hopefully you will get a good answer, but what stops you from A/B testing it? Properly measuring performance is a very good skill to have. For instance http://stuq.nl/weblog/2009-01-28/why-many-java-performance-tests-are-wrong" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T15:07:07.500", "Id": "19735", "Score": "0", "body": "@Leonid - I took your advice and conducted an experiment. Please see my results below. Any additional comments you may have concerning my conclusions would be appreciated. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T18:07:08.030", "Id": "19807", "Score": "0", "body": "I'm assuming the `EXECUTE...` one isn't vulnerable to SQL Injection, what about your ad-hoc query? (Sorry, I'm not up on how SQL Server handles that type of stuff)." } ]
[ { "body": "<p>According to <a href=\"http://technet.microsoft.com/en-us/library/cc293623.aspx\" rel=\"nofollow noreferrer\">this article</a>:</p>\n<blockquote>\n<p>SQL Server can avoid compilations of previously executed queries by using four mechanisms to make plan caching accessible in a wide set of situations.</p>\n<ul>\n<li><strong>Adhoc query caching</strong></li>\n<li>Autoparameterization</li>\n<li>Prepared queries, using either <strong>sp_executesql</strong> or the prepare and execute method invoked through your API</li>\n<li><strong>Stored procedures</strong> or other compiled objects (triggers, TVFs, etc.)</li>\n</ul>\n</blockquote>\n<p>In other words, both of your examples should fit SQL Server's criteria for query caching, since one is an ad-hoc query that will be textually the same each time it is run, and the other is a prepared query using <code>sp_executesql</code>.</p>\n<p>In addition, it appears that either one would appear in a stored procedure, which itself should have a query execution plan cached. The <code>sp_executesql</code> approach may be slightly slower because it's doing more work to set up the query, but it's possible that SQL Server actually precompiles the call into something that resembles the second query.</p>\n<p><em>As in all cases of optimization, the only way to be sure is to test both approaches against your expected data set.</em></p>\n<p>The second (ad-hoc) query is much more readable, in my opinion. All else being equal, I'd go with that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T15:04:10.343", "Id": "19734", "Score": "0", "body": "In case you're interested, I conducted an experiment based off the information you provided. I have posted it as a follow up answer to my own question. Thanks for your help." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T15:20:25.380", "Id": "12241", "ParentId": "12228", "Score": "2" } }, { "body": "<p>Armed with the <a href=\"http://technet.microsoft.com/en-us/library/cc293623.aspx\" rel=\"nofollow noreferrer\">article</a> and information provided by <a href=\"https://codereview.stackexchange.com/users/2844/striplingwarrior\">@StriplingWarrior</a>, I conducted an experiment and am posting it as an answer to my own question. Please feel free to comment if I have erred in my conclusions. </p>\n\n<h1>Assumptions</h1>\n\n<p>SQL Server can avoid compilations of previously executed queries by using four mechanisms to make plan caching accessible in a wide set of situations.</p>\n\n<ul>\n<li><strong>Adhoc</strong> query caching </li>\n<li>Autoparameterization </li>\n<li>Prepared queries, using\neither <strong>sp_executesql</strong> or the prepare and execute method invoked\nthrough your API </li>\n<li><strong>Stored procedures</strong> or other compiled objects\n(triggers, TVFs, etc.)</li>\n</ul>\n\n<p>SQL Server stores it’s caching plans in a metadata table called sys.dm_exec_cached_plans</p>\n\n<h1>Examining the cache</h1>\n\n<p><strong>LEGEND:</strong></p>\n\n<ul>\n<li><strong>Proc</strong> (Stored procedure) – “By default, the cached plan will be reused for all successive executions…. unlike the plans cached and reused with sp_executesql, you have an option with stored procedures and user-defined scalar functions to force recompilation when the object is executed.”</li>\n<li><strong>Prepared</strong> (Prepared statement) – ”The stored procedure sp_executesql is halfway between adhoc caching and stored procedures. Using sp_executesql requires that you identify the parameters and their datatypes, but doesn’t require all the persistent object management needed for stored procedures and other programmed objects.”</li>\n<li><strong>Adhoc</strong> (Adhoc query) – “…even when SQL Server caches your adhoc queries, you might not be able to depend on their reuse. When SQL Server caches the plan from an adhoc query, the cached plan will be used only if a subsequent batch matches exactly.”</li>\n</ul>\n\n<p><strong>DATA:</strong></p>\n\n<ol>\n<li><p>Determine what caching mechanisms are used outside the context of a stored procedure</p>\n\n<p>Running the attached query <strong>NoStoredProcs.sql</strong> (see Resources section) yields the following results: </p>\n\n<p><img src=\"https://i.stack.imgur.com/S31my.png\" alt=\"Query Results 1\"></p>\n\n<p>You can see that the Query executed with sp_executesql has its query plan cached as a Prepared type while the inline statements were cached as Adhoc types. </p></li>\n<li><p>Determine what caching mechanisms are used within the context of a stored procedure</p>\n\n<p>Running the attached query <strong>WithStoredProcs.sql</strong> (see Resources section) yields the following results:</p>\n\n<p><img src=\"https://i.stack.imgur.com/UhE3T.png\" alt=\"Query Results 2\"></p>\n\n<p>SP_Get_Person1 – Proc &amp; Prepared</p>\n\n<p>SP_Get_Person2 – Proc</p>\n\n<p>SP_Get_Person3 – Proc &amp; Adhoc</p></li>\n</ol>\n\n<p><strong>CONCLUSION:</strong></p>\n\n<p>It would seem that since there was no additional Adhoc cache plan created for <strong>SP_Get_Person2</strong> that its structure can stand on its own (within a Stored Procedure), in terms of database caching. This can be confirmed by the fact that an Adhoc cache plan was created for this query outside the context of the stored procedure, but not when placed inside the stored procedure. </p>\n\n<h1>Performance</h1>\n\n<p><strong>LEGEND:</strong></p>\n\n<ul>\n<li><strong>Client processing time</strong> - The cumulative amount of time that the client spent executing code while the query was executed.</li>\n<li><strong>Total execution time</strong> - The cumulative amount of time (in milliseconds) that the client spent processing while the query was executed, including the time that the client spent waiting for replies from the server as well as the time spent executing code.</li>\n<li><strong>Wait time on server replies</strong> - The cumulative amount of time (in milliseconds) that the client spent while it waited for the server to reply.</li>\n</ul>\n\n<p><strong>DATA:</strong></p>\n\n<p><strong>SP_Get_Person1</strong>\n<img src=\"https://i.stack.imgur.com/yyuCm.png\" alt=\"Query Results 3\"></p>\n\n<p><strong>SP_Get_Person2</strong>\n<img src=\"https://i.stack.imgur.com/C3wQA.png\" alt=\"Query Results 4\"></p>\n\n<p><strong>SP_Get_Person3</strong>\n<img src=\"https://i.stack.imgur.com/1PBzG.png\" alt=\"Query Results 5\"></p>\n\n<p><strong>CONCLUSION:</strong></p>\n\n<p>From the results above, I can only conclude that any performance gains or losses between <strong>SP_Get_Person1</strong> and <strong>SP_Get_Person2</strong> are inconclusive/negligible since the average total execution time consistently differs in terms of microseconds. However, it is interesting to note that the average time for <strong>SP_Get_Person3</strong> is significantly lower. I would strongly caution that this is not necessarily evidence of a reliable performance gain since every search would result in a new Adhoc query (SQL server did not autoparamatarize this query during my tests). Therefore it is inconclusive what the effect of a growing set of Adhoc queries would have on the database. Furthermore, we lose the safety of typed parameters when using this method.</p>\n\n<h1>Resources</h1>\n\n<p><strong>NoStoredProcs.sql</strong></p>\n\n<pre><code>use DemoDatabase\n\ndbcc freeproccache;\nGO\nDECLARE @SearchText varchar(50)\nSET @SearchText = 'Abatemarco'\nSelect * FROM PERSON Where LASTNAME Like '%' + @SearchText + '%' \n\nGO\nDECLARE @SearchText varchar(50)\nSET @SearchText = 'Abatemarco'\nEXECUTE sp_executesql N'Select * FROM PERSON Where LASTNAME Like ''%'' + @SearchText + ''%''', N'@SearchText varchar(50)',\n @SearchText = @SearchText;\n\nGO\nDECLARE @SearchText varchar(50)\nSET @SearchText = 'Abatemarco'\nEXECUTE ( 'Select * FROM PERSON Where LASTNAME Like ''%' + @SearchText + '%''')\n\nGO\nSELECT usecounts, cacheobjtype, objtype, [text]\nFROM sys.dm_exec_cached_plans P\n CROSS APPLY sys.dm_exec_sql_text (plan_handle)\nWHERE cacheobjtype = 'Compiled Plan'\n AND [text] NOT LIKE '%dm_exec_cached_plans%';\n</code></pre>\n\n<p><strong>WithStoredProcs.sql</strong></p>\n\n<pre><code>use DemoDatabase\n\ndbcc freeproccache;\n--DROP PROCEDURE [SP_Get_Person1]\n--DROP PROCEDURE [SP_Get_Person2]\n--DROP PROCEDURE [SP_Get_Person3]\nGO\n\n CREATE PROCEDURE [dbo].[SP_Get_Person1]\n @SearchText varchar(50)\n AS\n BEGIN\n SET NOCOUNT ON;\n EXECUTE sp_executesql N'Select * FROM PERSON Where LASTNAME Like ''%'' + @SearchText + ''%''', N'@SearchText varchar(50)',\n @SearchText = @SearchText;\n END\n\nGO\n\n CREATE PROCEDURE [dbo].[SP_Get_Person2]\n @SearchText varchar(50)\n AS\n BEGIN\n SET NOCOUNT ON;\n Select * FROM PERSON Where LASTNAME Like '%' + @SearchText + '%'\n END\nGO\n\n CREATE PROCEDURE [dbo].[SP_Get_Person3]\n @SearchText varchar(50)\n AS\n BEGIN\n SET NOCOUNT ON;\n EXECUTE ( 'Select * FROM PERSON Where LASTNAME Like ''%' + @SearchText + '%''')\n END\nGO\n\n --SET STATISTICS IO ON\n --SET STATISTICS TIME ON \nGO\n\n Execute [SP_Get_Person1] @SearchText = 'Abatemarco'\n\nGO\n\n Execute [SP_Get_Person2] @SearchText = 'Abatemarco'\n\nGO\n\n Execute [SP_Get_Person3] @SearchText = 'Abatemarco'\n\nGO\n\n --SET STATISTICS IO OFF\n --SET STATISTICS TIME OFF \nGO\n SELECT usecounts, cacheobjtype, objtype, [text]\n FROM sys.dm_exec_cached_plans P\n CROSS APPLY sys.dm_exec_sql_text (plan_handle)\n WHERE cacheobjtype = 'Compiled Plan'\n AND [text] NOT LIKE '%dm_exec_cached_plans%';\n</code></pre>\n\n<h1>Tools</h1>\n\n<p>Statistics were gathered using the <strong>Include Client Statistics</strong> button in SQL Server Management Studio. Only the last 10 query results are stored and averaged. The results can be cleared from the menu: <strong>Query</strong> -> <strong>Reset Client Statistics</strong>.</p>\n\n<p><img src=\"https://i.stack.imgur.com/cgSeE.jpg\" alt=\"Client Statistics Button\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/yJ2Xg.jpg\" alt=\"Client Statistics Tab\"> </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T16:05:03.230", "Id": "19737", "Score": "2", "body": "Nicely done. What I find particularly interesting is that `SP_Get_Person3` appeared to do better on *every* trial run. If its performance gain was due to caching the entire query, I would have expected it to take as long as the others on at least the first trial run. Did you clear the query cache before starting the test? I'd also be curious to see how the performance would compare if you used a different search string for each test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T17:22:04.367", "Id": "19742", "Score": "0", "body": "Very cool indeed. I do not have anything to add at this point other than a question - which tools did you use to get that cool summary and how?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T17:58:18.893", "Id": "19745", "Score": "0", "body": "Thanks @Leonid - See my edit above. I added a section for the tools." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T14:59:22.033", "Id": "12297", "ParentId": "12228", "Score": "4" } } ]
{ "AcceptedAnswerId": "12241", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T21:05:40.967", "Id": "12228", "Score": "2", "Tags": [ "optimization", "performance", "sql", "sql-server" ], "Title": "Which SQL statement is faster" }
12228
<p>I originally made this as a way to use character strings as a base-256 number, but then realized that I could turn it into a method for encryption instead. The only thing is that since I'm using a basic addition algorithm for the encryption process, I'm iterating through a string by one character at a time (which seems kind of slow). Are there any other ways to improve the performance of this process or am I pretty much stuck with simple iteration?</p> <p>Here's the encryption code:</p> <pre><code>void encodeStr(string encryptKey, string&amp; inputToEncrypt) { assert(minVal &lt; maxVal); if (inputToEncrypt.length() == 0) return; //preliminary remainder check initialization int remainder = minVal; //zero value int keyNumCount = 0; int keyCount = 0; //variables used to determine when to stop counting numbers size_t keyPos = 0; size_t count = 0; size_t countEnd = inputToEncrypt.length(); //begin numerical addition. stop once the end of both strings is reached while (count &lt; countEnd) { //convert current characters to unsigned chars keyNumCount = encryptKey[keyPos]; if (keyNumCount &lt; minVal) keyNumCount += minVal; keyCount = (count &lt; inputToEncrypt.length()) ? inputToEncrypt[count] : 0; if (keyCount &lt; minVal) keyCount += minVal; //take advantage of signed-char overflow to calculate current value remainder += keyNumCount + keyCount; inputToEncrypt[count] = remainder; //check if there is a remainder to be tabulated remainder = (remainder &gt; maxVal) ? 1 : 0; ++count; ++keyPos; if (keyPos == encryptKey.size()) keyPos = 0; //add 1 to the count if there is a remainder at the end of keyNum if (count == countEnd &amp;&amp; remainder != 0) { inputToEncrypt.push_back('\0'); ++countEnd; //variables used to avoid integer overflow } } } </code></pre> <p>And the decryption function:</p> <pre><code>void decodeStr(string decryptKey, string&amp; inputToDecrypt) { assert(minVal &lt; maxVal); if (inputToDecrypt.length() == 0) return; //preliminary remainder check initialization int remainder = minVal; int keyNumCount = 0; int keyCount = 0; //variables used to determine when to stop counting numbers size_t keyPos = 0; size_t count = 0; size_t countEnd = inputToDecrypt.length(); //make sure the program exits before the number necomes negative while (count &lt; countEnd) { //convert current characters to unsigned chars keyNumCount = decryptKey[keyPos]; if (keyNumCount &lt; minVal) keyNumCount += minVal; keyCount = inputToDecrypt[count]; if (keyCount &lt; minVal) keyCount += minVal; //take advantage of signed-char overflow to calculate current value remainder += keyCount - keyNumCount; inputToDecrypt[count] = remainder; //check if there is a remainder to be tabulated remainder = (remainder &gt; maxVal) ? 1 : 0; ++count; ++keyPos; if (keyPos == decryptKey.size()) keyPos = 0; } } </code></pre>
[]
[ { "body": "<p>Since you key is const it would be nice to mark it as such (and avoid accidents of changing your key):</p>\n\n<pre><code>void encodeStr(string const&amp; encryptKey, string&amp; inputToEncrypt) {\n// ^^^^^\n</code></pre>\n\n<p>To save the cost of the copy I would also make it a reference.</p>\n\n<p>No idea what these are:</p>\n\n<pre><code>assert(minVal &lt; maxVal);\n</code></pre>\n\n<p>The extra set of variables seems like a good idea but actually makes the code harder to read as you need to understand what the variable represents:</p>\n\n<pre><code>size_t countEnd = inputToEncrypt.length();\nwhile (count &lt; countEnd) {\n\n// Simpler to\n\nwhile (count &lt; inputToEncrypt.length()) {\n</code></pre>\n\n<p>When is this condition every going to fail and give you 0?</p>\n\n<pre><code>keyCount = (count &lt; inputToEncrypt.length()) ? inputToEncrypt[count] : 0;\n</code></pre>\n\n<p>If it was going to fail then you should have the same precautions on this:</p>\n\n<pre><code>inputToEncrypt[count] = remainder;\n</code></pre>\n\n<p>This is also bound to result in truncation of reminder. As <code>inputToEncrypt</code> as a string and thus each position is a <code>char</code> while remainder is the sum of 2 integers both greater than <code>minval</code>.</p>\n\n<pre><code>inputToEncrypt[count] = remainder;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T18:20:30.260", "Id": "19643", "Score": "0", "body": "Thanks for the help. The first two things you pointed out were remnants of when I was debugging. The \"keycount\" variable is used to determine what character in the encryption key should be used to do the encrypting. If the thing you want to encrypt is longer than the encryption key, then the encryption key becomes repeated." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T03:59:57.077", "Id": "12236", "ParentId": "12233", "Score": "5" } }, { "body": "<p>If you're only interested in implementing this <em>specific</em> form of encryption, then what I'm going to post is almost certainly overkill. On the other hand, if you want to play around with different forms of encryption, it may be interesting. This attempts to factor the the job into a few distinct pieces. I'm not sure it entirely succeeds at doing that, but perhaps the attempt will be interesting anyway.</p>\n\n<p>First, a little tool that's probably useful for a fair number of algorithms like this: a cyclic_iterator that provides an imitation of an infinite-length input by cycling through a finite-length input as often as needed. Right now, this is quite (excessively?) minimal -- for example, it doesn't even attempt to deal with post-increment, only pre-increment.</p>\n\n<pre><code>#ifndef CYCLIC_ITERATOR_H_INC_\n#define CYCLIC_ITERATOR_H_INC_\n#include &lt;iterator&gt;\n\ntemplate &lt;class FwdIt&gt;\nclass cyclic_iterator_t : public std::iterator&lt;std::input_iterator_tag, typename FwdIt::value_type&gt; {\n FwdIt begin;\n FwdIt end;\n FwdIt current;\npublic:\n cyclic_iterator_t(FwdIt begin, FwdIt end) : begin(begin), end(end), current(begin) {}\n\n cyclic_iterator_t operator++() { \n if (++current == end) \n current = begin; \n return *this; \n }\n typename FwdIt::value_type operator *() const { return *current; }\n};\n\ntemplate &lt;class Container&gt;\ncyclic_iterator_t&lt;typename Container::iterator&gt; cyclic_iterator(Container &amp;c) { \n return cyclic_iterator_t&lt;typename Container::iterator&gt;(c.begin(), c.end());\n}\n\n#endif\n</code></pre>\n\n<p>Then a little program to implement something that's at least similar to your algorithm (I couldn't regression test, because you didn't specify you <code>minVal</code>, among other things). It currently makes no attempt at dealing sensibly with negative inputs either. </p>\n\n<pre><code>#include &lt;limits.h&gt;\n#include &lt;vector&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;algorithm&gt;\n\n#include \"cyclic_iterator.h\"\n\n// first a class to encrypt one character at a time:\n// \nclass encrypt { \n bool carry;\npublic:\n encrypt() : carry(0) {}\n char operator()(char ina, char inb) { \n int ret = ina + inb + static_cast&lt;int&gt;(carry);\n carry = ret &gt; CHAR_MAX;\n return ret % CHAR_MAX;\n }\n operator bool() { return carry; }\n};\n\n// Then a little algorithm to apply that encryptor to an entire string of input:\n// \ntemplate&lt;class InIt1, class InIt2, class OutIt&gt;\nvoid encode_string(InIt1 begin1, InIt1 end1, InIt2 begin2, OutIt result) { \n encrypt e;\n // The main loop is almost like two-input std::transform:\n while (begin1 != end1) {\n *result = e(*begin1, *begin2);\n ++result;\n ++begin1;\n ++begin2;\n }\n // but then we handle the \"carry\" bit (if any):\n if (e)\n *result++ = '\\0';\n}\n\n// finally a simple main to test out the preceding: \nint main() {\n std::string input(\"This is some text\");\n std::string key(\"TheKey\");\n std::string result;\n\n encode_string(input.begin(), input.end(), cyclic_iterator(key), std::back_inserter(result));\n std::cout &lt;&lt; result;\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T05:45:32.597", "Id": "12257", "ParentId": "12233", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T19:04:57.270", "Id": "12233", "Score": "5", "Tags": [ "c++", "optimization", "cryptography" ], "Title": "Simple encryption algorithm" }
12233
<p>I'm just starting to experiment with F# (from a C# background). I think I'm starting to get into the right way of thinking, but this code still seems pretty awkward. Is there a better (more terse) way to accoAny comments appreciated. (BTW, this is supposed to sum all even fibonacci numbers up to 4,000,000)</p> <pre><code>let rec fib x y max acc = let z = x + y if z &lt; max then if z%2=0 then fib y z max (z + acc) else fib y z max acc else acc let result = fib 1 2 4000000 2 printfn "%d" result </code></pre>
[]
[ { "body": "<p>I think the solution reads better if you separate concerns a bit more instead of rolling it all into one mega function.</p>\n\n<p>For instance, with these helper functions (that each do one—and only one—thing):</p>\n\n<pre><code>let fib =\n Seq.unfold\n (fun (cur, next) -&gt; Some(cur, (next, cur + next)))\n (0I, 1I)\n\nlet isEven n = n % 2I = 0I\n</code></pre>\n\n<p>you can express the solution at a high level (almost at the level you would explain it in words!):</p>\n\n<pre><code>fib //given the set of fibonacci numbers\n|&gt; Seq.filter isEven //take those that are even\n|&gt; Seq.takeWhile (fun n -&gt; n &lt;= 4000000I) //not exceeding 4,000,000\n|&gt; Seq.sum //and sum them\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T18:29:26.563", "Id": "19687", "Score": "0", "body": "Cool. I like that. I'm going to read up on Seq.unfold." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T16:29:12.963", "Id": "12269", "ParentId": "12235", "Score": "3" } } ]
{ "AcceptedAnswerId": "12269", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T23:33:11.363", "Id": "12235", "Score": "3", "Tags": [ "project-euler", "f#", "fibonacci-sequence" ], "Title": "Euler 2 : Simple Fibonacci" }
12235
<p>I whipped this up last night and was wondering if anyone had any thoughts/comments on it; for example, on:</p> <ul> <li>Code organisation</li> <li>Coding style</li> <li>Other improvements</li> <li>Semantic errors</li> </ul> <p></p> <pre><code>(ns tictactoe.core) (comment " Author: Liam Goodacre Date: 03/06/12 This module allows the creation and progression of tictactoe games. To create a game, use the make-game function: (make-game) A game is a map with the following data: :play-state :playing | :player1 | :player2 | :draw :level-state [:player1|:player2|nil] :scores {:player1 Int, :player2 Int, :draw Int} :turn :player1 | :player2 | :none If the game isn't over, play-state is :playing. If play-state is :player1 or :player2, this indicates that that player won. If play-state is :draw, then the game completed with no winner. level-state is a vector or nine elements. An empty cell has the value of nil. If a player uses a cell, then the cell has that player's id. E.g., if a player1 uses an empty cell, that cell now has the value :player1 scores is a map from ids to integers. It includes score values for draws and for the two players. When the game is over, turn is :none. Otherwise, it describes which player's turn it is. When a new game is created, turn is randomised between the two players. To play a turn, use the play-turn command. For example, assuming 'g' is a predefined game: (play-turn g 2) Will produce a new game state with play progressed by one move, in which the current player used cell 2. Calling new-game clears the level data of a game and randomises the initial player turn. Scores are the only preserved datum. The following are game analysis functions: get-play-state - what state of play are we in? get-turn - whos turn is it? get-scores - get the scores get-level-state - get the state of the level playing? - are we still playing? game-over? - is the game over? valid-move? - is this a valid move? ") (declare ;; Public Functions ; Game Transforming make-game new-game play-turn ; Game Analysing get-play-state get-turn get-scores get-level-state playing? game-over? valid-move? ; Extra get-game-grid) (declare ;; Private Functions ^:private ; Transforming apply-move next-turn recalculate-state ; Analysis calculate-winner try-combination) ;; Utility functions (defmacro ^:private def- " A private version of def. " [&amp; info] `(def ^:private ~@info)) (defn- within-range " Determines if a value lies within an inclusive range. " [n x] (fn [v] (and (&gt;= v n) (&lt;= v x)))) ;; Initial data for making new games (def- players [:player1, :player2]) (def- initial-play-state :playing) (def- initial-level-state (vec (repeat 9 nil))) (def- initial-scores {:player1 0, :player2 0, :draw 0}) (defn- random-turn [] (players (int (rand 2)))) (def- winning-combinations [[1 2 3][4 5 6][7 8 9][1 5 9][3 5 7][1 4 7][2 5 8][3 6 9]]) ;; Public Transforming Functions (defn make-game [] " Creates a new game object. " { :play-state initial-play-state :level-state initial-level-state :scores initial-scores :turn (random-turn) }) (defn new-game [g] " Sets up a game object for the next play. " (assoc (make-game) :scores (get-scores g))) (defn play-turn [game move] " Progresses game-play by one move if possible. " (if (and (playing? game) (valid-move? game move)) (-&gt; game (apply-move move) (recalculate-state) (next-turn)) game)) ;; Private Transforming Functions (defn- apply-move [game move] " Progresses game-play by one move. " (assoc game :level-state (assoc (get-level-state game) move (get-turn game)))) (defn- next-turn [game] " Updates which player should play next. If no player is currently active, then do not switch. " (assoc game :turn (case (get-turn game) :none :none :player1 :player2 :player2 :player1))) (defn- recalculate-state [game] " Calculate if there is a winner. If so update the play-state, turn, and scores; to reflect the result. " (let [winner (calculate-winner game) scores (get-scores game)] (if (= winner :none) game (-&gt; game (assoc :play-state winner, :turn :none) (update-in [:scores winner] inc))))) ;; Private Analysis Functions (defn- calculate-winner [game] " Calculates if there is a winner. " (let [state (get-level-state game) matching (partial try-combination state)] (if (some matching winning-combinations) (get-turn game) (if (some nil? state) :none :draw)))) (defn- try-combination [state [one two three]] " Calculates if a winning combination has occurred. " (let [lookup (comp (partial nth state) dec) player (lookup one)] (and (not= player nil) (= player (lookup two) (lookup three))))) ;; Public Analysis Functions (def get-play-state :play-state) (def get-turn :turn) (def get-scores :scores) (def get-level-state :level-state) (defn playing? [game] (= :playing (get-play-state game))) (def game-over? (comp not playing?)) (defn valid-move? [game move] (and ((within-range 0 8) move) (nil? (nth (get-level-state game) move)))) ;; Public Extra Functions (defn get-game-grid [g] " Builds a simple string representation of the current level state. " (clojure.string/join "\n" (map vec (partition 3 (get-level-state g))))) </code></pre>
[]
[ { "body": "<p>I would put the long <code>(comment ...)</code> as the namespace's docstring. In fact, I would split that in docstrings because you're essentially describing the system by parts in a centralized place, while you could describe it in each part. I would keep the overall \"how this game/namespace works/is organized\" in namespace's docstring.</p>\n\n<p>Declare is meant for forward declarations, not to expose functions (that's what you're doing there, right?) I didn't see it used like that anywhere, but I like the idea!</p>\n\n<p><code>(not= player nil)</code> is just <code>player</code>!</p>\n\n<p>In <code>next-turn</code> I would just use a map instead of case (you're essentially mapping, right?)</p>\n\n<pre><code>(defn- next-turn [game]\n (assoc game :turn\n ((get-turn game)\n {:none :none ;; I haven't seen spacing to match vertically used too much, but I don't really dislike it\n :player1 :player2\n :player2 :player1})) ;; Or the other way around `(the-map (get-turn game))`\n</code></pre>\n\n<p>IMHO, this isn't very idiomatic:</p>\n\n<pre><code>(def get-play-state :play-state)\n...\n</code></pre>\n\n<p>Aren't you better off using :play-state directly? It offers no encapsulation or maintainability whatsoever (am I right guessing this came from an OOP-like mindset?) And you lose information: the fact that <code>:play-state</code> is a keyword. I guess you did it to expose the analysis functions, right? You're better off mentioning the acceptable keywords in the documentation for your public <code>make-game</code>. I would use either <code>(:play-state game)</code> or <code>(game :play-state)</code> (the second will throw a <code>NullPointerException</code> if game is <code>nil</code>, which isn't bad per se.)</p>\n\n<p>This is obviously style but: same goes for <code>Initial data for making new games</code>. I would shove that data directly into the <code>make-game</code>. It'd be already obvious for me that those are the initial states (since you're just bulding a map!)</p>\n\n<p>The code is pretty good. I didn't even read the long documentation text and got how it works in a quick glance. I had some troyble understanding how <code>try-combination</code> works (consider making it more readable) but unfortunately I'm a bit in a hurry. I'll come back later and review that too (consider \"not easily readable\" my review at the moment.)</p>\n\n<p>That's my humble opinion. The rest is pretty good.</p>\n\n<h1>EDIT</h1>\n\n<p>(answer to comment)</p>\n\n<p>@LiamGoodacre that's what I thougth. Clojure favors universal (i.e. reusable) behavior for types instead of \"interface tied to type\", so it's just the other way around compared to OOP where data and actions are heavily tied.</p>\n\n<p>Don't disregard the docstring tips either. Try <code>(doc function-or-namespace)</code> in a REPL to see how important is to have documentation tied to functions/namespaces instead of spread throughout the code or in <code>(comment ...)</code> forms. Documentation generation tools use this metadata too, so it's generally a good idea to do this.</p>\n\n<p>I had a hard time grasping <code>try-combination</code>. Consider reworking it a bit, or maybe just add some more info to the docstring like what's <code>[one two three]</code>. The current dosctring is not every useful, I know what the functions does just by reading the name... it tries combinations, and <code>\"Calculates if a winning combination has occurred.\"</code> is just a fancy way of saying <code>it tries combinations</code>.</p>\n\n<p>This is just a matter of style, but I dislike heavy use of <code>partial</code>, <code>comp</code>, etc. and would prefer <code>#(nth state (dec %))</code>. I think it's easier to read. I also prefer <code>[a b c]</code> or <code>[x y z]</code> to <code>[one two three]</code>. I had a hard time following you were just destructuring a simple array instead of getting some special values that deserved the long <code>one</code>, <code>two</code>, <code>three</code> names :)</p>\n\n<p>Why don't you return the winner in <code>try-combination</code>? Do it like this:</p>\n\n<pre><code>(defn- try-combination [state [x y z]]\n (let [lookup #(nth state (dec %))\n player (lookup x)]\n (and (= player\n (lookup y)\n (lookup z))\n player)))\n</code></pre>\n\n<p>That way, calculate-winner could return the actual winner and not just the current player, being more correct and reusable IMHO, also allowing you to decouple it from the <code>game</code> and just depending on the current <code>state</code> (e.g. what if you need it later to show the winner in a GUI for recorded games where you only have the final <code>:level-state</code>?)</p>\n\n<pre><code>(defn- calculate-winner [state]\n (let [matching (partial try-combination state)\n winner (find matching winning-combinations)]\n (or winner ; Short-circuit logic is cool for these tricks and VERY readable\n (and (some nil? state)\n :none)\n :draw))))\n</code></pre>\n\n<p>The more decoupled your functions are, the more reusable. Try working with the bare minimum data structures in a single function, instead of using complex maps.</p>\n\n<p>I would also use a <code>defrecord</code> to define your <code>game</code> data structure.</p>\n\n<pre><code>(defrecord Game [play-state level-state scores turn])\n</code></pre>\n\n<p>Instance <code>Game</code>s like any other Java class, e.g. for <code>make-game</code> :</p>\n\n<pre><code>(Game.\n initial-play-state\n initial-level-state\n initial-scores\n (random-turn))\n</code></pre>\n\n<p>The good thing: the map interface is still there!</p>\n\n<p>IMHO, it offers some benefits: actually encapsulating the tightly coupled structures into an actual object (is there any benefit in the game being a simple map?), the map keys are \"documented\" as the record args and you can add interfaces to this object. E.g.: you could get rid of <code>get-game-grid</code> and implement it as <code>java.lang.Object</code>'s <code>toString</code>, so you could do <code>(str game)</code> and get <code>game</code>'s grid (a nice feature IMHO.)</p>\n\n<p>You can also add customs <a href=\"http://clojure.org/protocols\" rel=\"nofollow\">protocols</a> to these records to encapsulate the tightly coupled interfaces to your <code>Game</code> object (your <code>Public Analysis Functions</code>, although I would discard most of that.) Please note this is very OOP-y and should be kept to a minimum.</p>\n\n<p>Finally: why bother defining functions as private? Screw encapsulation! You'll eventually need these functions outside your namespace for random uninentended tasks (specially if outside people interface with your game, it'd be a cool tic-tac-toe library), so keep these to a minimum (usually helper functions or functions that are tightly coupled with your namespace inner workings.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-24T22:34:37.820", "Id": "22622", "Score": "0", "body": "Cheers for all the pointers. My main goal with aliasing the keywords (for example :play-state as get-play-state) was to keep a consistant interface with the game: e.g. game-over? is a function, whereas :play-state is a keyword. Having said that, I now see some benefits to reverting these to keywords: play-state is game data, whereas game-over? is a calculated field." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-05T16:05:34.763", "Id": "23225", "Score": "0", "body": "@LiamGoodacre you're welcome :) I did a heavy edit commenting on the issue and adding some more tips after grasping `try-combination`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-14T10:51:02.680", "Id": "13658", "ParentId": "12238", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T07:55:07.387", "Id": "12238", "Score": "7", "Tags": [ "functional-programming", "tic-tac-toe", "clojure", "lisp" ], "Title": "Clojure TicTacToe (logic, no GUI)" }
12238
<p>I would like to know how I could improve my C# project. I'm not really sure whether or not I'm allowed to just post a link to the Google Code project here, so sorry if it's not allowed, I'll edit my question if someone tells me so.</p> <p><a href="http://code.google.com/p/simple-irc/source/browse/#svn%2Ftrunk" rel="nofollow">http://code.google.com/p/simple-irc/source/browse/#svn%2Ftrunk</a></p> <p>The reason I'm posting the entire project is because I would like to know if there's anything I can improve coding-wise (coding conventions I'm missing or misusing?), structural-wise (should anything be restructured, do I need to split it up in different classes etc?) and document-wise (how should I document my variables, methods, etc?).</p> <p><strong>Edit</strong>: Maybe I should explain a few things to save anyone who reads this some time. The project is split up in three "modules". The UI part of the application is in the "Source" folder, the core IRC library is in the "Library" folder and any plugins (that the UI module may load) are in the "Plugins" folder.</p> <p><strong>Edit2</strong>: I'll edit my question as a reply to the replies, this is a picture of the application: <a href="http://matthias.van-eeghem.com/data/simpleIRC.png" rel="nofollow">http://matthias.van-eeghem.com/data/simpleIRC.png</a></p> <p>This is a small bit of code (as I apparently have to include that according to the FAQ):</p> <pre><code>/// &lt;summary&gt; /// Called when the client receives the your hostName is event /// &lt;/summary&gt; /// &lt;param name="serverIndex"&gt;The server index&lt;/param&gt; /// &lt;param name="hostName"&gt;The displayed hostName&lt;/param&gt; private void OnDisplayedHostReceived(int serverIndex, string hostName) { string Output = "Your displayed hostName is: " + hostName + "\r"; Core.ServerList[serverIndex].Logger.Log(Output); ServerWindow.List[serverIndex].SendText(Output); foreach (PluginInterface Plugin in MainWindow.PluginList) if(Plugin != null) Plugin.OnDisplayedHostReceived(serverIndex, hostName); } /// &lt;summary&gt; /// Called when the server sends all the commands supported to the client /// &lt;/summary&gt; /// &lt;param name="serverIndex"&gt;The index of the server&lt;/param&gt; /// &lt;param name="commandsSupported"&gt;The list of the commands supported&lt;/param&gt; private void OnCommandsSupportedReceived(int serverIndex, string commandsSupported) { string Output = "Supported: " + commandsSupported + "\r"; Core.ServerList[serverIndex].Logger.Log(Output); ServerWindow.List[serverIndex].SendText(Output); foreach (PluginInterface Plugin in MainWindow.PluginList) if(Plugin != null) Plugin.OnCommandsSupportedReceived(serverIndex, commandsSupported); } /// &lt;summary&gt; /// Called when the client times out from the server /// &lt;/summary&gt; /// &lt;param name="serverIndex"&gt;The serverIndex&lt;/param&gt; private void OnClientTimeout(int serverIndex) { Server Server = Core.ServerList[serverIndex]; // Could not resolve hostName string Output = "* Lost connection to " + Server.Hostname + "\r"; Core.ServerList[serverIndex].Logger.Log(Output); ServerWindow.List[serverIndex].SendText(Output); Output = "* Trying to reconnect..\r"; Core.ServerList[serverIndex].Logger.Log(Output); ServerWindow.List[serverIndex].SendText(Output); // Loop through all channels for (int i = 0; i &lt; Core.ChannelList.Count; i++) { Channel Channel = Core.ChannelList[i]; if(Channel != null &amp;&amp; Channel.Server != null) { if (Channel.Server.Index == serverIndex) { Output = "* Lost connection to " + Server.Hostname + "\r"; Core.ServerList[serverIndex].Logger.Log(Output); ChannelWindow.List[i].SendText(Output); } } } // Try reconnecting Server.Connect(); foreach (PluginInterface Plugin in MainWindow.PluginList) if(Plugin != null) Plugin.OnClientTimeout(serverIndex); } </code></pre> <p>I'd love any feedback for this code specifically but I'd also appreciate any comments in regards to the entire project structure etc.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T21:29:57.110", "Id": "19645", "Score": "0", "body": "Can we see some pics?" } ]
[ { "body": "<p>One thing I noticed at a glance is that the main window code-behind is doing a lot of work that isn't really UI-focused. For example, the code to handle loading plugins from external DLLs is not something I would expect a Window subclass to do. I would highly recommend restructuring the application to utilize pattern that helps you to break things up into more single-purpose classes.</p>\n\n<p>A good example of a pattern that I use often is <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter\" rel=\"nofollow\">Model-View-Presenter</a>, or MVP. A more common pattern in WPF projects is <a href=\"http://en.wikipedia.org/wiki/Model_View_ViewModel\" rel=\"nofollow\">Model-View-ViewModel</a>, or MVVM.</p>\n\n<p>The separation of view logic from business logic makes the application more modular, allowing you to swap out components more easily. For example, if you decide later that a different UI technology (e.g., HTML/Javascript Metro) is more to your liking, you just need to swap out the view.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T20:18:11.327", "Id": "19692", "Score": "0", "body": "Thank you for your time! I'll do the coding as soon as I get some time on my hands." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T18:54:06.017", "Id": "12275", "ParentId": "12239", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T12:51:54.210", "Id": "12239", "Score": "2", "Tags": [ "c#", "wpf" ], "Title": "C# based IRC application (with WPF as UI)" }
12239
<p>At the moment, I have this code:</p> <pre><code>(function() { var lastSelectedIndex = -1; function onSelTypeSelected() { // #selType is a &lt;select&gt; tag // var selType = document.getElementById("selType"); var selType = this; // finished(onSuccess, onError) loader.finished(function(data) { lastSelectedIndex = selType.selectedIndex; }, function(err) { selType.selectedIndex = lastSelectedIndex; }); } })(); </code></pre> <p>So <code>lastSelectedIndex</code> is not in the global context, however I want to put it <s>into <code>eventListener()</code>'s context.</s> inside <code>eventListener()</code>, so you can't access it in the outer anonymous function. That's cleaner in my opinion and also faster (okay, a few nanoseconds) because of the scope chains hierarchy (<a href="http://www.youtube.com/watch?v=mHtdZgou0qU&amp;feature=player_detailpage#t=790s">Google Tech Talk: Speed Up Your JavaScript</a> is a good introduction).</p> <p>I thought of adding a property to the function (as I learnt <a href="http://ejohn.org/apps/learn/#19">here</a>) but I don't have access to <code>eventListener()</code> in the anonymous functions.</p> <p>The next idea I had was to use HTML 5 <code>data-*</code> attributes:</p> <pre><code>function onSelTypeSelected() { // #selType is a &lt;select&gt; tag // var selType = document.getElementById("selType"); var selType = this; // finished accepts two arguments: onSuccess and onError loader.finished(function(data) { selType.setAttribute("data-lastIndex", selType.selectedIndex); }, function(err) { selType.selectedIndex = selType.getAttribute("data-lastIndex"); }); } </code></pre> <p>(The default value for <code>data-lastIndex</code> will be set in the HTML Markup)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T22:49:24.310", "Id": "19650", "Score": "0", "body": "The code already works. `lastSelectedIndex` is already in `eventListener`'s context, because they are declared at the same scope." } ]
[ { "body": "<p><code>lastSelectedIndex</code> is already visible from eventListener. It is in fact visible from everywhere inside the immediately invoked anonymous function.</p>\n\n<p>Try putting <code>console.log(\"lastSelectedIndex is\", lastSelectedIndex);</code> in there and you'll see.</p>\n\n<p>This is due to the concept of <a href=\"https://developer.mozilla.org/en/JavaScript/Guide/Closures\" rel=\"nofollow\">closures</a> which in technical-ish terms means that when a variable is not found inside a function's context, it looks in the parent context (the context the function was in when created) and so on all the way up to the window object. In plain-english terms this means that you should forget all your Java/C#/Php training and the variables visible inside a function are exactly those that you intuitively think should be.</p>\n\n<p>That being said, there is going to be only one instance of <code>lastSelectIndex</code> for this block of code, so if the <code>eventlistener</code> is ever attached to more than a single element all instances of the listener will be referencing the same <code>lastSelectIndex</code>.</p>\n\n<p>There are plenty of ways to skin this cat and you really did not give enough details on what your trying to achieve to give advice on best practices but let me try to give some advice anyways</p>\n\n<ul>\n<li>DO the simplest thing that can possibly work first</li>\n<li>DON'T name your functions after how they're used (eventlistner)</li>\n<li>DO name your functions after what they do</li>\n<li>DON'T use data- attributes directly. Use a library like jquery, at the very least use <a href=\"https://developer.mozilla.org/en/DOM/element.dataset\" rel=\"nofollow\">element.dataset</a> to retrieve them, though keep in mind the data api is not available in all browsers (which libraries handle for you)</li>\n<li><p>CONSIDER having everything set up in response to a user action that triggers it so in pseudocode, the following would be all inline (and with js can be written gracefully and very compact).</p>\n\n<p>when the user changes the option\n memoize the previous value\n query the server\n on success continue\n on error restore the previous value</p></li>\n<li><p>Finally, if you do this more than a few times, CONSIDER coming up with an abstraction (possibly a custom control) for this pattern so you don't have to do it every time</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T07:46:03.763", "Id": "19662", "Score": "0", "body": "Thanks for your answer. I have changed the names and other things in my code in order to simplify it here (e.g. the event listener is called `onSelTypeSelected`). What I wanted to achieve was to put `lastSelectedIndex` inside the event listener so you can't access it from the outer function. This will be an app for Windows 8 (IE 10 supports *dataset*) ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T17:39:16.277", "Id": "19686", "Score": "0", "body": "@ComFreek `onSelTypeSelected` is still a name indicating how you're using it, not what it does. What it does seems to merit more a name like `setupLoader`. A good rule of thumb whenever you name a function is to forget how you're using it and look at it in isolation - imagine other uses that it could be put to and see if the name still makes sense.If you only describe what the function ''does'' then it will. And yes, I know the onNounVerbed thing has been pushed by MS demos, I've talked to lots of MS people - they hate that convention too :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T15:32:17.233", "Id": "19736", "Score": "0", "body": "The function also displays the loaded data, so what do you think about `loadAndShowType`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T16:26:45.520", "Id": "19739", "Score": "0", "body": "@ComFreek Yeah that sounds more like it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T03:22:59.437", "Id": "12256", "ParentId": "12246", "Score": "7" } } ]
{ "AcceptedAnswerId": "12256", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T16:19:23.190", "Id": "12246", "Score": "7", "Tags": [ "javascript" ], "Title": "Store variables function-wide and access them in an anonymous function" }
12246
<p>As a part of picking up <a href="http://en.wikipedia.org/wiki/Concatenative_programming_language">concatenative programming</a>, I decided to implement the common concatenative operations in PostScript. Here is my attempt at implementing some of the <a href="http://www.latrobe.edu.au/phimvt/joy/html-manual.html">words</a> in other concatenative languages in PostScript. Would any one who is familiar with PostScript and functional/concatenative programming comment on my code?</p> <pre><code>%!PS % conventions: parameter names with let begins with . % basic definition, makes the definitions less verbose. /. {bind def} bind def /' {load} bind def /reverse {{} exch {exch [3 1 roll aload pop]} forall}. /let {dup length dict begin reverse {exch def} forall}. /let* {reverse {exch def} forall}. % some predicates. /eq? {eq}. /list? {dup type /arraytype eq?}. /leaf? {list? not}. /empty? {dup length 0 eq?}. /zero? {dup 0 eq?}. % stacky functions /rup {3 1 roll}. /rdown {3 -1 roll}. /# {exch dup rdown .makeoperator bind def} bind def /getname {dup 0 get exch}. /getbody {dup length 1 sub 1 exch getinterval}. % convenience arithmetic /+ {add}. /- {sub}. /* {mul}. /\ {div}. % lispy functions /first {0 get}. /car {first}. /!first {dup first}. /rest {dup length 1 sub 1 exch getinterval}. /cdr {rest}. /!rest {dup rest}. /head {dup length 1 sub 0 exch getinterval}. /!head {dup head}. /tail {dup length 1 sub get}. /!tail {dup tail}. /cons {[rup aload pop]}. /tadd {[rup aload length 1 add -1 roll] }. /uncons {getname getbody}. /concat {exch [ rup aload pop counttomark -1 roll aload pop ] }. % make a unit list. /unit {1 array astore cvx}. /succ {1 add}. /pred {1 sub}. /range {[rup exch aload pop rup exch rdown {} for]}. % higher order thingies. /map { [ rup forall ] }. % [1 2 3 4] {1 add} map /fold {rup exch rdown forall}. %/reverse {{} {exch cons} fold}. % {} [1 2 3 4 5] {exch cons} forall % [1 2 3 4] 0 {+} fold % name - filter is taken so we are left with.. /find { 4 dict begin /aif {0 /get /if}. /atox { [ exch cvx {cvx} forall ] cvx}. [ rup [ /dup rdown /exec /not [{pop}] aif ] atox forall ] end}. /transpose { [ exch { { {empty? exch pop} map all?} {pop exit} ift [ exch {} {uncons {exch cons} dip exch} fold counttomark 1 roll] uncons } loop ] {reverse} map }. /zip {[rup] transpose}. /all? { { {empty?} ? {pop true exit} if uncons {?} dip exch not {pop false exit} if } loop }. /any? { { {empty?} ? {pop false exit} if uncons {?} dip exch {pop true exit} if } loop }. /pipe { { {empty?} ? {pop exit} if uncons {i} dip } loop }. % 1 {{2 *} {3 *} {5 *}} pipe /collect { { {empty?} ? {pop exit} if uncons {?} dip } loop }. % 1 {{2 *} {3 *} {5 *}} collect /? { 4 dict begin [/.pred] let* count array astore /.stack exch def /_restore {clear .stack aload pop}. .stack aload pop .pred /.top exch def _restore .top end}. % control structures /ift { [/.if /.then] let /.if ' ? /.then ' if end}. /ifte { [/.if /.then /.else] let /.if ' ? /.then ' /.else ' ifelse end}. % switch statement. /is? {{exit} concat cvx ift}. /cond {{exit} concat cvx loop}. % combinators /dip { [/.v /.q] let .q /.v ' end}. /apply {exec}. /i {cvx exec}. /linrec { [/.if /.then /.rec1 /.rec2] let /.if ' /.then ' {.rec1 {/.if ' /.then ' /.rec1 ' /.rec2 ' linrec} i .rec2} ifte end}. /binrec { [/.if /.then /.rec1 /.rec2] let /.if ' /.then ' { .rec1 {/.if ' /.then ' /.rec1 ' /.rec2 ' binrec} dip {/.if ' /.then ' /.rec1 ' /.rec2 ' binrec} i .rec2 } ifte end}. /genrec { [/.if /.then /.rec1 /.rec2] let /.if ' /.then ' {.rec1 {/.if ' /.then ' /.rec1 ' /.rec2 ' genrec} .rec2} ifte end}. /tailrec {{} linrec}. /primrec { 5 dict begin /lzero? { {list?} {empty?} {zero?} ifte}. /lnext { {list?} {rest} {pred} ifte}. [/.param /.then /.rec] let* {/.param ' lzero?} /.then ' {.param {/.param ' lnext /.then ' /.rec ' primrec} i .rec} ifte end}. /treemap { [/.tree /.rec] let /.tree ' {leaf?} /.rec ' {{empty?} {} {dup {first /.rec ' treemap} dip {rest /.rec ' treemap} i cons} ifte} ifte end}. % debug /puts {= flush}. /cvstr { 4 dict begin /elements exch def /len elements length def /str len string def /i 0 def { i len ge { exit } if str i %The element of the array, as a hexadecimal string. %If it exceeds 16#FF, this will fail with a rangecheck. elements i get cvi put /i i 1 add def } loop str end } def /, {(=============\n) print pstack (=============\n) print}. </code></pre> <p><code>localdefs.ps</code> includes any definitions that needs to be included locally. </p> <pre><code>% set the prompt to something else so that we know initlib is loaded. /prompt {(&gt;| ) print flush} bind def /:x {(localdefs.ps) run}. </code></pre> <p>Here is how to load the library and get a working REPL.</p> <pre><code>rlwrap ghostscript -q -dNOSAFER -dNODISPLAY -c '(init.ps) run' $* </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-24T21:57:46.067", "Id": "35605", "Score": "0", "body": "+1 for introducing me to `rlwrap`! Sorry, I don't know concatenative programming, so the rest is just gibberish to me. :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-05T04:48:16.260", "Id": "125836", "Score": "0", "body": "Your code was mentioned in [a thread in comp.lang.postscript](https://groups.google.com/d/topic/comp.lang.postscript/SjXE6-Azoz0/discussion) which resulted in an improved `map` function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-13T17:45:34.820", "Id": "127484", "Score": "0", "body": "@luserdroog Wow! thank you, if you could paste that solution, I will accept that as an answer." } ]
[ { "body": "<p>There is an improvement that can be made to the <code>map</code> function. Your version:</p>\n\n<pre><code>/. {bind def} bind def\n\n%...\n\n/rup {3 1 roll}.\n\n%...\n\n/map { [ rup forall ] }.\n% [1 2 3 4] {1 add} map\n</code></pre>\n\n<p>The problem here is building the new array on the stack. While normally this is a perfectly sound technique in postscript, it places severe restrictions on how the procedure must behave. Using <a href=\"https://github.com/luser-dr00g/debug.ps\" rel=\"nofollow\">debug.ps</a> to produce a trace (caveat: I had to remove all the <code>bind</code> calls because the debugger has a bug with binding, apparently) illustrates how the execution proceeds through the example <code>[1 2 3 4] {1 add} map</code>. (I know you know how it executes, this is for the audience. ;)</p>\n\n<pre><code>[ %|- -mark- \n1 %|- -mark- 1 \n2 %|- -mark- 1 2 \n3 %|- -mark- 1 2 3 \n4 %|- -mark- 1 2 3 4 \n] %|- [1 2 3 4] \n{1 add} %|- [1 2 3 4] {1 add} \nmap %|- [1 2 3 4] {1 add} \n[ %|- [1 2 3 4] {1 add} -mark- \nrup %|- [1 2 3 4] {1 add} -mark- \n3 %|- [1 2 3 4] {1 add} -mark- 3 \n1 %|- [1 2 3 4] {1 add} -mark- 3 1 \nroll %|- -mark- [1 2 3 4] {1 add} \nforall %|- -mark- 1 \n1 %|- -mark- 1 1 \nadd %|- -mark- 2 \n[2 3 4] %|- -mark- 2 [2 3 4] \n{1 add} %|- -mark- 2 [2 3 4] {1 add} \nforall %|- -mark- 2 2 \n1 %|- -mark- 2 2 1 \nadd %|- -mark- 2 3 \n[3 4] %|- -mark- 2 3 [3 4] \n{1 add} %|- -mark- 2 3 [3 4] {1 add} \nforall %|- -mark- 2 3 3 \n1 %|- -mark- 2 3 3 1 \nadd %|- -mark- 2 3 4 \n[4] %|- -mark- 2 3 4 [4] \n{1 add} %|- -mark- 2 3 4 [4] {1 add} \nforall %|- -mark- 2 3 4 4 \n1 %|- -mark- 2 3 4 4 1 \nadd %|- -mark- 2 3 4 5 \n[] %|- -mark- 2 3 4 5 [] \n{1 add} %|- -mark- 2 3 4 5 [] {1 add} \nforall %|- -mark- 2 3 4 5\n</code></pre>\n\n<p>So whenever the procedure (the loop body) executes, the rest of the array is on the stack.</p>\n\n<pre><code>1 %|- -mark- 1 1 \nadd %|- -mark- 2 \n% ...\n1 %|- -mark- 2 2 1 \nadd %|- -mark- 2 3 \n% ...\n1 %|- -mark- 2 3 3 1 \nadd %|- -mark- 2 3 4 \n% ...\n1 %|- -mark- 2 3 4 4 1 \nadd %|- -mark- 2 3 4 5 \n</code></pre>\n\n<p>So you can't do something like this to add a constant to each element. Because the array-building gets in the way.</p>\n\n<pre><code>5 [1 2 3 4] {1 index add} map\n</code></pre>\n\n<p>A good attempt at removing this difficulty came from <a href=\"https://groups.google.com/d/msg/comp.lang.postscript/SjXE6-Azoz0/ZOWFzblMsrkJ\" rel=\"nofollow\">Carlos</a> in a comp.lang.postscript thread. Instead of using a <code>forall</code> loop directly, he uses a <code>for</code> loop running through the indices of the array and calls the user proc by name, managing the extraction and re-insertion of the the values in the array in the loop body. </p>\n\n<p>The problem there is that we've simply passed-off the interference to a different stack. The operand stack is now clear and usable, but the dictionary stack now has our bookkeeping dictionary on top (or worse: everything is <em>global</em> in <code>userdict</code>). So we're very prone to name-collision and unintended scoping issues when trying to use the function in an application.</p>\n\n<p>A couple of little-known features of the postscript language combine to offer a solution: dynamic code-generation. So we want a map that roughly does this:</p>\n\n<pre><code>/map { % arr proc map arr'\n 10 dict begin % arr proc\n /proc exch def % arr\n /arr exch def % &lt;empty&gt;\n 0 1 arr length 1 sub { % i\n /i exch def % &lt;empty&gt;\n arr i get % arr_i\n proc % proc(arr_i)\n arr exch i exch put % &lt;empty&gt;\n } for % &lt;empty&gt;\n arr % arr'\n end % arr'\n} def\n</code></pre>\n\n<p>But without having this local dictionary on the stack while <code>proc</code> is executing. </p>\n\n<p>What we can do to accomplish this is to generate a loop-body with these names <em>hard-bound</em> to their values. Postscript provides its scanner as the <code>token</code> operator which can produce a complete procedure-body from a string <em>template</em>.</p>\n\n<pre><code>({1 1 add =} remainder) token % ( remainder) {1 1 add =} true\npop % ( remainder) {1 1 add =}\nexch % {1 1 add =} ( remainder)\npop % {1 1 add =}\n</code></pre>\n\n<p>And the scanner will also substitute names prefixed with a double-slash <code>//</code> when they are encountered. So we can do this, too:</p>\n\n<pre><code>/val 5 def\n({//val =}) token pop exch pop % {5 =}\n</code></pre>\n\n<p>Now the name doesn't need to be defined for the procedure to execute.</p>\n\n<pre><code>/val 5 def\n({//val =}) token pop exch pop % {5 =}\ncurrentdict /val undef\nexec % prints: 5\n</code></pre>\n\n<p>So finally we get something like this:</p>\n\n<pre><code>/map { % arr proc map arr'\n 10 dict begin % arr proc\n /mydict currentdict def % arr proc\n /proc exch def % arr\n /arr exch def % &lt;empty&gt;\n 0 1 arr length 1 sub % 0 1 n-1\n ({\n { % i\n //mydict exch /i exch put % &lt;empty&gt;\n //arr % arr\n //mydict /i get % arr i\n get % arr_i\n //mydict /proc get % arr_i proc\n exec % proc(arr_i)\n //arr exch % arr proc(arr_i)\n //mydict /i get exch % arr i proc(arr_i)\n put % &lt;empty&gt;\n } for % &lt;empty&gt;\n //arr % arr'\n }) token pop exch pop % 0 1 n-1 {{...}for...}\n end % &lt;-- remove dictionary\n exec % &lt;-- execute dynamic proc\n} def\n</code></pre>\n\n<p>You can also <code>bind</code> the procedure just before <code>exec</code>ing, to factor-out name lookups for the operators. </p>\n\n<p>This version changes the existing array and returns that as the result. <a href=\"https://groups.google.com/d/msg/comp.lang.postscript/SjXE6-Azoz0/uq-4r5FfVM4J\" rel=\"nofollow\">Carlos' final version</a> creates a new array for the result, which is closer to the behavior of your original function.</p>\n\n<hr>\n\n<p>It was not Carlos' final version. After I discovered possible problems with applying <code>bind</code> to the user-procedure, Carlos realized that the whole technique of calling <code>token</code> on a string containing a procedure (my big gimmick) was inherently prone to goofs with <code>bind</code>, and he produced this <a href=\"https://groups.google.com/d/msg/comp.lang.postscript/SjXE6-Azoz0/4e9qaKYZm7sJ\" rel=\"nofollow\"><em>final</em> final version</a>. The string trick is gone. Instead all library functions (including the <em>dynamic loop body</em>) have <code>bind</code> applied at \"library load time\". The behavior is thus independent of the user redefining any operator names.</p>\n\n<p>The string-token trick has been replaced by two procedures, <code>deepcopy</code> which makes a modifiable copy of the loop-body (<code>bind</code> makes the original loop-body -- as it does to all subarrays of the function -- <strong>readonly</strong>, so we need a copy in order to patch the variables), and <code>replaceall</code> which takes an array and a dictionary and maps the array (recursively) through the dictionary (it patches the variables). So this is now a much more robust function.</p>\n\n<pre><code>% &lt;array/string&gt; &lt;proc&gt; map &lt;new array/string&gt; \n/map { \n 4 dict begin \n\n /,proc exch def \n /,arr exch def \n /,res ,arr length \n ,arr type /stringtype eq { string } { array } ifelse \n def \n /,i 1 array def \n { \n 0 1 /,arr length 1 sub { % for \n dup /,i 0 3 -1 roll put \n /,arr exch get \n /,proc exec \n /,res /,i 0 get 3 -1 roll put \n } for \n /,res \n } deepcopy dup currentdict replaceall \n end exec \n} bind def \n\n% copies array recursively \n% &lt;array&gt; deepcopy &lt;new array&gt; \n/deepcopy { \n dup xcheck exch \n dup length array copy \n dup length 1 sub 0 exch 1 exch { % for % a i \n 2 copy 2 copy get dup type /arraytype eq % a i a i e ? \n { % ifelse \n deepcopy put \n } \n { \n pop pop pop \n } ifelse \n pop \n } for \n exch { cvx } if \n} bind def \n\n% recursively replaces elements in &lt;array&gt; found in &lt;dict&gt; \n% &lt;array&gt; &lt;dict&gt; replaceall - \n/replaceall { \n 1 index length 1 sub 0 1 3 -1 roll { % for 0 1 length-1 \n 3 copy 3 -1 roll exch % a d i d a i \n get % a d i d e \n 2 copy known % a d i d e ? \n % ifelse \n { % a d i d e \n get % a d i v \n 3 index 3 1 roll % a d a i v \n put \n } % else \n { % a d i d e \n dup type /arraytype eq % a d i d e ? \n { exch replaceall } \n { pop pop } ifelse \n pop \n } ifelse % a d \n } for \n pop pop \n} bind def \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-15T17:41:57.407", "Id": "127820", "Score": "0", "body": "Thank you!, could you also paste the final version from Carlos, for posterity?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-17T05:04:42.103", "Id": "127996", "Score": "0", "body": "@rahul There have been some further developments, and Carlos has an *even more final* version. I need to think through the issues with `bind` before adding more. But I *will* add more." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-15T08:47:02.540", "Id": "69933", "ParentId": "12249", "Score": "8" } }, { "body": "<p>Here's a solution that doesn't use as many deep features of PostScript, although it might be considered twisted in its own way. It stores temporary variables at the bottom of the stack instead of at the top, and does this by rotating the entire stack repeatedly. Even so, it seems efficient enough.</p>\n\n<p>First, a version that modifies the array in place.</p>\n\n<pre><code>% Very general map that operates on an existing array. \n% Does not pollute dictionary. Allows natural access to stack. \n% Efficiency may vary since it rotates the entire stack a lot. \n\n/map { % array f map -- \n % ... array f \n count count 1 add roll % array f ... \n count 1 sub index % array f ... array \n length 1 sub 0 exch 1 exch % array f ... 0 1 (n-1) \n { % array f ... i \n count count roll % i array f ... \n count 2 sub index % i array f ... array \n count 1 sub index % i array f ... array i \n get % i array f ... array[i] \n count 3 sub index % i array f ... array[i] f \n exec % i array f ... f(array[i]) \n count 2 sub index % i array f ... f(array[i]) array \n exch % i array f ... array f(array[i]) \n count 1 count sub roll % array f ... array f(array[i]) i \n exch put % array f ... \n } for\n count 0 count sub roll % ... array f \n pop pop % ... \n} bind def\n</code></pre>\n\n<p>Second, a version that leaves the array unmodified and returns a new array:</p>\n\n<pre><code>% Very general map that returns a new array. \n% Does not pollute dictionary. Allows natural access to stack. \n% Efficiency may vary since it rotates the entire stack a lot. \n\n/mapc { % array f map -- array \n % ... array f \n exch dup length array % ... f array newarr \n count count 2 add roll % f array newarr ... \n count 2 sub index % f array newarr ... array \n length 1 sub 0 exch 1 exch % f array newarr ... 0 1 (n-1) \n { % f array newarr ... i \n count count roll % i f array newarr ... \n count 3 sub index % i f array newarr ... array \n count 1 sub index % i f array newarr ... array i \n get % i f array newarr ... array[i] \n count 2 sub index % i f array newarr ... array[i] f \n exec % i f array newarr ... f(array[i]) \n count 4 sub index % i f array newarr ... f(array[i]) newarr \n exch % i f array newarr ... newarr f(array[i]) \n count 1 count sub roll % f array newarr ... array f(array[i]) i \n exch put % f array newarr ... \n } for\n count 0 count sub roll % newarr ... f array \n pop pop % newarr ... \n count 1 count sub roll % ... newarr \n} bind def\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-24T23:46:05.643", "Id": "241169", "ParentId": "12249", "Score": "4" } } ]
{ "AcceptedAnswerId": "69933", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T19:29:17.057", "Id": "12249", "Score": "12", "Tags": [ "functional-programming", "postscript" ], "Title": "Concatenative PostScript library" }
12249
<p>I have written following small utility to abstract away the lazy initialization logic. (I tend to use lazy variables quite often.)</p> <p>Are there any issues in this implementation?</p> <pre><code>// File: F0.java public abstract class F0&lt;A&gt; { public abstract A apply(); } // File: Lazy.java public class Lazy&lt;A&gt; { private boolean isInitialized = false; private A content; private final F0&lt;A&gt; init; private Lazy(F0&lt;A&gt; init) { this.init = init; } public static &lt;A&gt; Lazy&lt;A&gt; initializedAs(F0&lt;A&gt; init) { return new Lazy&lt;A&gt;(init); } @Override public String toString() { return this.get().toString(); } public A get() { if (!isInitialized) { content = init.apply(); isInitialized = true; } return content; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Lazy lazy = (Lazy) o; Object c = this.get(); if (c != null ? !c.equals(lazy.get()) : lazy.get() != null) { return false; } return true; } @Override public int hashCode() { return this.get().hashCode(); } } </code></pre> <p><strong>Edit:</strong></p> <p>Here is an example usage from the current project I am working on.</p> <pre><code>final Prerequisite prerequisite = new Prerequisite() { private Lazy&lt;String&gt; minimumRequiredJavaVersion = Lazy.initializedAs( new F0&lt;String&gt;() { @Override public String apply() { return SystemProperties.isWindows() &amp;&amp; SystemProperties.is64Bit() ? "1.7" : "1.6"; } } ); @Override public boolean isSatisfied() { return SystemProperties.javaVersionIsMinimum(minimumRequiredJavaVersion.get()); } @Override public String failureMessage() { StringBuilder sb = new StringBuilder(); sb.append("Minimum required Java version is: " + minimumRequiredJavaVersion.get() + "\n"); sb.append("Your system has " + JAVA_SPECIFICATION_VERSION + "."); return sb.toString(); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T21:27:28.327", "Id": "19644", "Score": "0", "body": "Samples of how you use it would be appreciated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T22:27:43.213", "Id": "19646", "Score": "0", "body": "@blufox, I added an example. Basically, the variable is not initialized until it is required. (And not initialized at all if it is not required.) After computing it once, it is cached and this cached value is returned on further accesses." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T22:41:06.543", "Id": "19647", "Score": "0", "body": "This has nothing to do with the question, but... do you know Scala? I found the language quite interesting (functional-oriented, so lazyness is part of the language), it runs in the JVM too and is completely interoperable with Java." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T22:44:02.350", "Id": "19648", "Score": "0", "body": "@kaoD, I have been a Scala enthusiast for more than 2 years, have been professionally working with it since past 1 year, and am one of the [top answeres in Scala tag on stackoverflow](http://stackoverflow.com/tags/scala/topusers) (with a gold badge). :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T22:45:28.900", "Id": "19649", "Score": "0", "body": "@kaoD, the current project however is in Java. (Team decision.) So I am trying to replicate some abstractions from Scala that I find indispensable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T07:31:00.870", "Id": "19997", "Score": "0", "body": "Similar question from stackoverflow: http://stackoverflow.com/questions/7524423/lazy-loading-reference-implementation." } ]
[ { "body": "<p>Four notes:</p>\n\n<ol>\n<li><p>It's not thread-safe. <code>init.apply()</code> could be called multiple times from different threads. (I don't know whether it is an issue or not.)</p></li>\n<li><p>The constructor should check <code>null</code> inputs. (<em>Effective Java 2nd Edition, Item 38: Check parameters for validity</em>)</p></li>\n<li><p>You should use <code>append</code> instead of <code>String</code> concatenation:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nsb.append(\"Minimum required Java version is: \").append(minimumRequiredJavaVersion.get()).append(\"\\n\");\nsb.append(\"Your system has \").append(JAVA_SPECIFICATION_VERSION).append(\".\");\nreturn sb.toString();\n</code></pre></li>\n<li><p>Instead of the anonymous <code>Prerequisite</code> inner class I'd use a named top-level class (for example, <code>MinimumRequiredJavaVersionPrerequisite</code>). I think it's easier to read, naming it helps readers to understand the purpose of the class.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T05:16:29.193", "Id": "19657", "Score": "0", "body": "1. Indeed. Should I put it in a synchronized block?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T05:17:49.533", "Id": "19659", "Score": "0", "body": "3. Actually, I was planning to get rid of `StringBuilder`. Java optimizes this stuff anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T05:18:40.080", "Id": "19660", "Score": "0", "body": "4. Personal matter of taste. The code follows a functional programming style, and therefore anonymous inner classes are abound." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T05:18:50.233", "Id": "19661", "Score": "0", "body": "Overall, a good advice. +1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T07:46:12.237", "Id": "19663", "Score": "0", "body": "I misunderstood your 2nd bullet, so removed that comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T16:59:02.173", "Id": "19683", "Score": "0", "body": "1. Yes, I think you should. Or you could use a [ReentrantLock](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/locks/ReentrantLock.html) too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T16:59:15.603", "Id": "19684", "Score": "0", "body": "4. In this case I'd rename the `prerequisite` variable to `minimumRequiredJavaVersionPrerequisite` :-)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T23:49:39.017", "Id": "12252", "ParentId": "12250", "Score": "2" } }, { "body": "<p>I do not see any issues with your code, however,\nA few questions, </p>\n\n<ul>\n<li>Why is F0 abstract? (why not an interface)?</li>\n<li>Why do you need isInitialized? cant you null check the content? even if init could throw, there doesn't seem to be a difference.</li>\n<li>What happens if the initialization results in an exception? Do you want to retry each time .get is called? or do you want to remember that it was unsuccessful?</li>\n<li>I am also curious, why did you opt to use initializedAs rather than using just new Lazy&lt;String&gt;()? </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T05:08:35.630", "Id": "19652", "Score": "0", "body": "1. The other `F{n}` abstract classes contain abstract methods, and therefore cannot be interfaces. So for the sake of consistency, I made `F0` an abstract class. But yes, I agree, it should really be an interface." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T05:10:00.213", "Id": "19653", "Score": "0", "body": "2. To allow `null` as a valid value. In the retrospect, I cannot think of a case where I would require that. So perhaps, yes, I should do away with `isInitialized`, and add a `null` check in `init`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T05:11:22.490", "Id": "19654", "Score": "0", "body": "3. A very good point. I did not think about it. I think it would make sense to retry the initialization on each access if it failed on last access." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T05:15:45.433", "Id": "19655", "Score": "0", "body": "4. For better type inference, and less redundancy (at use site). In case of direct constructor use, user has to supply the type parameter. In case of static methods, it can be inferred from the type of reference to which the object is being assigned. (This is in the same spirit as say Guava's `Lists.newArrayList`.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T05:15:55.463", "Id": "19656", "Score": "0", "body": "Overall, a good advice. +1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T07:48:40.203", "Id": "19664", "Score": "0", "body": "Regarding 2nd bullet, if `init.apply` happens to return null, then it will unnecessarily get called every time `get` is accessed. It appears I will be needing `isInitialized` after all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T18:32:21.410", "Id": "19688", "Score": "0", "body": "@missingfaktor Yes certainly, I was only wondering if that was your intension." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T18:39:19.513", "Id": "19689", "Score": "0", "body": "If returning null in init.apply is an indication of failure, any particular reason you chose that rather than allowing apply throw an exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T04:57:30.110", "Id": "19709", "Score": "0", "body": "I did not understand that last comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T05:14:10.613", "Id": "19711", "Score": "0", "body": "I assume that you kept isInitialized because init.apply may return null on failure. Since your interface for apply does not have a \"throws\" I assume it is not expected that an exception happen. I was wondering why you chose to use null as a construction-failure indicator rather than allow apply to throw an exception on that event. Perhaps I am confusing some part of your design?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T05:24:31.240", "Id": "19712", "Score": "0", "body": "No, you misunderstood. The reason I am using `isInitialized` is because I want to allow `null` as a valid value. In other words, it has no special privileges over any other values `contents` can take. It is not used as a construction-failure indicator." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T05:42:30.643", "Id": "19713", "Score": "0", "body": "ok, that is reasonable." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T00:52:30.253", "Id": "12253", "ParentId": "12250", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T21:03:37.703", "Id": "12250", "Score": "3", "Tags": [ "java", "lazy" ], "Title": "Are there any issues in this `Lazy` implementation?" }
12250
<p>I am writing my own website where users sign up. It then saves that data in an array. I want to know if this is effective or if there are better ways to do it.</p> <pre><code>var isLoggedOn = false; var numberOfUsers = 0; var users = new Array(); var correct = false; var currentUser = new User(); var date = new Array(); var userNumber = 0; function getRegistrationFields() { var first1 = document.getElementById("firstname"); first1.onclick = getRegistrationFields; var last1 = document.getElementById("lastname"); last1.onclick = getRegistrationFields; var email1 = document.getElementById("email"); email1.onclick = getRegistrationFields; var age1 = document.getElementById("age").value; age1.onclick = getRegistrationFields; var username1 = document.getElementById("username"); username1.onclick = getRegistrationFields; var password1 = document.getElementById("password"); password1.onclick = getRegistrationFields; var confirm1 = document.getElementById("passwordconfirm"); confirm1.onclick = getRegistrationFields; var first = document.getElementById("firstname").value; var last = document.getElementById("lastname").value; var email = document.getElementById("email").value; var age = document.getElementById("age").value; var username = document.getElementById("username").value; var password = document.getElementById("password").value; var confirmpassword = document.getElementById("passwordconfirm").value; var empty = ""; if ((first === empty) || (last === empty) || (email === empty) || (age === empty) || (username === empty) || (password === empty) || (confirm === empty)) { var message = "Not all of the fields are filled out"; alert(message); //showModalWindow("fields"); return false; } else { age = parseInt(age); if (password.length &lt; 10) { var message2 = "Password must be at least 10 characters long"; alert(message2); //showModalWindow("passwordlength"); return false; } else if (password != confirmpassword) { var message3 = "Passwords Do not match"; alert(message3); //showModalWindow("passwordmatch"); return false; } else if (age &lt; 18) { var message4 = "You must be older to register for this software."; alert(message4); //showModalWindow("young"); return false; } else { var message5 = "All of the fields are correct. We will be processing your request"; alert(message5); var d = new Date(); date[numberOfUsers] = d.toDatestring(); var user = new User(username, password, email, first, last, age, date[numberOfUsers]); users[numberOfUsers]=user; numberOfUsers += 1; //showModalWindow("success"); return true; } } } function User(username, password, email, firstname, lastname, age, datecreated) { this.username = username; this.password = password; this.firstname = firstname; this.lastname = lastname; this.name = firstname + " " + lastname; this.age = age; this.datecreated = datecreated; } Array.prototype.checkFields = function(username, password) { for(var i = 0; i &lt; this.length; i++) { if(this[i].username === username) { if(this[i].password === password) { return true; userNumber = i; } } else { return false; } } } function CheckSignIn() { var username = document.getElementById("username").value; var password = document.getElementById("password").value; if (username === "" || password === "") { alert("Please enter a username/password"); } else { if (users.checkFields(username, password)) { window.location = "http://localhost/profile.html"; currentUser.username = users[userNumber].username; currentUser.password = users[userNumber].password; currentUser.age = users[userNumber].age; currentUser.firstname = users[userNumber].firstname; currentUser.lastname = users[userNumber].lastname; currentUser.datecreated = users[userNumber].datecreated; isLoggedOn = true; } } } </code></pre>
[]
[ { "body": "<p>Just a few general notes:</p>\n\n<ol>\n<li><p>Instead of using arrow <code>if-else { if-else { ... } }</code> structure you could format the code as guard clauses. For example:</p>\n\n<pre><code>if ((first === empty) || (last === empty) || (email === empty) || (age === empty)\n || (username === empty) || (password === empty) || (confirm === empty)) {\n var message = \"Not all of the fields are filled out\";\n alert(message);\n return false;\n}\nage = parseInt(age);\n...\n</code></pre>\n\n<p>Reference: <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">Flattening Arrow Code</a></p></li>\n<li><p>You could create some local variables:</p>\n\n<pre><code>currentUser.username = users[userNumber].username;\ncurrentUser.password = users[userNumber].password;\ncurrentUser.age = users[userNumber].age;\n...\n</code></pre>\n\n<p>Here <code>users[userNumber]</code> could be extracted out to a local variable. It would improve readability and remove some duplication.</p></li>\n<li><p>Using <code>alert</code> does not seem good: <a href=\"https://stackoverflow.com/questions/8825384/alert-is-bad-really\">\"Alert is bad\" - really?</a>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T17:13:13.510", "Id": "12272", "ParentId": "12254", "Score": "1" } } ]
{ "AcceptedAnswerId": "12272", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T01:34:08.433", "Id": "12254", "Score": "2", "Tags": [ "javascript", "array", "validation" ], "Title": "User data storage" }
12254
<p>I have files containing data sets which contain 11,000 rows. I have to run a loop through each row, which is taking me 25 minutes for each file.</p> <pre><code> z &lt;- read.zoo("Title.txt", tz = "") for(i in seq_along(z[,1])) { if(is.na(coredata(z[i,1]))) next ctr &lt;- i while(ctr &lt; length(z[,1])) { if( ( abs ( coredata(z[i,1]) -coredata(z[ctr+1,1]) ) ) &gt; std_d) { z[ctr+1,1] &lt;- NA ctr &lt;- ctr + 1 } else { break } } } </code></pre> <p>Where Title.txt is a file containing 11,000 rows. It looks like this (first five rows):</p> <blockquote> <pre><code>"timestamp" "mesured_distance" "IFC_Code" "from_sensor_to_river_bottom" "1" "2012-06-03 12:30:07-05" 3188 1005 3500 "2" "2012-06-03 12:15:16-05" 3189 1005 3500 "3" "2012-06-03 12:00:08-05" 3185 1005 3500 "4" "2012-06-03 11:45:11-05" 3191 1005 3500 "5" "2012-06-03 11:30:15-05" 3188 1005 3500 </code></pre> </blockquote> <p>How can I increase the speed of this code?</p>
[]
[ { "body": "<p>In your code, <code>std_d</code> is not defined. Presumably it is some threshold value, since it is used in a comparison of absolute differences.</p>\n\n<p>First, reformat your code so that I can better determine what it is supposed to do:</p>\n\n<pre><code>for(i in seq_along(z[,1])) {\n if(is.na(coredata(z[i,1]))) next\n ctr &lt;- i\n while(ctr &lt; length(z[,1])) {\n if((abs(coredata(z[i,1])-coredata(z[ctr+1,1]))) &gt; std_d) {\n z[ctr+1,1] &lt;- NA\n ctr &lt;- ctr + 1\n } else {\n break\n }\n }\n}\n</code></pre>\n\n<p>Then determine what the algorithm is that you are trying to do:</p>\n\n<p>Looping over each element of the first column of z, skipping any missing values, compare that value to every other value to the end of column. If the current value and some subsequent value differ by more than some threshold (in absolute difference), set that subsequent value to NA.</p>\n\n<p>R is a vectorized language, so explicit <code>for</code> loops are often not the most efficient way to perform an operation.</p>\n\n<p>Let's vectorize that inner while loop.</p>\n\n<pre><code>for(i in seq_along(z[,1])) {\n if(is.na(coredata(z[i,1]))) next\n ctr &lt;- (i+1):length(z[,1])\n z[i+which(abs(coredata(z[i,1]) - coredata(z[ctr,1])) &gt; std_d),1] &lt;- NA\n}\n</code></pre>\n\n<p>I make <code>ctr</code> a vector of all the indexes higher than <code>i</code>, and use that most functions are vectorized. For example, with <code>i</code> equal to 1, (and picking <code>std_d</code> equal to 2) working the statements from inside out:</p>\n\n<pre><code>&gt; ctr &lt;- (i+1):length(z[,1])\n&gt; ctr\n[1] 6 5\n&gt; i\n[1] 5\n&gt; i &lt;- 1\n&gt; ctr &lt;- (i+1):length(z[,1])\n&gt; ctr\n[1] 2 3 4 5\n&gt; coredata(z[i,1]) - coredata(z[ctr,1])\n 4 3 2 1 \n-3 3 -1 0 \n&gt; abs(coredata(z[i,1]) - coredata(z[ctr,1]))\n4 3 2 1 \n3 3 1 0 \n&gt; abs(coredata(z[i,1]) - coredata(z[ctr,1])) &gt; std_d\n 4 3 2 1 \n TRUE TRUE FALSE FALSE \n&gt; which(abs(coredata(z[i,1]) - coredata(z[ctr,1])) &gt; std_d)\n4 3 \n1 2 \n&gt; i+which(abs(coredata(z[i,1]) - coredata(z[ctr,1])) &gt; std_d)\n4 3 \n2 3 \n&gt; z[i+which(abs(coredata(z[i,1]) - coredata(z[ctr,1])) &gt; std_d),1]\n2012-06-03 11:45:11 2012-06-03 12:00:08 \n 3191 3185 \n&gt; z[i+which(abs(coredata(z[i,1]) - coredata(z[ctr,1])) &gt; std_d),1] &lt;- NA\n&gt; z\n mesured_distance IFC_Code from_sensor_to_river_bottom\n2012-06-03 11:30:15 3188 1005 3500\n2012-06-03 11:45:11 NA 1005 3500\n2012-06-03 12:00:08 NA 1005 3500\n2012-06-03 12:15:16 3189 1005 3500\n2012-06-03 12:30:07 3188 1005 3500\n</code></pre>\n\n<p>This change alone would probably speed up your code a lot. You could aslo pull the computation of <code>length(z[,1])</code> outside the loop, but that will be a much smaller improvement.</p>\n\n<p>The sample of data you gave is too small to do any reasonable benchmarking on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T16:40:25.313", "Id": "12270", "ParentId": "12255", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T02:55:42.887", "Id": "12255", "Score": "2", "Tags": [ "performance", "r" ], "Title": "Looping through rows of data sets in files" }
12255
<p>I'm an amateur coder writing a geometry library in Python, and would like some feedback regarding my implementation of a class for 3D Vectors.</p> <p>My priority is to have a really friendly API for beginners who are just starting out writing code, to build it with as few dependencies as possible (no numpy or scipy), and for it to be compatible with at least Python 2.6, hopefully as early as 2.4.</p> <p><strong>EDIT #1:</strong> I really just want general feedback and thought an experienced coder might see glaring errors relating to performance or object hashing and comparison.</p> <p><strong>EDIT #2:</strong> @Winston raised a good criticism about my goal to not use dependencies, so I'll explain this goal in more detail. My primary audience for this library is beginners who may be using Python or writing code for the first time. This may be the first library they've ever had to put on sys.path and import, and there is a decent chance they will utilize the package to script a GUI application, and therefore within a non-standard implementation of Python, such as IronPython. I want to minimize the complexity of using the library for first time users. But yeah, I totally love the array of fantastic packages in Python, but ideally, I just don't want the first 3rd party package someone uses to have additional dependencies, and if I have to, it should come with "batteries included"</p> <p>These goals are more important than performance to me, but if I can improve performance (or anything else) without sacrificing these bigger priorities, that would be great.</p> <pre><code>class Vector3D(object): """A 3D vector object. Intended to basically be an api wrapper around a tuple of 3 float values. It would allow people to reset different coordinates, and to treat the Vector like a list or even a dictionary, but at heart it would be a tuple of floats. """ def __init__(self, x=0.0, y=0.0, z=0.0): for arg in (x, y, z): if not isinstance(arg, numbers.Number): raise TypeError # coords is the essence of the data structure. It's immutable and # iterable self.coords = (x, y, z) # defining x, y, and z like this to allow for the coords to remain a # non-mutable iterable. @property def x(self): return self[0] @x.setter def x(self, number): self.coords = (number, self[1], self[2]) @property def y(self): return self[1] @y.setter def y(self, number): self.coords = (self[0], number, self[2]) @property def z(self): return self[2] @z.setter def z(self, number): self.coords = (self[0], self[1], number) @property def length(self): """get the vector length / amplitude &gt;&gt;&gt; v = Vector3D(0.0, 2.0, 1.0) &gt;&gt;&gt; v.length 2.2360679774997898 """ # iterate through the coordinates, square each, and return the root of # the sum return math.sqrt(sum(n**2 for n in self)) @length.setter def length(self, number): """set the vector amplitude &gt;&gt;&gt; v = Vector3D(0.0, 2.0, 1.0) &gt;&gt;&gt; v.length 2.2360679774997898 &gt;&gt;&gt; v.length = -3.689 &gt;&gt;&gt; v Vector3D(-0.0, -3.2995419076, -1.6497709538) """ # depends on normalized() and __mult__ # create a vector as long as the number v = self.normalized() * number # copy it self.match(v) def normalize(self): """edits vector in place to amplitude 1.0 and then returns self &gt;&gt;&gt; v Vector3D(-0.0, -3.2995419076, -1.6497709538) &gt;&gt;&gt; v.normalize() Vector3D(-0.0, -0.894427191, -0.4472135955) &gt;&gt;&gt; v Vector3D(-0.0, -0.894427191, -0.4472135955) """ # depends on normalized and match self.match(self.normalized()) return self def normalized(self): """just returns the normalized version of self without editing self in place. &gt;&gt;&gt; v.normalized() Vector3D(0.0, 0.894427191, 0.4472135955) &gt;&gt;&gt; v Vector3D(0.0, 3.2995419076, 1.6497709538) """ # think how important float accuracy is here! if isRoughlyZero(sum(n**2 for n in self)): raise ZeroDivisionError else: return self * (1 / self.length) def match(self, other): """sets the vector to something, either another vector, a dictionary, or an iterable. If an iterable, it ignores everything beyond the first 3 items. If a dictionary, it only uses keys 'x','y', and 'z' &gt;&gt;&gt; v Vector3D(0.0, 3.2995419076, 1.6497709538) &gt;&gt;&gt; v.match({'x':2.0, 'y':1.0, 'z':2.2}) &gt;&gt;&gt; v Vector3D(2.0, 1.0, 2.2) """ # this basically just makes a new vector and uses it's coordinates to # reset the coordinates of this one. if isinstance(other, Vector3D): self.coords = other.coords elif isinstance(other, dict): self.coords = (other['x'], other['y'], other['z']) else: # assume it is some other iterable self.coords = tuple(other[:3]) def asList(self): """return vector as a list""" return [c for c in self] def asDict(self): """return dictionary representation of the vector""" return dict( zip( list('xyz'), self.coords ) ) def __getitem__(self, key): """Treats the vector as a tuple or dict for indexes and slicing. &gt;&gt;&gt; v Vector3D(2.0, 1.0, 2.2) &gt;&gt;&gt; v[0] 2.0 &gt;&gt;&gt; v[-1] 2.2000000000000002 &gt;&gt;&gt; v[:2] (2.0, 1.0) &gt;&gt;&gt; v['y'] 1.0 """ # key index if isinstance(key, int): return self.coords[key] # dictionary elif key in ('x','y','z'): return self.asDict()[key] # slicing elif isinstance(key, type(slice(1))): return self.coords.__getitem__(key) else: raise KeyError def __setitem__(self, key, value): """Treats the vector as a list or dictionary for setting values. &gt;&gt;&gt; v Vector3D(0.0, 1.20747670785, 2.4149534157) &gt;&gt;&gt; v[0] = 5 &gt;&gt;&gt; v Vector3D(5, 1.20747670785, 2.4149534157) &gt;&gt;&gt; v['z'] = 60.0 &gt;&gt;&gt; v Vector3D(5, 1.20747670785, 60.0) """ if not isinstance(value, numbers.Number): raise ValueError if key in ('x','y','z'): d = self.asDict() d.__setitem__(key, value) self.match(d) elif key in (0,1,2): l = self.asList() l.__setitem__(key, value) self.match(l) else: raise KeyError def __iter__(self): """For iterating, the vectors coordinates are represented as a tuple.""" return self.coords.__iter__() ## Time for some math def dot(self, other): """Gets the dot product of this vector and another. &gt;&gt;&gt; v Vector3D(5, 1.20747670785, 60.0) &gt;&gt;&gt; v1 Vector3D(0.0, 2.0, 1.0) &gt;&gt;&gt; v1.dot(v) 62.41495341569977 """ return sum((p[0] * p[1]) for p in zip(self, other)) def cross(self, other): """Gets the cross product between two vectors &gt;&gt;&gt; v Vector3D(5, 1.20747670785, 60.0) &gt;&gt;&gt; v1 Vector3D(0.0, 2.0, 1.0) &gt;&gt;&gt; v1.cross(v) Vector3D(118.792523292, 5.0, -10.0) """ # I hope I did this right x = (self[1] * other[2]) - (self[2] * other[1]) y = (self[2] * other[0]) - (self[0] * other[2]) z = (self[0] * other[1]) - (self[1] * other[0]) return Vector3D(x, y, z) def __add__(self, other): """we want to add single numbers as a way of changing the length of the vector, while it would be nice to be able to do vector addition with other vectors. &gt;&gt;&gt; from core import Vector3D &gt;&gt;&gt; # test add ... v = Vector3D(0.0, 1.0, 2.0) &gt;&gt;&gt; v1 = v + 1 &gt;&gt;&gt; v1 Vector3D(0.0, 1.4472135955, 2.894427191) &gt;&gt;&gt; v1.length - v.length 0.99999999999999956 &gt;&gt;&gt; v1 + v Vector3D(0.0, 2.4472135955, 4.894427191) """ if isinstance(other, numbers.Number): # then add to the length of the vector # multiply the number by the normalized self, and then # add the multiplied vector to self return self.normalized() * other + self elif isinstance(other, Vector3D): # add all the coordinates together # there are probably more efficient ways to do this return Vector3D(*(sum(p) for p in zip(self, other))) else: raise NotImplementedError def __sub__(self, other): """Subtract a vector or number &gt;&gt;&gt; v2 = Vector3D(-4.0, 1.2, 3.5) &gt;&gt;&gt; v1 = Vector3D(2.0, 1.1, 0.0) &gt;&gt;&gt; v2 - v1 Vector3D(-6.0, 0.1, 3.5) """ return self.__add__(other * -1) def __mul__(self, other): """if with a number, then scalar multiplication of the vector, if with a Vector, then dot product, I guess for now, because the asterisk looks more like a dot than an X. &gt;&gt;&gt; v2 = Vector3D(-4.0, 1.2, 3.5) &gt;&gt;&gt; v1 = Vector3D(2.0, 1.1, 0.0) &gt;&gt;&gt; v2 * 1.25 Vector3D(-5.0, 1.5, 4.375) &gt;&gt;&gt; v2 * v1 #dot product -6.6799999999999997 """ if isinstance(other, numbers.Number): # scalar multiplication for numbers return Vector3D( *((n * other) for n in self)) elif isinstance(other, Vector3D): # dot product for other vectors return self.dot(other) def __hash__(self): """This method provides a hashing value that is the same hashing value returned by the vector's coordinate tuple. This allows for testing for equality between vectors and tuples, as well as between vectors. Two vector instances (a and b) with the same coordinates would return True when compared for equality: a == b, a behavior that I would love to have, and which would seem very intuitive. They would also return true when compared for equality with a tuple equivalent to their coordinates. My hope is that this will greatly aid in filtering duplicate points where necessary - something I presume many geometry algorithms will need to look out for. I'm not sure it is a bad idea, but I intend this class to basically be a tuple of floats wrapped with additional functionality. """ return self.coords.__hash__() def __repr__(self): return 'Vector3D%s' % self.coords </code></pre> <p>Some specific questions as prompts, but I'm mostly just looking for general review:</p> <ol> <li>Is it foolish to implement a <code>__hash__</code> method that returns true between the object and a tuple contained in one of it's attributes? I thought this method would be useful for creating sets of vectors, and comparing for equality between vectors. Will it have some unforeseen consequences in terms of comparison?</li> <li>Are there an glaring performance mistakes that I'm making?</li> <li>Is there anything else that you would warn me about, or opportunities I'm missing?</li> </ol>
[]
[ { "body": "<pre><code> for arg in (x, y, z):\n if not isinstance(arg, numbers.Number):\n raise TypeError\n</code></pre>\n\n<p>Don't check types. Just assume that the user passed in the correct types. I am serious. It'll waste time every time you make a Vector3D class. </p>\n\n<pre><code> # coords is the essence of the data structure. It's immutable and\n # iterable\n self.coords = (x, y, z)\n</code></pre>\n\n<p>What are you trying to accomplish with this tuple? This class doesn't act like a tuple, because you can modify the coordinates, so there is no reason to be using a tuple.</p>\n\n<pre><code> @property\n def x(self):\n return self[0]\n @x.setter\n def x(self, number):\n self.coords = (number, self[1], self[2])\n</code></pre>\n\n<p>A Vector class should be immutable. You shouldn't have setters for x, y, or z. In python value objects like strings/integers/floats/etc are all immutable. If you break that pattern for your class, code will end up being confusing. The reason is because of code like this:</p>\n\n<pre><code>a = Vector3d()\nb = a\na.x = 5\nprint b.x\n</code></pre>\n\n<p><code>a</code> and <code>b</code> are the same object, so modifying one modifies the other. This tends to produce subtle bugs, hence objects that hold values like this are usually made immutable to prevent this.</p>\n\n<blockquote>\n <p>to build it with as few dependencies as possible (no numpy or scipy)</p>\n</blockquote>\n\n<p>Don't. That should (almost) never be a goal. Libraries like numpy are what makes python so great. If you avoid use a numpy when it is useful, you doom your library to be completely useless. Any sort of code that operations on data like this in python should be using numpy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T10:11:02.477", "Id": "19722", "Score": "0", "body": "\"Don't check types\" - Thank you. I'll stop doing that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T10:15:42.423", "Id": "19723", "Score": "0", "body": "\"A Vector class should be immutable. You shouldn't have setters for x, y, or z.\" - thanks, I've been going back and forth about this and how I've handled it. You put the inner debate to rest. It will be immutable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T10:20:21.467", "Id": "19724", "Score": "0", "body": "\"Don't. That should (almost) never be a goal. Libraries like numpy are what makes python so great.\" - I strongly agreee that such libraries make python great, but I aim to focus on beginners as an audience, many of whom might be using the library to script a GUI application, so they may be using different implementations of Python (such as IronPython). It may also be the first library they've ever had to install and use. I admire how NetworkX handles this: written in pure python, but can be used with numpy if desired." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T10:32:37.863", "Id": "19725", "Score": "0", "body": "Thank you for taking the time to review my code, I appreciate it _a ton_. Seriously." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T10:34:43.180", "Id": "19726", "Score": "0", "body": "\"Don't check types. Just assume that the user passed in the correct types.\" - One question: If I have methods that I want to respond differently to different input types, is it still a bad idea to use type checking in that context?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T14:21:51.923", "Id": "19730", "Score": "0", "body": "@BenjaminGolder, most of the time you shouldn't be writing methods that respond differently to different input types. If you really must, its preferred to check to do check for supported operations, not the type so you can duck type it." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T05:03:08.770", "Id": "12283", "ParentId": "12261", "Score": "2" } } ]
{ "AcceptedAnswerId": "12283", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T12:37:56.560", "Id": "12261", "Score": "2", "Tags": [ "python", "classes" ], "Title": "Implementation of a Vector3D class" }
12261
<p>I'm trying to write a Java program that, given a particular number of groups and number of total participants, creates a list of all possible ways to fill that number of groups <em>evenly</em> using <em>all</em> the participants. The group number/order doesn't matter. For instance, if {} denotes one possible way to create a set of groups, [] denotes a group, and each individual is represented by a number, the groupings {[1,2],[3,4,5]} and {[4,3,5],[1,2]} should be considered equivalent and are both valid groupings for an input of 5 participants and 2 groups. </p> <p>So far I've written the following code, which works by recursively finding all possible permutations and removing any duplicates (like in the example above). This works fine for small input values, but becomes extremely slow quickly. Can anyone give my any ideas on how to either optimize this code or for a more efficient way to do this (and if the latter, pseudo or java code would be great)? I know that there might not be an extremely fast way to do this, but I'd like to at least be able to run it with some reasonably small numbers and have it finish in a relatively short time period and not take up more RAM than it has too. </p> <p>Let me know if the above explanation is unclear! Thanks!</p> <pre><code>private int numParticipants, numGroups, maxParticipantsPerGroup; private ArrayList&lt;ArrayList&lt;ArrayList&lt;Integer&gt;&gt;&gt; participantGroups = new ArrayList&lt;ArrayList&lt;ArrayList&lt;Integer&gt;&gt;&gt;(); private void generateParticipantGroupings() { ArrayList&lt;ArrayList&lt;Integer&gt;&gt; groupings = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;(); for (int i = 0; i &lt; numGroups; i++) groupings.add(new ArrayList&lt;Integer&gt;()); buildParticipantGrouping(1, groupings); } private void buildParticipantGrouping(int currentParticipant, ArrayList&lt;ArrayList&lt;Integer&gt;&gt; grouping) { if (currentParticipant &gt; numParticipants) { boolean match = false; for (int j = 0; j &lt; participantGroups.size(); j++) { int numMatches = 0; for (int k = 0; k &lt; numGroups; k++) { for (int m = 0; m &lt; numGroups; m++) { if (grouping.get(k).equals(participantGroups.get(j).get(m))) { numMatches++; break; } } } if (numMatches &gt;= numGroups) { match = true; break; } } if (!match) participantGroups.add(grouping); } else { for (int i = 0; i &lt; numGroups; i++) { if (grouping.get(i).size() &lt; maxParticipantsPerGroup) { ArrayList&lt;ArrayList&lt;Integer&gt;&gt; tempGroupings = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;(); for (int a = 0; a &lt; numGroups; a++) { tempGroupings.add(new ArrayList&lt;Integer&gt;()); for (Integer x : grouping.get(a)) tempGroupings.get(a).add(x); } tempGroupings.get(i).add(currentParticipant); buildParticipantGrouping(currentParticipant + 1, tempGroupings); } } } } </code></pre> <p><strong>EDIT</strong>: Yes, I have searched to see if I can find a previous post that asks the same question. I have <em>not</em> found any. If you can find a previous post asking the same question (that has answers) then I'd love to see it, but otherwise please make sure that a question is actually the same as mine before suggesting it as a duplicate.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T03:33:04.350", "Id": "19671", "Score": "0", "body": "possible duplicate of [All possible combinations of elements](http://stackoverflow.com/questions/1471558/all-possible-combinations-of-elements)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T03:46:31.233", "Id": "19672", "Score": "0", "body": "@TedHopp no, in that question they're just getting ways to create a single group (and of varying length). I want combinations into multiple groups, of (basically) fixed size." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T04:01:08.113", "Id": "19673", "Score": "0", "body": "possible duplicate: http://stackoverflow.com/questions/3931775/java-simple-combination-of-a-set-of-element-of-k-order" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T04:05:36.137", "Id": "19674", "Score": "0", "body": "@RayTayek Again, that's looking for all ways to create ONE group. I'm trying to create multiple groups using all elements." } ]
[ { "body": "<p>First, determine the one or two group sizes that will apply, and how many of each you will have. Define <code>m</code>, the maximum capacity of any one group, as <code>ceil( k / n )</code>. Let <code>i</code> represent the number of groups of size <code>m</code>. Solving for <code>i</code>, we have</p>\n\n<pre><code>m == ceil( k / n )\n( m * i ) + ( ( m - 1 ) * ( n - i ) ) == k\n( m * i ) + ( m * ( n - i ) ) - ( n - i ) == k\n( m * n ) - ( n - i ) == k\n( m * n ) - k - n == -i\nk + ( n * ( 1 - m ) ) == i\n</code></pre>\n\n<p>Thus, there will be <code>i</code> groups of size <code>m</code> and <code>n - i</code> groups of size <code>m - 1</code>.</p>\n\n<p>Then, choose an ordering of the groups. This is like generating an integer with a given number of 1 bits. If <code>k</code> happens to be divisible by 'n', there's only one possible ordering. See <a href=\"https://softwareengineering.stackexchange.com/questions/67065/whats-your-favorite-bit-wise-technique\">Gosper's hack</a> for a nifty way to get the next choice given the current choice, which is essential if you want to implement this as an iterator that yields the next grouping on each call to <code>next()</code>.</p>\n\n<pre><code>class GosperIterator implements Iterator&lt; Long &gt; {\n private final int iParticipants, iGroups, iMaxCap, iHowManyMax;\n private long lCurrentOrder;\n public GosperIterator( int iParticipants, int iGroups ) {\n this.iParticipants = iParticipants;\n this.iGroups = iGroups;\n this.iMaxCap = Math.ceil( iParticipants / iGroups );\n this.iHowManyMax = iParticipants + ( iGroups * ( 1 - iMaxCap ) );\n // implemented only for maximum of 64 groups\n this.lCurrentOrder = ( 1L &lt;&lt; iHowManyMax ) - 1L;\n }\n @Override public boolean hasNext() {\n return lCurrentOrder &lt; ( 1L &lt;&lt; iGroups );\n }\n @Override public Long next() {\n long lOut = lCurrentOrder;\n // Gosper's Hack\n long c = lCurrentOrder &amp; -lCurrentOrder;\n long r = lCurrentOrder + c;\n lCurrentOrder = ( ( ( r ^ lCurrentOrder ) &gt;&gt;&gt; 2 ) / c ) | r;\n return lOut;\n }\n // would be nice if there were a read-only iterator interface\n @Override public void remove() {\n throw new UnsupportedOperationException();\n }\n}\n</code></pre>\n\n<p>Then, allocate each participant <em>x</em> to one of the not full groups which is between the first and the maximum empty group. That means, in particular, that participant 1 always ends up in the first group, participant 2 always ends up in the first or second group (if there are two groups), etc.</p>\n\n<p>To do this one grouping per <code>next()</code> call, you will need to produce the first grouping (all the participants in order, say), then start removing participants in reverse order of participant number, looking for an alternative place to assign them which has a higher group number but no smaller empty group. If no such place exists, back out to a smaller participant number. If you get all the way to participant 1, it is time to call on Gosper again, and if there are no numbers left for Gosper, you're done.</p>\n\n<pre><code>class GroupingWithFixedLayoutIterator implements Iterator&lt; Set&lt; Set&lt; Integer &gt; &gt; &gt; {\n @Override public boolean hasNext() {\n // left as exercise\n }\n @Override public Set&lt; Set&lt; Integer &gt; &gt; next() {\n // left as exercise\n }\n // would be nice if there were a read-only iterator interface\n @Override public void remove() {\n throw new UnsupportedOperationException();\n }\n}\nclass GroupingIterator implements Iterator&lt; Set&lt; Set&lt; Integer &gt; &gt; &gt; {\n private final int iParticipants;\n private final Iterator&lt; Long &gt; ilLayout;\n private Iterator&lt; Set&lt; Set&lt; Integer &gt; &gt; issiGrouping = null;\n\n public GroupingIterator( int iParticipants, int iGroups ) {\n this.iParticipants = iParticipants;\n this.ilLayout = new GosperIterator( iParticipants, iGroups );\n initFixedLayoutIterator();\n }\n private final boolean initFixedLayoutIterator() {\n this.issiGrouping = ilLayout.hasNext()\n ? new GroupingWithFixedLayoutIterator( iParticipants, ilLayout.next() )\n : new EmptyIterator&lt; Set&lt; Set&lt; Integer &gt; &gt; &gt;(); // left as exercise\n }\n @Override public boolean hasNext() {\n return issiGrouping.hasNext() || ilLayout.hasNext();\n }\n @Override public Set&lt; Set&lt; Integer &gt; &gt; next() {\n if ( !issiGrouping.hasNext() )\n initFixedLayoutIterator();\n return issiGrouping.next();\n }\n // would be nice if there were a read-only iterator interface\n @Override public void remove() {\n throw new UnsupportedOperationException();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T05:41:32.740", "Id": "19675", "Score": "0", "body": "did you actually read my question fully? I need to get ALL possible unique groupings, not just any one grouping." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T05:45:13.590", "Id": "19676", "Score": "0", "body": "Each time I say \"choose\", or \"one of\", I am implying that you will loop over all possible choices. There are a very large number of combinations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T05:53:15.243", "Id": "19677", "Score": "0", "body": "ok, sorry I misunderstood. could you be a little bit more concrete (or maybe give some pseudo code) as to how this would actually work (how you'd pick the groups/participants so that every combination was listed, in an efficient manner)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T06:49:57.613", "Id": "19678", "Score": "0", "body": "I'll try to answer this in parts. The fundamental principle is going to be that we need to yield one grouping at a time, because there are so many possibilities that they will never all fit into memory." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T05:20:41.103", "Id": "12263", "ParentId": "12262", "Score": "1" } }, { "body": "<p>An other (complementary) way to optimize if is rather than creating an <code>ArrayList&lt;ArrayList&lt;ArrayList&lt;Integer&gt;&gt;&gt;</code>, create an implmentation of <code>Iterable&lt;ArrayList&lt;ArrayList&lt;Integer&gt;&gt;&gt;</code> that would internaly store the variables of the outer loop in it's <code>Iterator&lt;ArrayList&lt;ArrayList&lt;Integer&gt;&gt;</code> instances, and perform an iteration each time <code>next()</code> is called. This way, you will have only one instance of <code>ArrayList&lt;ArrayList&lt;Integer&gt;&gt;</code> in RAM at a time.</p>\n\n<p>Then do what you have to do with this <code>Iterable</code> rather that the <code>ArrayList</code>. Implementing things this way would <strong><em>dramatically reduce your RAM usage</em></strong>, which means less allocations and less cache misses. This will not change the complexity of the algorithm, but that can still improve performance a lot. Also, your algorithm will be able to go much further before dying from out of memory.</p>\n\n<p>Not: of course, if you use this solution, you must not use the iterator to store all the instances in an ArrayList or you loose all the benefit. The idea is to do all the processing in a \"Stream mode\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T07:16:12.277", "Id": "12264", "ParentId": "12262", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T03:30:50.117", "Id": "12262", "Score": "1", "Tags": [ "java", "optimization", "recursion" ], "Title": "Create a list of all possible combinations of elements into n-groups from a set of size k" }
12262
<p>Is this a reasonable C++ wrapper function for Python's "list.count([character])" method?</p> <pre><code>int count( char CHAR, string STR ) { int counter = 0; for ( int i = 0 ; i &lt; STR.size() - 1 ; i++ ) { if ( STR[i] == CHAR ) { counter++; } } return counter; } //Edited "for( int i = 0 ; i++ &lt; STR.size-1 ; )" to "for(int i = 0 ; i &lt; STR.size ; i++)" now it counts the first char of the string =D </code></pre> <p>Tested it...works exactly like the python &lt;3</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T05:06:01.857", "Id": "19710", "Score": "3", "body": "you seem confused about what a wrapper function is. A wrapper function should call what it is wrapping, not reimplement it." } ]
[ { "body": "<p>When STR is empty, STR.size() returns 0u. As a result, STR.size()-1 becomes maximum value of unsigned size type. i++ &lt; STR.size()-1. This will lead the function to crash.</p>\n\n<p>Also your function will not count CHAR of the first character of STR.</p>\n\n<p>You may want to use standard library.</p>\n\n<p><a href=\"http://www.cplusplus.com/reference/algorithm/count/\" rel=\"nofollow\">std::count(begin, end, CHAR)</a> is just what you are looking for.</p>\n\n<p>for example,</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;string&gt;\n\n...\nchar CHAR = 'l';\nstd::string STR(\"Hello World!\");\nptrdiff_t counter = std::count(STR.begin(), STR.end(), CHAR);\n...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T10:36:53.417", "Id": "19679", "Score": "0", "body": "Oh...im reading primer C++ n its pretty basic so i never even knew this existed in C++ :( do you have any suggestions on some great books/resources i can use to get myself up and coding in C++ the right way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T11:00:38.000", "Id": "19681", "Score": "0", "body": "@BUCKSHOT - see this FAQ-entry: http://stackoverflow.com/q/388242/1025391" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T10:33:10.580", "Id": "12266", "ParentId": "12265", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T10:25:01.090", "Id": "12265", "Score": "1", "Tags": [ "c++", "python" ], "Title": "C++ wrapper function for Python's \"list.count([character])\" method?" }
12265
<p>I'm just trying to see if there's a better way to write the code between the asterisk markers.</p> <pre><code>&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Activate extends CI_Controller { public function __construct() { parent::__construct(); $this-&gt;load-&gt;model('users/usersmodel'); } public function index() { //Config Defaults Start $msgBoxMsgs = array();//msgType = dl, info, warn, note, msg $cssPageAddons = '';//If you have extra CSS for this view append it here $jsPageAddons = '';//If you have extra JS for this view append it here $metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's $siteTitle = '';//alter only if you need something other than the default for this view. //Config Defaults Start //examples of how to use the message box system (css not included). //$msgBoxMsgs[] = array('msgType' =&gt; 'dl', 'theMsg' =&gt; 'This is a Blank Message Box...'); /**********************************************************Your Coding Logic Here, Start*/ $userID = $this-&gt;uri-&gt;segment(2); $registrationKey = $this-&gt;uri-&gt;segment(3); if ( ((!is_numeric($userID)) || (is_null($userID))) || ((is_null($registrationKey)) || (!preg_match('/^[A-Za-z0-9]+$/', $registrationKey))) ) { $bodyContent = $this-&gt;config-&gt;item('defaultTemplate') ."/404";//which view file } else { $registrationDetails = $this-&gt;usersmodel-&gt;getRegistrationDetails($userID); if (!is_null($registrationDetails)) { if ($this-&gt;usersmodel-&gt;activateUser($userID, $registrationKey)) { $jsPageAddons .= '&lt;script src='.base_url().'assets/'. $this-&gt;config-&gt;item('defaultTemplate') .'/js/validate/activate.js&gt;&lt;/script&gt;'; $message = 'User was activated successfully! You may now login!'; $bodyContent = $this-&gt;config-&gt;item('defaultTemplate') ."/usermanagement/forms/activate";//which view file } else { $message = 'User was not activated successfully! Please try again with the right credentials!'; $bodyContent = $this-&gt;config-&gt;item('defaultTemplate') ."/usermanagement/forms/activate";//which view file } $this-&gt;data['message'] = $message; } else { $bodyContent = $this-&gt;config-&gt;item('defaultTemplate') ."/404"; } } $bodyType = "full";//type of template /***********************************************************Your Coding Logic Here, End*/ //Double checks if any default variables have been changed, Start. //If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing. if(count($msgBoxMsgs) !== 0) { $msgBoxes = $this-&gt;msgboxes-&gt;buildMsgBoxesOutput(array('display' =&gt; 'show', 'msgs' =&gt;$msgBoxMsgs)); } else { $msgBoxes = array('display' =&gt; 'none'); } if($siteTitle == '') { $siteTitle = $this-&gt;metatags-&gt;SiteTitle(); //reads } //Double checks if any default variables have been changed, End. $this-&gt;data['msgBoxes'] = $msgBoxes; $this-&gt;data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view. $this-&gt;data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view. $this-&gt;data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php $this-&gt;data['bodyType'] = $bodyType; $this-&gt;data['bodyContent'] = $bodyContent; $this-&gt;load-&gt;view($this-&gt;config-&gt;item('defaultTemplate') .'/usermanagement/index', $this-&gt;data); } } /* End of file activate.php */ /* Location: ./application/controllers/activate.php */ </code></pre>
[]
[ { "body": "<p>i think a good way to improve the code would be using exceptions and extracting some stuff into reusable code. </p>\n\n<p>you could change </p>\n\n<pre><code>$userID = $this-&gt;uri-&gt;segment(2);\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$userId = $this-&gt;getUserIdByUri($this-&gt;uri)\n</code></pre>\n\n<p>this way you have a single point of change if the user id should ever move from segment 2 to 3 r any other segment or event out of the uri. (same for the registrationKey)</p>\n\n<pre><code>if ( ((!is_numeric($userID)) || (is_null($userID))) || ((is_null($registrationKey)) || (!preg_match('/^[A-Za-z0-9]+$/', $registrationKey))) )\n</code></pre>\n\n<p>thats the point where i would start my try/catch block and extract the validation into another method like</p>\n\n<pre><code>try {\n $this-&gt;checkUserId($userID)\n} catch (InvalidUserIdException) {\n $bodyContent = $this-&gt;config-&gt;item('defaultTemplate') .\"/404\";\n}\n</code></pre>\n\n<p>same thing for $registrationDetails just export the check into a checkRegistrationDetails method and throw an exception. </p>\n\n<p>one more thing would be to extract some \"magic strings / values\" into const values\nlike</p>\n\n<pre><code>const TEMPLATE_DEFAULT = 'defaultTemplate';\nconst TEMPLATE_FORM_ACTIVE = '/usermanagement/forms/activate';\n</code></pre>\n\n<p>but i think thats a thing of taste. so after my changes the code would look like</p>\n\n<pre><code>/**********************************************************Your Coding Logic Here, Start*/\n\n $userID = $this-&gt;getUserIdByUri($this-&gt;uri);\n $registrationKey = $this-&gt;getRegKeyByUri($this-&gt;uri);\n\n try {\n $this-&gt;checkUserId($userID); // throw InvalidUserIdException\n\n $registrationDetails = $this-&gt;usersmodel-&gt;getRegistrationDetails($userID);\n $this-&gt;checkRegistrationDetails($registrationDetails); // throws InvalidRegDetails\n\n if ($this-&gt;usersmodel-&gt;activateUser($userID, $registrationKey))\n {\n $jsPageAddons .= $this-&gt;getActivJS();\n $message = 'User was activated successfully! You may now login!';\n $bodyContent = $this-&gt;config-&gt;item(self::TEMPLATE_DEFAULT) . self::TEMPLATE_FORM_ACTIVATE;//which view file\n }\n else\n {\n $message = 'User was not activated successfully! Please try again with the right credentials!';\n $bodyContent = $this-&gt;config-&gt;item(self::TEMPLATE_DEFAULT) . self::TEMPLATE_FORM_ACTIVATE;//which view file\n\n }\n $this-&gt;data['message'] = $message;\n\n } catch (InvalidUserIdException $e) {\n $bodyContent = $this-&gt;config-&gt;item('defaultTemplate') .\"/404\";\n } catch (InvalidRegDetails $e) {\n $bodyContent = $this-&gt;config-&gt;item('defaultTemplate') .\"/404\";\n } catch (Exception $e) {\n // something unexpected happened (- ;\n }\n\n\n $bodyType = \"full\";//type of template\n\n /***********************************************************Your Coding Logic Here, End*/\n</code></pre>\n\n<p>maybe i could help you a little. These things i pointed out are not any rules you HAVE to follow. Just some advice (- : </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T08:41:33.663", "Id": "19718", "Score": "0", "body": "updated my post! what do you think now?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T08:43:50.260", "Id": "19719", "Score": "0", "body": "can you better explain the top part of your answer with factoring in the uri segments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T08:52:39.203", "Id": "19720", "Score": "1", "body": "the uri segment is just another seperation of code. For now you have hardcoded that your id is in segment 3 which also is a \"magic number\". Also what is \"$this->kow->\" in your update? typo?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T09:02:32.263", "Id": "19721", "Score": "0", "body": "kow is my library that is different functions I use across my scripts" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T13:33:00.033", "Id": "19728", "Score": "0", "body": "Knew I forgot to mention something. Those magic numbers!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T16:27:03.093", "Id": "19740", "Score": "0", "body": "Magic numbers??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T11:21:02.720", "Id": "19772", "Score": "0", "body": "see SO:[what-is-a-magic-number-and-why-is-it-bad](http://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T18:49:47.653", "Id": "12274", "ParentId": "12268", "Score": "2" } }, { "body": "<p>I know you are specifically asking about just the code between the commented section, but I feel the rest deserves some attention as well. I will try to focus primarily upon what you requested though.</p>\n\n<p><strong>Separating Your Code</strong></p>\n\n<p>First off, there is no reason for all that code to be contained in a single method. Separate your code into smaller pieces so that they perform single functions. This improves legibility, is helpful for debugging, and makes your code more reusable, among other things. As I go through I'll try and point out a few examples.</p>\n\n<p><strong>Verifying Your Variables</strong></p>\n\n<p>There's a few things I would change about how you are currently verifying your variables. First, you should separate the processes, not just by moving it to a new method, but you should also separate it by variable. Right now you are checking for both <code>$userID</code> and <code>$registrationKey</code> together. There's nothing wrong with it except that it is a little hard to read and does not allow for custom error support should you decide to do so at a future date. Second, assuming you are not using 0 as a value for either of those two variables, you can just check each as a boolean (<code>! $var</code>) instead of using <code>is_null()</code>. This way you can perform the same function on values other than numeric or null without needing to write additional conditions. Checking it as a boolean will return FALSE if its values is empty, FALSE, NULL, 0, or a string version of any of those. The final way in which I would change this, is by moving your <code>preg_match()</code> statement outside of the if statement. How you have it now strongly contributes to its illegibility. These points also hold true for <code>$registrationDetails</code>.</p>\n\n<pre><code>private function _verify( $userID, $registrationKey ) {\n if( ! $userID || ! is_numeric( $userID ) ) { return FALSE; }\n\n $matches = preg_match('/^[A-Za-z0-9]+$/', $registrationKey);//You should comment this to explain what it does\n if ( ! $registrationKey || ! $matches ) { return FALSE; }\n\n return TRUE;\n}\n\n//Usage\nif( ! $this-&gt;_verify( $userID, $registrationKey ) ) { $bodyContent = $this-&gt;config-&gt;item( 'defaultTemplate' ) . '/404'; }\n</code></pre>\n\n<p>Take a look at PHP's <code>filter_var()</code> function (PHP >= 5.2) as a better way of verifying your variables. I didn't mention it until now so that I could comment on the above as it can be adapted elsewhere in your code, not necessarily here, but maybe in your other code. With <code>filter_var()</code> you can just use the desired flag(s) to specify the type of data you want a variable to contain and it will verify it and/or sanitize it or return FALSE if it does not meet its criteria. Also, I'm not sure what your regex statement does, but I'm sure this function can do something similar for you.</p>\n\n<pre><code>if( ! filter_var( $userID, FILTER_VALIDATE_INT ) ) { //etc... }\n</code></pre>\n\n<p><strong>Reusing Code</strong></p>\n\n<p>This is a simple instance of it, but instead of continuously writing out the bit for the \"404\" page, I would make it into a function to return that value.</p>\n\n<pre><code>private function _return404() { return $this-&gt;config-&gt;item( 'defaultTemplate' ) . '/404'; }\n</code></pre>\n\n<p>Here's a better example. When you are verifying your <code>$registrationDetails</code>. Your <code>$bodyContent</code> remains the same unless <code>$registrationDetails</code> is null, the only thing that changes is your message, so I would change it to something more like...</p>\n\n<pre><code> if ( ! $registrationDetails) {\n $message = 'User was not activated successfully! Please try again with the right credentials!';//Message will change on success\n\n if ($this-&gt;usersmodel-&gt;activateUser($userID, $registrationKey))\n {\n $jsPageAddons .= '&lt;script src='.base_url().'assets/'. $this-&gt;config-&gt;item('defaultTemplate') .'/js/validate/activate.js&gt;&lt;/script&gt;';\n $message = 'User was activated successfully! You may now login!'; \n }\n\n $bodyContent = $this-&gt;config-&gt;item('defaultTemplate') .\"/usermanagement/forms/activate\";//which view file \n $this-&gt;data['message'] = $message; \n }\n</code></pre>\n\n<p>Also, you never use <code>$registrationDetails</code> except as a check. If that is its only purpose, you should create a method in your user model called <code>isRegistered()</code> and have it return a boolean so that you can use it for that purpose. No need to load what I'm assuming is an array of credentials just to verify a user has been registered.</p>\n\n<p><strong>jsPageAddons</strong></p>\n\n<p>Assuming that only the file itself, and maybe the last directory changes, I would convert <code>$jsPageAddons</code> to accept an array of filenames and pass it to a method to return the appropriate string. This way you do not have to rewrite each script tag. This also holds for <code>$cssPageAddons</code>.</p>\n\n<pre><code>private function _setScript( $file ) { return '&lt;script src=\"' . base_url() . \"assets/{$this-&gt;config-&gt;item('defaultTemplate')}/js/$file.js\\\"&gt;&lt;/script&gt;\"; }\n//Usage\n$scripts = '';\nforeach( $jsPageAddons AS $file ) { $scripts .= $this-&gt;_setScript( $file ); }//$file = 'validate/activate';\n</code></pre>\n\n<p>Or, if you were to do it in the view:</p>\n\n<pre><code>//set in controller $jsPath = base_url() . \"assets/{$this-&gt;config-&gt;item('defaultTemplate')}/js/\";\n&lt;?php foreach( $jsPageAddons AS $file ) : ?&gt;\n\n&lt;script src=\"&lt;?php echo $jsPath . $file; ?&gt;\"&gt;&lt;/script&gt;\n\n&lt;?php endforeach; ?&gt;\n</code></pre>\n\n<p><strong>Site Variables</strong></p>\n\n<p>Instead of typing out each of your site variables like so:</p>\n\n<pre><code>$this-&gt;data['msgBoxes'] = $msgBoxes;\n</code></pre>\n\n<p>It would be smarter to do it like so:</p>\n\n<pre><code>$this-&gt;data = compact(\n 'msgBoxes',\n 'cssPageAddons',\n 'jsPageAddons',\n 'siteTitle',\n 'bodyType',\n 'bodyContent'\n);//$msgBoxes, $cssPageAddons, $jsPageAddons, $siteTitle, $bodyType, $bodyContent\n</code></pre>\n\n<p>I added the comment at the end so that your IDE can find those variables later if needed as <code>compact()</code> is not very IDE friendly.</p>\n\n<p><strong>Minor Things</strong></p>\n\n<p>You have excessive parenthesis. Half of them aren't necessary and its already challenging to tier your braces, brackets, and parenthesis without adding extra :)</p>\n\n<p>if ( (!is_numeric($userID) || is_null($userID)) || (is_null($registrationKey) || !preg_match('/^[A-Za-z0-9]+$/', $registrationKey)) ) </p>\n\n<p>Unless you are specifically looking for \"0\" do not use equality operators on integers, use the greater than <code>&gt;</code> or less than <code>&lt;</code> operators.</p>\n\n<pre><code>if(count($msgBoxMsgs) &gt; 0) { //etc...\n</code></pre>\n\n<p>This is preference really, but I hardly ever see <code>is_null()</code> anymore. Its still supported, and probably always will be. But more often I see an equality comparison <code>=== NULL</code>. In the documentation it is show to be faster as well, but that doesn't matter unless you are an optimization nut.</p>\n\n<p>You'll probably want to perform the same function on <code>$siteTitle</code> whether it is empty, FALSE, NULL, or 0. So this will be another one of those instances where I'd just perform a boolean comparison on it.</p>\n\n<pre><code>if( ! $siteTitle ) { //etc...\n</code></pre>\n\n<p><strong>Final Thoughts</strong></p>\n\n<p>braunbaer had some good advice as well.</p>\n\n<p>Now I'm assuming that the code that you highlighted is your own and the code wrapping it is part of a framework. Otherwise, why do you have all these variables that you never use? The only one I see you use is <code>$jsPageAddons</code>, and then <code>$siteTitle</code> is checked even though nothing was done to it before being set by an outside method. The rest are always blank. If it is necessary for your rendering method to have all these fields to work, you might want to take a look at it too. Perform <code>isset()</code> checks on those values you have not set and only set those you need, when you need them. Processing all these other variables is just dead weight. Admittedly light dead weight, but dead weight none-the-less. And confusing. If these are only here as a guideline of what variables to use and their types, I would document it in the PHPDOC comments instead.</p>\n\n<p>Also, you have a 0% acceptance ratio. I don't know if this is because you are new and SO starts you off at 0 (don't think so) or if you just don't give credit to those who answer your questions. You aren't likely to get much help if you don't go back and accept some of those answers. I like helping which is why I answered your question, but some others might not feel the same and will ignore your questions because of it. Just a friendly pointer :) Good luck!</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>The changes that you made look fine. I am a little confused as to where <code>isRegistered()</code> is defined so that it can be called like a normal function instead of a method though. Assuming this was an oversight.</p>\n\n<p>Just had a thought on how to improve it even more. No need to set your <code>$bodyContent</code> so many times. It directs to a 404 page if there are any issues, so you only need to worry about changing it if there is success. Just set it up initially to direct to the 404. This means that the <code>return404()</code> method I suggested is now unnecessary, unless you use it elsewhere.</p>\n\n<pre><code>$bodyContent = $this-&gt;kow-&gt;return404();\n\nif( $this-&gt;verify( $userID, $registrationKey ) ) {\n if ( ! isRegistered( $userID ))\n {\n $message = 'User was not registered successfully! Please try again with the right credentials!'; \n\n if ($this-&gt;usersmodel-&gt;activateUser($userID, $registrationKey))\n {\n $jsPageAddons .= '&lt;script src='.base_url().'assets/'. $this-&gt;config-&gt;item('defaultTemplate') .'/js/validate/activate.js&gt;&lt;/script&gt;';\n $message = 'User was activated successfully! You may now login!'; \n }\n\n $bodyContent = $this-&gt;config-&gt;item('defaultTemplate') .\"/usermanagement/forms/activate\";//which view file \n $this-&gt;data['message'] = $message; \n }\n}\n</code></pre>\n\n<p>One last thing I noticed. You are not setting <code>$data['message']</code> with the rest of the <code>$data</code> array. I'm assuming it is because <code>$message</code> is not always set. If I were you, I would create an empty <code>$message</code> variable in with the \"Config Defaults\" and move that <code>$data</code> array definition with the rest to keep your coding logic together.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T16:26:38.617", "Id": "19738", "Score": "0", "body": "This is really awesome however what do you mean \"Config Defaults\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T16:40:24.153", "Id": "19741", "Score": "0", "body": "You have them wrapped between two comments (`//Config Defaults Start`) at the start of your index() method..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T17:44:30.953", "Id": "19744", "Score": "0", "body": "I updated my post once more. Please look over and thank you." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T20:05:53.503", "Id": "12277", "ParentId": "12268", "Score": "4" } } ]
{ "AcceptedAnswerId": "12277", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T15:48:02.983", "Id": "12268", "Score": "-1", "Tags": [ "php", "codeigniter" ], "Title": "User registration / activation process for a website" }
12268
<p>I have files containing data set which contain 11,000 rows. I have to run a loop through each row, this is taking me 25minutes for each file. I am using following code:</p> <pre><code>z &lt;- read.zoo("Title.txt", tz = "") for(i in seq_along(z[,1])) { if(is.na(coredata(z[i,1]))) next ctr &lt;- i while(ctr &lt; length(z[,1])) { if(abs(coredata(z[i,1])-coredata(z[ctr+1,1])) &gt; std_d) { z[ctr+1,1] &lt;- NA ctr &lt;- ctr + 1 } else { break } } } </code></pre> <p>Where <code>"Title.txt"</code> is file containing 11,000 rows. It looks like (first five rows):</p> <pre><code>"timestamp" "mesured_distance" "IFC_Code" "from_sensor_to_river_bottom" "1" "2012-06-03 12:30:07-05" 3188 1005 3500 "2" "2012-06-03 12:15:16-05" 3189 1005 3500 "3" "2012-06-03 12:00:08-05" 3185 1005 3500 "4" "2012-06-03 11:45:11-05" 3191 1005 3500 "5" "2012-06-03 11:30:15-05" 3188 1005 3500 </code></pre> <p>I wish to receive help on how should I increase the speed for this code?</p> <p>Here is how the code works:</p> <pre><code> set.seed(100) x=rnorm(15) std_d=sd(x) </code></pre> <p>afer running code. It gives this:</p> <pre><code> m [1] -0.50219235 NA -0.07891709 NA 0.11697127 0.31863009 NA [8] 0.71453271 NA NA NA NA NA 0.73984050 [15] NA </code></pre> <p>It replaces the next element(e2) with NA if the subtraction(e1-e2) is > std_d and then checks e1 with e3 if (e1-e3) is > std_d then it replaces e3, if it was &lt; std_d then it would check e3-e4 and so on.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T02:53:05.767", "Id": "19697", "Score": "0", "body": "Is `coredata` an array lookup or a function call?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T02:57:06.413", "Id": "19698", "Score": "0", "body": "its a function call, from the package-zoo." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T03:03:33.853", "Id": "19699", "Score": "1", "body": "Have you profiled your code? Since you are creating new zoo objects countless times, I wouldn't be surprised if most of the time were spent in `[.zoo` or `coredata`: if it is the case, extracting the array once before the loop may speed things up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T03:20:00.723", "Id": "19700", "Score": "0", "body": "okay ill try that...what if this is not the case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T06:11:23.443", "Id": "19701", "Score": "2", "body": "Possible duplicate - http://stackoverflow.com/questions/10823971/clean-up-the-dataset. Also looks like a homework problem with 2 different people on same problem" } ]
[ { "body": "<p>Revised: ...I wonder if this could replace those two loops? Here are the results with the test vector offered in your comments:</p>\n\n<pre><code>set.seed(100); m=rnorm(15); std_d &lt;- sd(m)\nReduce(function(y,xx){ if( abs(tail(y[!is.na(y)], 1) - xx) &gt; std_d ) {c(y,NA)}else{ \n c(y,xx)} }, \n m )\n [1] -0.50219235 NA -0.07891709 NA 0.11697127 0.31863009 NA 0.71453271\n [9] NA NA NA NA NA 0.73984050 NA\n</code></pre>\n\n<p>Here's original test case with revised results. It is now comparing the last non-NA value to the current one and making NA if it exceeds the standard value. That other solution looked at the running sd() but your code did not do that so I just used a global sd value:</p>\n\n<pre><code>&gt; z &lt;- read.zoo(text=' \"timestamp\" \"mesured_distance\" \"IFC_Code\" \"from_sensor_to_river_bottom\"\n \"1\" \"2012-06-03 12:30:07-05\" 3188 1005 3500\n \"2\" \"2012-06-03 12:15:16-05\" 3189 1005 3500\n \"3\" \"2012-06-03 12:00:08-05\" 3185 1005 3500\n \"4\" \"2012-06-03 11:45:11-05\" 3191 1005 3500\n \"5\" \"2012-06-03 11:30:15-05\" 3188 1005 3500', tz = \"\")\n std_d &lt;- sd(coredata(z[,1]) )\n zx &lt;- as.numeric(coredata(z[,1]))\n coredata(z[,1]) &lt;- Reduce(function(y,xx){ \n if( abs(tail(y[!is.na(y)], 1) - xx) &gt; std_d ) {\n c(y,NA)} else { \n c(y,xx)} }, \n zx )\n z\n mesured_distance IFC_Code from_sensor_to_river_bottom\n2012-06-03 11:30:15 3188 1005 3500\n2012-06-03 11:45:11 NA 1005 3500\n2012-06-03 12:00:08 NA 1005 3500\n2012-06-03 12:15:16 3189 1005 3500\n2012-06-03 12:30:07 3188 1005 3500\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T03:56:10.287", "Id": "19702", "Score": "0", "body": "Sorry, but it doesn't. Your code detects whether there are any na values. But my code converts the z[ctr+1,1] values, which satisfy the condtion, to NA.\nI'll be grateful to you if you can provide something as this short for my entire code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T04:22:09.400", "Id": "19703", "Score": "0", "body": "set.seed(100)\n> m=rnorm(15)\n> m\n [1] -0.50219235 0.13153117 -0.07891709 0.88678481 0.11697127 0.31863009 -0.58179068\n [8] 0.71453271 -0.82525943 -0.35986213 0.08988614 0.09627446 -0.20163395 0.73984050\n[15] 0.12337950\n\n\nThis what my code does:\n\n m\n [1] -0.50219235 NA -0.07891709 NA 0.11697127 0.31863009 NA\n [8] 0.71453271 NA NA NA NA NA 0.73984050\n[15] NA\n\nsee this link:\nhttp://stackoverflow.com/questions/10823971/clean-up-the-dataset\nThings in code are perfectly explained there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T04:28:57.540", "Id": "19704", "Score": "0", "body": "@DWin-I have edited the question to explain the code in more detail." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T04:39:09.843", "Id": "19705", "Score": "0", "body": "Sorry but the solution you provided gives me incorrect output.\nI tried using array instead of coredata(z[,1]), but it still takes a long time...around 12min." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T08:07:27.733", "Id": "19706", "Score": "0", "body": "Thats great. Its working. Takes very less time. Thanks" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T03:28:20.577", "Id": "12281", "ParentId": "12280", "Score": "6" } } ]
{ "AcceptedAnswerId": "12281", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T02:44:14.547", "Id": "12280", "Score": "1", "Tags": [ "performance", "r" ], "Title": "increase speed for 'for loop'" }
12280
<p>In my last question on Stack Overflow I was a very confused newcomer about classes and OOP and how to correctly implement everything to make things easier. So I started a different example to practice.</p> <p>This has the classes of a band and person. The people audition but only some get in and the rest leave to form their own group. Then there's a battle of the bands and bands face off. Here is my code.</p> <pre><code>&lt;? class Start{ var $name; var $type; //If construct not set, this is the construct. function __construct($name){ $this-&gt;name = $name; } } class Band extends Start{ var $name; var $type; var $membersAndInstruments = array(); var $badArray = array(); //Specify starting parameters. function __construct($type, $name){ $this-&gt;type = $type; $this-&gt;name = $name; echo isset($this-&gt;name) ? "This " . $type . " band called " . $this-&gt;name . " has just been formed!" //If name is set : "This band was formed. Genre: " . $type; //If name isn't. } //Add new members. Instrument =&gt; Member function recruitMembers($instrument, $member){ $this-&gt;membersAndInstruments[$instrument] = $member; //echo $instrument; } //Reject members from the audition function reject($instrument, $rejectee){ $this-&gt;badArray[] = array($instrument =&gt; $rejectee); } //Show the ones who didn't make it function sorryReject($msgStart, $msgEnd){ echo "&lt;br /&gt;&lt;br /&gt;$msgStart, "; foreach($this-&gt;badArray as $k =&gt; $v){ //$k = array_values($k); $v = array_values($v); echo $v[0]; if ($k != count($this-&gt;badArray)-1){ echo ", "; } } echo ". $msgEnd&lt;/br&gt;"; } //Show the members in the group and their instruments. function displayMembers(){ foreach($this-&gt;membersAndInstruments as $craft =&gt; $member){ echo "&lt;br /&gt;" . $member . " as " . $craft ; } } //Challenge other bands. Input a band or an Array of bands. function battle($band2, $winMsg){ echo "&lt;br /&gt;&lt;br /&gt; BATTLE OF THE BANDS &lt;br /&gt;&lt;br /&gt;"; $band1 = $this; if (!is_array($band2)){ $contestants = array($band1, $band2); //Ready bands }else{ $contestants = array($band1); foreach($band2 as $bandX){ $contestants[] = $bandX; } //var_dump($contestants); } //Count members once and store in array of the same order the bands were entered for($i = 0; $i &lt; count($contestants); $i++){ $numOfMembers[] = count($contestants[$i]-&gt;membersAndInstruments); } //echo "&lt;br /&gt;"; //var_dump($contestants); //var_dump($numOfMembers); $moreMembers = ($numOfMembers[0] &gt; $numOfMembers[1]) ? 0 : 1; //Set to the index that has more. $winner = Randomizer($contestants, $contestants[$moreMembers], $numOfMembers[$moreMembers]); echo $winner-&gt;name . " $winMsg"; } } class Person extends Start{ var $goodAtInstrument; function __construct($name, $good){ $this-&gt;name = $name; $this-&gt;goodAtInstrument = $good; } function audition($band, $good, $instrument){ $this-&gt;goodAtInstrument = $instrument; $instrument = killTheLastLetter($instrument, "s"); $instrument != "Drum" ? $instrument .= "ist" : $instrument .= "mer"; if ($good){ $band-&gt;recruitMembers($instrument, $this-&gt;name); }else{ $band-&gt;reject($instrument, $this-&gt;name); //echo "&lt;br /&gt; Sorry, " . $this-&gt;name . "....you didn't make it."; } } } //Looks for a specified ending letter and cuts it if found and returns. function killTheLastLetter($input, $cutThisLetter){ if (substr($input, -2, 2) == "ss"){ return $input; } substr($input, -1) == $cutThisLetter ? $input = substr($input, 0, -1) : $input = $input; return $input; } function Randomizer($choiceArray, $chanceChoice, $chances = 0){ !$choiceArray ? $TorF = array(true, false) : $TorF = $choiceArray; for($i = 0; $i &lt; $chances; $i++){ //echo "DOJNE"; $TorF[] = $chanceChoice; } //var_dump($TorF); $random = array_rand($TorF); //echo $random; return $TorF[$random]; } //==================================================================================================== $FirstRockBand = new Band("Progressive Rock","Erais"); $bandMembers = array ( "Bass" =&gt; $M1 = new Person("Shepard", Randomizer()), "Guitar" =&gt; $M2 = new Person("Sy", Randomizer()), "Drums" =&gt; $M3 = new Person("Chris", Randomizer()), "Keyboards" =&gt; $M4 = new Person("Jill", Randomizer()), "Vocals" =&gt; $M5 = new Person("Michele", Randomizer()), "Cowbell" =&gt; $M6 = new Person("Ben", Randomizer()) ); echo "&lt;br /&gt; Welcome to the auditions. &lt;br /&gt;"; foreach($bandMembers as $k =&gt; $v){ $v-&gt;audition($FirstRockBand, $v-&gt;goodAtInstrument, $k); } $FirstRockBand-&gt;displayMembers(); //echo count($FirstRockBand-&gt;badArray); if (count($FirstRockBand-&gt;badArray) &gt; 0){ $FirstRockBand-&gt;sorryReject("Sorry", "you didn't make it in."); echo "&lt;br /&gt;&lt;br /&gt; The rejected members have started their own group: " . $SecondRockBand-&gt;name . "&lt;br /&gt;&lt;br /&gt;"; $SecondRockBand = new Band("Death Metal", "Sideshow Hubris"); $RockBands = array( $FirstRockBand, $SecondRockBand ); foreach($FirstRockBand-&gt;badArray as $k =&gt; $v){ foreach($v as $inst =&gt; $member){ $SecondRockBand-&gt;recruitMembers($inst, $member); } } //echo '&lt;div style = "background-color: 00FFFF"&gt;'; $SecondRockBand-&gt;displayMembers(); //echo "&lt;/div&gt;"; //Battle of the Bands! Scales tipped on the side that has more members. Need to work on the whole talent thing. $FirstRockBand-&gt;battle($SecondRockBand, "blew the crowd away!"); } </code></pre> <p>Some things seem iffy to me, like plugging members into an array and then going through other arrays and so on. But PHP isn't exactly interactive so unless I'm reading from a DB all answers should already be in there....</p> <p>Anyway, if you could please look this over and tell me if this is confusing or if I seem to be using classes correctly and what else I could fix.</p>
[]
[ { "body": "<p>Just two quick notes: </p>\n\n<ol>\n<li><p>From Clean Code by Robert C. Martin:</p>\n\n<blockquote>\n <p>A class name should not be a verb.</p>\n</blockquote>\n\n<p>So, <code>Start</code> does not seem a good name. </p></li>\n<li><p>Furthermore, it seems that <code>Band</code> \"is-a\" <code>Start</code> is not true. Check <a href=\"https://stackoverflow.com/questions/2218937/has-a-is-a-terminology-in-object-oriented-language\">HAS-A, IS-A terminology in object oriented</a> on StackOverflow and the linked resources in that question.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T08:26:48.200", "Id": "19716", "Score": "0", "body": "Alright, the only reason I called it Start was because it looked like default was already taken. Maybe a constant. I'll keep those in mind thanks. Are these the biggest problems you see?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T19:23:26.557", "Id": "19753", "Score": "0", "body": "@braunbaer was faster, +1 for him :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T08:19:38.107", "Id": "12286", "ParentId": "12284", "Score": "2" } }, { "body": "<p>I think you have to rethink your code (- ;</p>\n\n<p>as palacsint pointed out, there is some bad naming involved but whats more troublesome is why you extend \"start\". </p>\n\n<p>the only reason i can think of why you did this is that person and band has \"name\" in common. Well thats not how it works. You do not put common things into parent classes and extend these as you see fit (at least it is not a good design)</p>\n\n<p>Band and Person are totaly seperate enteties. There is nothing to gain to have the same parentclass. </p>\n\n<p>If you want to make sure that everything which has a name will implement something, use interfaces. You could do something like this</p>\n\n<pre><code>interface HasName {\n public function getName(); \n}\n\nclass Band implements HasName {}\nclass Person implements HasName {}\n</code></pre>\n\n<p>Also there is the possibility to implement multiple interfaces but you can extend only from one parent. The name of the interface \"HasName\" is already a hint that it is not a good interface. If interested you should read about interfaces and naming guides.</p>\n\n<p>So how would i do it?</p>\n\n<p>If you want \"default stuff\" to inherit from use an abstract class</p>\n\n<pre><code>abstract class Band {\n //...\n public function addMember(Person $Person) {\n\n }\n\n public function getMembers() {\n\n }\n //...\n}\n</code></pre>\n\n<p>You put all the stuff every band has in common in there, you forge the behavior of \"Band\" every Band will behave like the Abstract class this has many benefits. </p>\n\n<p>Now you have the possibility to extend this class if you would like to add features like</p>\n\n<pre><code>class RockBand extends Band {\n public function smashGuitar() {\n\n }\n}\n</code></pre>\n\n<p>Also you should seperate concerns, i dont think \"battle\" is a concern of Band nor is \"audition\" a concern of Person. These are methods you should seperate in own classes or functions.</p>\n\n<p><strong>+++ EDIT</strong></p>\n\n<pre><code>interface CanBattle {\n public function battle();\n}\n\nabstract class BandBattle {\n public function addParticipant(CanBattle $Participant) {}\n public function battle() {}\n public function getWinner() {}\n}\n\nclass HiphopBattle {\n public function battle() {\n // other logic then rock band battle\n }\n}\n\nclass RockBattle {\n public function battle() {\n // other logi then hiphop battle\n }\n}\n</code></pre>\n\n<p>As you can see you have now the power to implement as many different battles as you please. You do not have even to touch Person or Band to do this (thats the power of seperation)\nThe only thing Band and Person have to do is impelment the interface \"CanBattle\" as the battle does not care if you ar a Band (rock) or a person (hiphop), i hope this examples will help you. </p>\n\n<p><strong>--- EDIT</strong></p>\n\n<p>Same for the output methods. You could use the __toString method and implement it for Band to output all Members but a better idea would be to seperate output into another class or function. So Band would only return the Data and the other one would present it. </p>\n\n<p>Why do you set goodAtInstrument in Person once in the constructor and then again in the audition? </p>\n\n<p>I think there would be more but i have to wait for your answers befor going to far (- :\nHope i could help. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T04:54:35.663", "Id": "19765", "Score": "0", "body": "Hey thanks sorry it took so long to accept and get back to you. Before I never knew anything about the existence of abstract classes and interfaces or toString...why do you say that battle is not a concern of Band or audition the concern of Person? The way I understand it is appropriate methods of classes are things that the object would do, a verb. A person can audition for a band and a band can challenge another band so I don't quite understand... and I'm not sure why I set good in two places....I think I was intending something different at the time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-07T20:31:33.810", "Id": "19856", "Score": "0", "body": "@user1159454 added an example for seperation (see edit), hope that helps to clear things up." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T11:46:57.623", "Id": "12289", "ParentId": "12284", "Score": "5" } }, { "body": "<p>I would accept braunbaer's answer, this is merely an addition.</p>\n\n<p><strong>OOP Review</strong></p>\n\n<p><strong>Inheritance</strong></p>\n\n<p>As braunbaer said, these classes are nothing alike and so they shouldn't be inheriting from the same source. However, you are not using inheritance right anyways. If class \"Start\" has a method that sets the \"name\" property, there is no need to type that again in the overriding child method, you should call <code>parent::__construct();</code> within the child constructor method at the appropriate point instead. But this is a bad example because it only performs one task and that task isn't any shorter than rewriting it. Assume all of your classes set the \"type\" and \"name\" properties and performed a shared method. Of course for this the parent class should also have this shared method as well, but we will assume it does for now. Then you can immediately see the benefit of calling the <code>parent::construct()</code> method instead of retyping all of that for each child method. What you have right now might as well be an interface because you are not reusing any of its code :)</p>\n\n<p><strong>Encapsulation</strong></p>\n\n<p>The true purpose for OOP is not just code reuse, but encapsulation. In other words, hiding information from the users. Your classes don't do this. This isn't really a necessity, but it is one of the key features of OOP and a good one. Right now all of your methods and properties have defaulted to public because none of them are properly defined. PHP 5 still supports declaring class properties with <code>var</code> but it is an old and outdated method that will probably become deprecated at some point. The proper way is to use the property's state (public, private, or protected) to declare them. This also holds true for class methods, though they still require the \"function\" keyword.</p>\n\n<p><strong>General Code Review</strong></p>\n\n<p><strong>Variables</strong></p>\n\n<p>Your variables should be descriptive. For example, <code>$k</code> and <code>$v</code> as defined in your foreach loop in the <code>sorryReject()</code> method could be renamed <code>$instruments</code> and <code>$musicians</code> respectively. This is a form of self documentation that ensures everyone who reads your code understands what those variables indicate.</p>\n\n<p><strong>var_dump()</strong></p>\n\n<p>You shouldn't dump variables into the view like this. It is very messy. <code>var_dump()</code>, <code>exit()</code>, <code>die()</code>, etc... (even <code>echo()</code> in my opinion) are all debugging tools that should not make it into the final release of a program. They are inelegant and counter-intuitive to separation of code, but that is a more advanced venture into OOP (see MVC) so I won't get into it here :)</p>\n\n<p><strong>Ternary Operations</strong></p>\n\n<p>Ternary operations are nice, but should only be used when they benefit your code, not as a short hand. So the following should be expanded.</p>\n\n<pre><code>if( isset($this-&gt;name) ) { echo \"This $type band called {$this-&gt;name} has just been formed!\";\nelse { echo \"This band was formed. Genre: $type\"; }\n</code></pre>\n\n<p>So a better example of a \"good\" ternary operation:</p>\n\n<pre><code>$name = isset($this-&gt;name) ? $this-&gt;name : 'default';\n</code></pre>\n\n<p>Though it is argued that ternary is never good practice. I myself believe it ok if it is implemented similar to the later example.</p>\n\n<p><strong>Strings</strong></p>\n\n<p>You'll also notice I fiddled with your strings in the above code. Double quotes (\" \") tell PHP that it needs to process the incoming string, that there are PHP variables or entities needing to be escaped inside. Single quoted (' ') strings are not processed and will produce the same string that you typed, letter-for-letter, symbol-for-symbol. So your double quoted string was not being used appropriately. You told PHP there were variables or entities to escape and then manually escaped them yourself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T05:10:59.363", "Id": "19766", "Score": "0", "body": "Thanks\nThe only reason that I made the Start class was so even if nothing was set in a new class it would still have or want a name. I'll look into parent::construct. \nNow by calling the $k and $v variables as instrument and musician, I won't be interfering with other variables will I? I usually call foreach vars k and v so that I never interfere with variables outside of the loop…I just had some exceptions this time around." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T05:11:17.443", "Id": "19767", "Score": "0", "body": "I don't intend to have var_dump in final releases, I use it simply to see what's going on in the background, what's wrong with it?\nOn ternary, isn't ternary or not a matter of preference? What is wrong with it? I usually use ternary if the if/else statement is very very short (1 line). I can understand if it gets complicated and nested, but this is one line and one if/else condition. I'd figure it's slightly faster as well, only being on one line. When would it \"benefit code\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T05:11:26.837", "Id": "19768", "Score": "0", "body": "On strings, I know what you mean, I just haven't broken the habit of using double quotes everywhere. I'll have to work on that. Single in static strings and double in strings with escape characters. However I find it easier to read when concatenating variables instead of just putting them in the quotes. Does this interfere with speed?\nThanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T12:21:29.710", "Id": "19779", "Score": "0", "body": "@user1159454: Better code separation by method will help ensure no variable conflicts, but as long as you don't use the same variables in the same scope you should be fine. Variable conflicts are only a major concern in procedural code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T12:28:07.360", "Id": "19780", "Score": "0", "body": "@user1159454: There's nothing wrong with `var_dump()`, just that it is an inelegant way of outputting data to the browser. Ternary is a matter of preference. You say you are doing it only for one line statements, but the ones I see are spread across two.. If they are so large that you are spreading them across multiple lines to improve legibility, you might as well be using those if statement. Its true they also shouldn't be nested. And I actually think ternary is slower... It benefits your code when it can help shorten your code without reducing legibility." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T12:29:11.197", "Id": "19781", "Score": "0", "body": "@user1159454: The speed is negligible and only because of the double quotes, not for manually escaping them." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T21:10:13.447", "Id": "12306", "ParentId": "12284", "Score": "3" } } ]
{ "AcceptedAnswerId": "12289", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T05:54:25.993", "Id": "12284", "Score": "2", "Tags": [ "php", "object-oriented", "classes" ], "Title": "Am I utilizing classes and OOP efficiently?" }
12284
<p>Here's one more controller I'm trying to get reviewed for. Any thoughts?</p> <pre><code>&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Login extends CI_Controller { public function __construct() { parent::__construct(); $this-&gt;load-&gt;model('users/usersmodel'); } public function index() { //Config Defaults Start $msgBoxMsgs = array();//msgType = dl, info, warn, note, msg $cssPageAddons = '';//If you have extra CSS for this view append it here $jsPageAddons = '&lt;script src='.base_url().'assets/'. $this-&gt;config-&gt;item('defaultTemplate') .'/js/validate/login.js&gt;&lt;/script&gt;';//If you have extra JS for this view append it here $metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's $siteTitle = '';//alter only if you need something other than the default for this view. //Config Defaults Start //examples of how to use the message box system (css not included). //$msgBoxMsgs[] = array('msgType' =&gt; 'dl', 'theMsg' =&gt; 'This is a Blank Message Box...'); /**********************************************************Your Coding Logic Here, Start*/ if ($this-&gt;session-&gt;userdata('xtr') == "yes") { redirect('cpanel'); } else { $bodyContent = $this-&gt;config-&gt;item('defaultTemplate') ."/usermanagement/forms/login_form";//which view file $bodyType = "full";//type of template } /***********************************************************Your Coding Logic Here, End*/ //Double checks if any default variables have been changed, Start. //If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing. if(count($msgBoxMsgs) !== 0) { $msgBoxes = $this-&gt;msgboxes-&gt;buildMsgBoxesOutput(array('display' =&gt; 'show', 'msgs' =&gt;$msgBoxMsgs)); } else { $msgBoxes = array('display' =&gt; 'none'); } if($siteTitle == '') { $siteTitle = $this-&gt;metatags-&gt;SiteTitle(); //reads } //Double checks if any default variables have been changed, End. $this-&gt;data['msgBoxes'] = $msgBoxes; $this-&gt;data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view. $this-&gt;data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view. $this-&gt;data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php $this-&gt;data['bodyType'] = $bodyType; $this-&gt;data['bodyContent'] = $bodyContent; $this-&gt;load-&gt;view($this-&gt;config-&gt;item('defaultTemplate') .'/usermanagement/index', $this-&gt;data); } function submit() { // Sets validation rules for the login form $this-&gt;form_validation-&gt;set_rules('username', 'Username', 'trim|required|xss_clean'); $this-&gt;form_validation-&gt;set_rules('password', 'Password', 'trim|required|xss_clean'); $this-&gt;form_validation-&gt;set_rules('remember', 'Remember me', 'integer'); // Checks to see if login form was submitted properly if ($this-&gt;form_validation-&gt;run() === false) { $outputArray = array('error' =&gt; 'yes', 'message' =&gt; 'There was a problem submitting the form! Please refresh the window and try again!'); } else { if (is_null($userData = $this-&gt;usersmodel-&gt;getUserByUsername($this-&gt;input-&gt;post('username')))) { // Username was not found in the database $outputArray = array('error' =&gt; 'yes', 'message' =&gt; 'Incorrect username and password combination!'); } else { // Checks to see if user has exceeded max login attempts if ($this-&gt;auth-&gt;isMaxLoginAttemptsExceeded($userData-&gt;userID)) { // Max was exceeded and sends email to account holder $outputArray = array('error' =&gt; 'yes', 'message' =&gt; 'Your account is currently locked, we appologize for the inconvienence. You must wait 10 minutes before you can login again! An email was sent to the owner of this account!'); $userData = array('userID' =&gt; $userData-&gt;userID, 'firstName' =&gt; $userData-&gt;firstName, 'lastName' =&gt; $userData-&gt;lastName, 'email' =&gt; $userData-&gt;email, 'username' =&gt; $userData-&gt;username); $this-&gt;auth-&gt;sendEmail($this-&gt;config-&gt;item('defaultTemplate'), 'maxlogins', 'KOW Manager Account Locked', $userData); } else { // Matches user's status for validity switch($userData-&gt;usersStatusesID) { // Registered not validated case 1: $outputArray = array('error' =&gt; 'yes', 'message' =&gt; 'Sorry you must verify your account before logging in!'); break; // Account suspended case 3: $outputArray = array('error' =&gt; 'yes', 'message' =&gt; 'Your account has been suspended!'); break; // Account Banned case 4: $outputArray = array('error' =&gt; 'yes', 'message' =&gt; 'Your account is currently banned!'); break; // Account Deleted case 5: $outputArray = array('error' =&gt; 'yes', 'message' =&gt; 'Your account has been deleted!'); break; // Registered and validated default: // Checks to see if login was successful if ($this-&gt;auth-&gt;login($this-&gt;input-&gt;post('username'), $this-&gt;input-&gt;post('password'), $this-&gt;input-&gt;post('remember'))) { // Login was successful $outputArray = array('success' =&gt; 'Yes', 'message' =&gt; 'Sending to control panel!'); } else { // Login failed $outputArray = array('error' =&gt; 'yes', 'message' =&gt; 'Incorrect username and password combination!'); } } } } } echo json_encode($outputArray); } } /* End of file login.php */ /* Location: ./application/controllers/login.php */ </code></pre> <p>KOW Auth:</p> <pre><code>/** * Login user on the site. Return TRUE if login is successful * (user exists and activated, password is correct), otherwise FALSE. * * @param string * @param string * @param integer * @return array */ function login($username, $password, $remember) { $this-&gt;ci-&gt;load-&gt;model('users/usersmodel'); if ($userData = $this-&gt;ci-&gt;usersmodel-&gt;getUserByUsername($username)) { $regenFromPostPW = $this-&gt;ci-&gt;genfunc-&gt;reGenPassHash($password, $userData-&gt;passwordHash); if ($regenFromPostPW == $userData-&gt;password) { $this-&gt;ci-&gt;session-&gt;set_userdata(array( 'xtr' =&gt; 'yes', 'userID' =&gt; $userData-&gt;userID, 'username' =&gt; $userData-&gt;username, 'role' =&gt; $userData-&gt;usersRolesID )); if ($remember == 1) { //$this-&gt;create_autologin($user_data-&gt;user_id); } $this-&gt;clearLoginUserAttempts($userData-&gt;userID); $this-&gt;session-&gt;all_userdata(); //$this-&gt;ci-&gt;users-&gt;insert_session($this-&gt;session-&gt;userdata('session_id'), $this-&gt;session-&gt;userdata('user_id'), $this-&gt;genfunc-&gt;getRealIpAddr(), $this-&gt;session-&gt;userdata('user_agent')); return $userData; } else { $this-&gt;increaseLoginUserAttempt($userData-&gt;userID); } } else { return null; } } </code></pre>
[]
[ { "body": "<p>I've already reviewed some of your other code, so I will only add new items in an attempt not to repeat posts</p>\n\n<p><strong>Booleans</strong></p>\n\n<p>There is no reason to recreate a feature that already exists. By checking for a <code>\"yes\"</code> or <code>\"no\"</code> or a <code>1</code> or <code>0</code> value you are recreating a boolean. Simpler to just use TRUE/FALSE this way you can check your variables like so.</p>\n\n<pre><code>if ($this-&gt;session-&gt;userdata('xtr'))\n//instead of\nif ($this-&gt;session-&gt;userdata('xtr') == \"yes\")\n\n//OR\nif ($remember)\n//instead of\nif ($remember == 1)\n</code></pre>\n\n<p><strong>Redirects</strong></p>\n\n<p>I'm not familiar with CodeIgniter, but if <code>redirect()</code> interrupts the current code flow and physically redirects to a new page, then there is no reason to use an else statement. As it will never be processed. Save yourself from those indents.</p>\n\n<p><strong>Variables in Statements</strong></p>\n\n<p>Defining a variable in a statement is bad! There are few exceptions to this rule, and even those exceptions can be avoided. Declaring a variable in any kind of statement is wrong. A couple of reasons for this. First, it could be accidental and your IDE and PHP will have no way of telling you because it is valid code. Second, it adds unnecessary complexity to the statement that hinders legibility.</p>\n\n<pre><code>$postUser = $this-&gt;input-&gt;post('username');\n$userData = $this-&gt;usermodel-&gt;getUserByUsername($postUser);\nif (is_null($userData ))\n</code></pre>\n\n<p>And I already mentioned <code>is_null()</code> in my last review :)</p>\n\n<p><strong>outputArray</strong></p>\n\n<p>I've already mentioned how I think the \"error\" element should be a boolean. This is to serve two purposes. First, was the one I already mentioned, about not recreating a feature. The second was to do away with the \"success\" element. No reason to have two separate elements that accomplish more or less the same thing. If there is an error, then success is obviously false. If there is no error, then success is obviously true. So you see, you can just use the \"error\" element for both.</p>\n\n<p>There is also unnecessary duplication here. I would create a default <code>$outputArray</code> at the beginning of my <code>submit()</code> method that contains default values. Then, instead of recreating the array every time I wanted to set the message, I would just set the \"message\" directly. The only time you need to do anything extra is when you have \"success\" in which case you need to change the value of \"error\" to false.</p>\n\n<pre><code>$outputArray = array(\n 'error' =&gt; TRUE,\n 'message' =&gt; 'There was a problem submitting the form! Please refresh the window and try again!'\n);\n\nif ($this-&gt;form_validation-&gt;run() !== FALSE) {\n //etc...\n\n if ($this-&gt;auth-&gt;login($this-&gt;input-&gt;post('username'), $this-&gt;input-&gt;post('password'), $this-&gt;input-&gt;post('remember')))\n {\n // Login was successful\n $outputArray['error'] = FALSE;\n $outputArray['message'] = 'Sending to control panel!';\n }\n else\n {\n // Login failed\n $outputArray['message'] = 'Incorrect username and password combination!';\n } \n}\n</code></pre>\n\n<p><strong>Default Values</strong></p>\n\n<p>The cool thing about if/else statements is that the else is usually unnecessary. When coding, be a pessimist. Assume the worst will happen and perform that action by default. Then you only have to plan for success. You could technically do it the other way around, but better this way in case you miss something. That way the script is already prepared to handle an error.</p>\n\n<p>So here's an example using the code from above...</p>\n\n<pre><code>$outputArray['message'] = 'Incorrect username and password combination!';\n\nif ($this-&gt;auth-&gt;login($this-&gt;input-&gt;post('username'), $this-&gt;input-&gt;post('password'), $this-&gt;input-&gt;post('remember')))\n{\n // Login was successful\n $outputArray['error'] = FALSE;\n $outputArray['message'] = 'Sending to control panel!';\n}\n</code></pre>\n\n<p><strong>Shortening Your Code</strong></p>\n\n<p>This line is rather bulky...</p>\n\n<pre><code>if ($this-&gt;auth-&gt;login($this-&gt;input-&gt;post('username'), $this-&gt;input-&gt;post('password'), $this-&gt;input-&gt;post('remember')))\n</code></pre>\n\n<p>You don't really use these anywhere else, but I still think it would be worth it to set these up as variables to improve legibility. Since you do, use the \"username\" only once more, I would set them towards the top of the method so that they can be used in both places. So...</p>\n\n<pre><code>$username = $this-&gt;input-&gt;post('username');\n$password = $this-&gt;input-&gt;post('password');\n$remember = $this-&gt;input-&gt;post('remember');\n//usage\nif ($this-&gt;auth-&gt;login($username, $password, $remember))\n</code></pre>\n\n<p><strong>Methods</strong></p>\n\n<p>Your <code>submit()</code> and <code>login()</code> methods have not been defined as public/private/protected. By default it is set to public, but you should not depend upon PHP always providing a default, or the same default.</p>\n\n<p><strong>Magical toarray Method</strong></p>\n\n<p>Well, not so magical, because it doesn't exist, but you can get the same functionality out of PHP's <code>get_object_vars()</code> function. So, assuming that the only public properties you have in the <code>$userData</code> class are the ones you are seeking, or at the very least you do not mind having extra unused properties in your <code>$userData</code> array, you can get the same results for your <code>$userData</code> array like so:</p>\n\n<pre><code>$userData = get_object_vars($userData);\n//instead of...\n$userData = array('userID' =&gt; $userData-&gt;userID, 'firstName' =&gt; $userData-&gt;firstName, 'lastName' =&gt; $userData-&gt;lastName, 'email' =&gt; $userData-&gt;email, 'username' =&gt; $userData-&gt;username);\n</code></pre>\n\n<p><strong>Final Thoughts</strong></p>\n\n<p>What is \"xtr\"? Your variables should be a bit more descriptive than that.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p><strong>Methods</strong></p>\n\n<p>A public method or property is one you can access from outside the current scope of a class. Whether in the traditional <code>$class-&gt;</code> method or the static <code>class::</code> method. In other words, if you were to load this class into another file and create a new instance of it, that file will be able to use any public methods or properties simply by calling the class.</p>\n\n<p>Private and protected methods and properties are just the opposite. Both are only accessible from within the class themselves. You can only call them within the class via <code>$this-&gt;</code> or statically via <code>class::</code>. If you were to load this class into another file and create a new instance of it, all private and protected methods and properties would be invisible to it and inaccessible. They are only available within the class' scope. So if the file used the public method <code>getPrivateData</code> to retrieve the private property <code>$privateData</code> it would not know where that information came from and would not be able to specifically ask for the <code>$privateData</code> property. This is ideal for information you do not wish someone to have access to, such as a password or something else critical in nature. The difference between private and protected is that a protected method or property is used for class inheritance and only a child class and the parent class can access them whereas private methods and properties are only accessible by the parent and invisible to the child.</p>\n\n<p>If this is not clear enough you'll have to look at the PHP documentation.</p>\n\n<p><strong>NULL</strong></p>\n\n<p>If you are specifically looking for NULL you should use the <code>is_null()</code> function or the absolute equality <code>===</code> operator instead of loose equality <code>==</code> operator. Doing a loose comparison of NULL will return TRUE for empty strings, \"null\", \"NULL\", null, NULL, and 0, not sure about FALSE... So you might as well use a boolean comparison (<code>! $userData</code>) as to use the loose comparison. They will both return more or less the same thing and the later is cleaner.</p>\n\n<pre><code>if ($userData === null)\n//OR\nif (is_null($userData))\n</code></pre>\n\n<p><strong>One Last Thing</strong></p>\n\n<p>As I mentioned earlier, if you are a \"coding pessimist\", there is no need for all these else statements. We set the <code>$outputArray['message']</code> with a default value that handled the first error should it occur. This is being pessimistic. We are assuming the code will fail and have already set up our code to handle it should it do so. We laugh at the optimists for they assume their code will work and will eventually be proven wrong when they meet an error they never expected. We do not want to be optimistic. We pity the hesitant coder for their many if/else statements are hard to read and their code heavily indented. We do not want to be hesitant. We are pessimists and we have handled all eventualities before they occur. We tell our code it is wrong and challenge it to \"Trial by If Statements\". And we do it again and again until we are satisfied. Each time telling it how it is wrong and what it can do to get better. We are emotionally abusive to our code, but it will grow the stronger for it. Only once our code has proven itself and passed all of our tests will we declare it fit and can be proud of it.</p>\n\n<p>Excuse my fun little rant, but if you read it and take it to heart you'll have the right mindset. To clarify, once inside each if statement our code has literally told us it is not wrong and the previous statement about it (error) is no longer valid. So we do it again and again until there are no more if statements. Because we assume our code is wrong there is no need for else statements, and should some unforseen error occur we don't have to do anything extra to it because we have already assumed it is wrong. This can be done with any if/else block.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T17:37:52.600", "Id": "19743", "Score": "0", "body": "Looks amazing. I updated my post and tell me if I missed anything. I'm still confused over the methods part. How do I know which to make them. As far as the xtr its just my little string for settings up a cookie that only I will know the value of that way a hacker/user can't know what it means to try and manipulate the data." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T15:24:26.087", "Id": "12298", "ParentId": "12287", "Score": "4" } } ]
{ "AcceptedAnswerId": "12298", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T09:08:37.843", "Id": "12287", "Score": "2", "Tags": [ "php", "codeigniter" ], "Title": "Login Controller" }
12287
<p>Assume the following situation: you have an object that can store any object based on a key (basically, <code>IDictionary&lt;string, object&gt;</code>). You want to store objects of various types into it that are not directly related. (For example, the dictionary can be an ASP.NET <code>Session</code>, or it can represent a dictionary that will be serialized to disk for persistent storage.)</p> <p>I don't want to create a single class that will contain all those objects, because they are not directly related, they come from different places. But if you store each object separately, it means you have to use casts when getting some value and there is no type-check when you're setting it.</p> <p>To solve this, I created a generic type that encapsulates the key along with the associated type and a couple of extension methods that use it:</p> <pre><code>class TypedKey&lt;T&gt; { public string Name { get; private set; } public TypedKey(string name) { Name = name; } } static class DictionaryExtensions { public static T Get&lt;T&gt;(this IDictionary&lt;string, object&gt; dictionary, TypedKey&lt;T&gt; key) { return (T)dictionary[key.Name]; } public static void Set&lt;T&gt;(this IDictionary&lt;string, object&gt; dictionary, TypedKey&lt;T&gt; key, T value) { dictionary[key.Name] = value; } } </code></pre> <p>Usage:</p> <pre><code>private static readonly TypedKey&lt;int&gt; AgeKey = new TypedKey&lt;int&gt;("age"); … dictionary.Get(AgeKey) &gt; 18 dictionary.Set(AgeKey, age) </code></pre> <p>This has the type-safety (both on get and set) of using a property, while being backed by a dictionary that can store anything.</p> <p>What do you think about this pattern?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T16:20:02.997", "Id": "394964", "Score": "1", "body": "Beautiful solution!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T19:35:24.933", "Id": "426553", "Score": "0", "body": "I would use Convert.ChangeType rather than naively casting to T. Let the TypeDescriptor framework handle object conversions for you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-08T11:29:10.443", "Id": "507228", "Score": "0", "body": "See https://stackoverflow.com/questions/323613/heterogeneous-dictionary-but-typed/323714#323714 and https://stackoverflow.com/a/32561156/361177" } ]
[ { "body": "<p>Your suggestion is not really type-safe as you can still pass a key of the wrong type. Therefore I would just use a normal (string) key. But I would add a generic <code>TryGet</code> method which takes account of the type. The setter needs not to be generic. </p>\n\n<pre><code>static class DictionaryExtensions\n{\n public static T Get&lt;T&gt;(this IDictionary&lt;string, object&gt; dictionary, string key)\n {\n return (T)dictionary[key];\n }\n\n public static bool TryGet&lt;T&gt;(this IDictionary&lt;string, object&gt; dictionary,\n string key, out T value)\n {\n object result;\n if (dictionary.TryGetValue(key, out result) &amp;&amp; result is T) {\n value = (T)result;\n return true;\n }\n value = default(T);\n return false;\n }\n\n public static void Set(this IDictionary&lt;string, object&gt; dictionary,\n string key, object value)\n {\n dictionary[key] = value;\n }\n}\n</code></pre>\n\n<p>You can then use the dictionary like this.</p>\n\n<pre><code>int age = 20;\ndictionary.Set(\"age\", age);\n\n// ...\n\nage = dictionary.Get&lt;int&gt;(\"age\");\n\n// or the safe way\nif (dictionary.TryGet(\"age\", out age)) {\n Console.WriteLine(\"The age is {0}\", age);\n} else {\n Console.WriteLine(\"Age not found or of wrong type\");\n}\n</code></pre>\n\n<p>Note that the compiler can infer the generic type when using <code>TryGet</code>.</p>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p>In despite of my suggestion above, I must agree that your solution is elegant. Here is another suggestion which is based on your solution but which encapsulates the dictionary instead of providing a key. Well, it acts as wrapper and as key at the same time</p>\n\n<pre><code>public class Property&lt;T&gt;\n{\n Dictionary&lt;object, object&gt; _dict;\n\n public Property (Dictionary&lt;object, object&gt; dict)\n {\n _dict = dict;\n }\n\n public T Value {\n get { return (T)_dict[this]; }\n set { _dict[this] = value; }\n }\n}\n</code></pre>\n\n<p>Alternatively, a string key could be provided in the Property's constructor.</p>\n\n<p>You can use it like this</p>\n\n<pre><code>private static readonly Dictionary&lt;object, object&gt; _properties = \n new Dictionary&lt;object, object&gt;();\nprivate static readonly Property&lt;int&gt; _age = new Property&lt;int&gt;(_properties);\n\n...\n\n_age.Value &gt; 18\n_age.Value = age\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T14:36:02.233", "Id": "19732", "Score": "0", "body": "The problem with this is that you have to specify the type every time you use `Get()` and that it's possible to use the wrong type with `Set()`, which will cause a runtime exception on a later `Get()`. But you're right that my solution is not completely type-safe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T18:57:19.957", "Id": "20793", "Score": "0", "body": "I have picked up your original idea again and developed it a little bit further. Please see my update." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T19:12:02.120", "Id": "20795", "Score": "1", "body": "That's certainly an interesting idea. Yeah, I think it's better than what I originally proposed. Although using the object itself as a key (with reference equality) wouldn't work in my cases, because the `Dictionary` is persisted. But as you mentioned, that can be easily modified." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T12:59:51.353", "Id": "12292", "ParentId": "12291", "Score": "16" } }, { "body": "<p>I know you don't want to create a single class, but this seems exactly what is needed. I would create a new class and favor composition. Call the whole ball of wax a <code>PropertyBag</code> since that declares its intent a bit clearer. I also am a fan of interfaced-based development, so I extracted a couple of them. Note one constructor overload takes a non-generic <code>IDictionary</code> so you can create one of these from any existing dictionary (generic or not). Commentary welcome.</p>\n\n<pre><code>public interface ITypedKey&lt;T&gt;\n{\n string Name { get; }\n}\n\npublic class TypedKey&lt;T&gt; : ITypedKey&lt;T&gt;\n{\n public TypedKey(string name) =&gt; this.Name = name ?? throw new ArgumentNullException(nameof(name));\n\n public string Name { get; }\n}\n\npublic interface IPropertyBag\n{\n T Get&lt;T&gt;(ITypedKey&lt;T&gt; key);\n\n bool TryGet&lt;T&gt;(ITypedKey&lt;T&gt; key, out T value);\n\n void Set&lt;T&gt;(ITypedKey&lt;T&gt; key, T value);\n\n void Remove&lt;T&gt;(ITypedKey&lt;T&gt; key);\n}\n\npublic class PropertyBag : IPropertyBag\n{\n private readonly IDictionary&lt;string, object&gt; _bag;\n\n public PropertyBag() =&gt; this._bag = new Dictionary&lt;string, object&gt;();\n\n public PropertyBag(IDictionary dict)\n {\n if (dict == null)\n {\n throw new ArgumentNullException(nameof(dict));\n }\n\n this._bag = new Dictionary&lt;string, object&gt;(dict.Count);\n foreach (DictionaryEntry kvp in dict)\n {\n this._bag.Add(new KeyValuePair&lt;string, object&gt;(kvp.Key.ToString(), kvp.Value));\n }\n }\n\n public T Get&lt;T&gt;(ITypedKey&lt;T&gt; key)\n {\n if (key == null)\n {\n throw new ArgumentNullException(nameof(key));\n }\n\n return (T)this._bag[key.Name];\n }\n\n public bool TryGet&lt;T&gt;(ITypedKey&lt;T&gt; key, out T value)\n {\n if (this._bag.TryGetValue(key.Name, out object result) &amp;&amp; result is T typedValue)\n {\n value = typedValue;\n return true;\n }\n\n value = default(T);\n return false;\n }\n\n public void Set&lt;T&gt;(ITypedKey&lt;T&gt; key, T value)\n {\n if (key == null)\n {\n throw new ArgumentNullException(nameof(key));\n }\n\n this._bag[key.Name] = value;\n }\n\n public void Remove&lt;T&gt;(ITypedKey&lt;T&gt; key)\n {\n if (key == null)\n {\n throw new ArgumentNullException(nameof(key));\n }\n\n this._bag.Remove(key.Name);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T14:38:09.000", "Id": "19733", "Score": "0", "body": "I meant I didn't want to create a single class with lots of properties. Your way does make sense." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T13:48:54.513", "Id": "12295", "ParentId": "12291", "Score": "6" } }, { "body": "<p>I know that this solution has some really bumpy corners and using it at scale would have some really interesting implications, but please consider it as a thought experiment.</p>\n\n<p>In all of the previously posted examples you still have the potential for a mistake - i.e., someone might intentionally or unintentionally do something along the lines of this:</p>\n\n<pre><code>private static readonly TypedKey&lt;int&gt; AgeKey = new TypedKey&lt;int&gt;(\"age\");\nprivate static readonly TypedKey&lt;string&gt; BadAgeKey = new TypedKey&lt;string&gt;(\"age\");\ndictionary.Set(BadAgeKey, “foo”);\n...\n// this would throw\ndictionary.Get(AgeKey);\n</code></pre>\n\n<p>And there is really nothing that you can do at compile time to validate that. You could implement some kind of code analyzer to look for examples of <code>AgeKey</code> and <code>BadAgeKey</code>. Normally this is addressed by name spacing keys so that they don’t overlap.</p>\n\n<p>In this solution, I attempted to solve that problem… To do that I dropped the string key, and instead indexed the dictionary by Type, especially the Type of what the consumer is using as a key, and not the Type of data being stored. Doing that means that each key has to be a predefined Type. It does give you options for accessing the data. </p>\n\n<p>You could select which key to read/write at compile time using a Generic Type parameter or you could defer that to run time by passing the key as a normal parameter.</p>\n\n<p>And I came up with this:</p>\n\n<pre><code>public class TypeSafeKey&lt;T&gt; { }\n\npublic class TypeSafeKeyValuePairBag\n{\n public T GetItemOrDefault&lt;TKey, T&gt;(T defaultValue = default(T)) where TKey : TypeSafeKey&lt;T&gt;\n =&gt; TryGet(typeof(TKey), out T result) ? result : defaultValue;\n\n public T GetItemOrDefault&lt;T&gt;(TypeSafeKey&lt;T&gt; key, T defaultValue = default(T))\n =&gt; TryGet(key?.GetType() ?? throw new ArgumentNullException(nameof(key)), out T result) ? result : defaultValue;\n\n public void SetItem&lt;TKey, T&gt;(T value) where TKey : TypeSafeKey&lt;T&gt;\n =&gt; m_values[typeof(TKey)] = value;\n\n public void SetItem&lt;T&gt;(TypeSafeKey&lt;T&gt; key, T value)\n =&gt; m_values[key?.GetType() ?? throw new ArgumentNullException(nameof(key))] = value;\n\n public T GetItem&lt;TKey, T&gt;() where TKey : TypeSafeKey&lt;T&gt;\n =&gt; Get&lt;T&gt;(typeof(TKey));\n\n public T GetItem&lt;T&gt;(TypeSafeKey&lt;T&gt; key)\n =&gt; Get&lt;T&gt;(key?.GetType() ?? throw new ArgumentNullException(nameof(key)));\n\n private bool TryGet&lt;T&gt;(Type type, out T value)\n {\n if (m_values.TryGetValue(type, out object obj))\n {\n value = (T)obj;\n return true;\n }\n\n value = default(T);\n return false;\n }\n\n private T Get&lt;T&gt;(Type type)\n =&gt; TryGet(type, out T result) ? result : throw new KeyNotFoundException($\"Key {type.FullName} not found\");\n\n private Dictionary&lt;Type, object&gt; m_values = new Dictionary&lt;Type, object&gt;();\n}\n</code></pre>\n\n<p>Then using it would look something like this:</p>\n\n<pre><code>// You need to declare a Type for each key that you want to use, all though the types can defined anywhere\n// They don't need to be known to the assembly where TypeSafeKeyValuePairBag is defined, but they do need to\n// be known to the any code that is setting or getting any given key. So even though the declaration of\n// these class could be spread throughout the source tree, since each is a type they are forced to be unique\npublic class KeyHight : TypeSafeKey&lt;int&gt; { }\npublic class KeyWidth : TypeSafeKey&lt;int&gt; { }\npublic class KeyName : TypeSafeKey&lt;string&gt; { }\n\n// A static class, with static public members would reduce the number of instances of objects that needed to be created for repeated reads/writes. \n// You would need to create these in a lazy fashion if you had many of them. And since only their type matters, you don’t need to worry about locking, since two different instances of the same Type would function as the same key. \npublic static class Keys\n{\n public static KeyHight KeyHight { get; } = new KeyHight();\n public static KeyWidth KeyWidth { get; } = new KeyWidth();\n public static KeyName KeyName { get; } = new KeyName();\n}\n\n...\n\nTypeSafeKeyValuePairBag bag = new TypeSafeKeyValuePairBag();\n\n// Accessing hard coded keys\n//Using Generic Type Parameters: The compiler can't infer the value Type from the Key Type, which means listing them both\nbag.SetItem&lt;KeyHight, int&gt;(5);\n//Passing the key as a parameter\nbag.SetItem(Keys.KeyWidth, 10);\nbag.SetItem(Keys.KeyName, \"foo\");\n\n// Selecting which keys to access at run time\nint value = 1;\nforeach(var key in new TypeSafeKey&lt;int&gt;[] { Keys.KeyHight, Keys.KeyWidth })\n{\n value *= bag.GetItem(key);\n}\n\nConsole.WriteLine($\"{bag.GetItem&lt;KeyName, string&gt;()}'s area is {value}\");\n</code></pre>\n\n<p>This does have some large drawbacks. Specifically you need to create a lot of types which will add bloat. And serializing it would be rather verbose. It would also still be easy to use the wrong key, and before where that may have resulted in a runtime error, the wrong key could easily lead to corruption.</p>\n\n<p>Using Types has another really large complication if you are using versioned software. Many of the previous examples could easily be shared in a process that has a mixture of different assembly versions loaded. This is definitely true if all the items in the property bag were primitive types. The string constant “foo” defined in version 1.0 is going to the same in version 2.0 (assuming no one change the value). When you start using types as keys you will get unexpected results if someone sets a value with one version of the key, but attempts to read it with another, specifically KeyHight defined in version 1.0 is not the same type as KeyHeight defined in version 2.0</p>\n\n<p>The multiple ways of getting to the setters and getters could also make it difficult to locate all the uses of a specific key, but since they are bound to type, most IDEs can easily get you a comprehensive list of accesses.</p>\n\n<p>I spent some time exploring what else you could do if you had a structure like this. You could utilize the inheritance to build a hierarchy. There are likely simpler and more efficient way to do this, but consider if we change the TryGet method like this:</p>\n\n<pre><code>private bool TryGet&lt;T&gt;(Type type, out T value)\n{\n if (m_values.TryGetValue(type, out object obj))\n {\n value = (T)obj;\n return true;\n }\n\n Type baseType = type.BaseType;\n if (baseType != typeof(TypeSafeKey&lt;T&gt;))\n {\n return TryGet(baseType, out value);\n }\n\n value = default(T);\n return false;\n}\n</code></pre>\n\n<p>And you consumed it like this:</p>\n\n<pre><code>public class KeyLevel0Value : TypeSafeKey&lt;int&gt; { }\npublic class KeyLevelA1Value : KeyLevel0Value { }\npublic class KeyLevelA2Value : KeyLevelA1Value { }\npublic class KeyLevelB1Value : KeyLevel0Value { }\npublic class KeyLevelB2Value : KeyLevelB1Value { }\n\n...\n\nbag.SetItem&lt;KeyLevelA1Value, int&gt;(5);\n// This will first check the value for LevelA2. After not finding it, it will check LevelA2, and that value will be returned\nConsole.WriteLine(bag.GetItem&lt;KeyLevelA2Value, int&gt;());\n// This will first check the value for LevelB2, LevelB1, and finally Level0, and since none are set it will return default\nConsole.WriteLine(bag.GetItemOrDefault&lt;KeyLevelB2Value, int&gt;());\n</code></pre>\n\n<p>So with all that being said, this does create a Property bag that can hold arbitrary types, and access to the data is done in a type safe way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-26T08:31:58.727", "Id": "370762", "Score": "0", "body": "This reminds me of WPF's dependency property system, except that it uses (static readonly) `DependencyProperty` *instances* as keys. Using `TypeSafeKey<>` instances instead of (derived) types as keys would provide the same level of type-safety, without the need for all those classes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-25T23:48:56.253", "Id": "192959", "ParentId": "12291", "Score": "2" } }, { "body": "<p>You could allow for some more flexibility in type conversions by using type converters.</p>\n\n<pre><code> public static T Get&lt;T&gt;(this IDictionary&lt;string, object&gt; dictionary, TypedKey&lt;T&gt; key)\n {\n return (T)Convert.ChangeType(dictionary[key.Name], typeof(T));\n }\n</code></pre>\n\n<blockquote>\n<pre><code>static class DictionaryExtensions\n{\n public static T Get&lt;T&gt;(this IDictionary&lt;string, object&gt; dictionary, TypedKey&lt;T&gt; key)\n {\n return (T)dictionary[key.Name];\n }\n\n public static void Set&lt;T&gt;(this IDictionary&lt;string, object&gt; dictionary, TypedKey&lt;T&gt; key, T value)\n {\n dictionary[key.Name] = value;\n }\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Edit (after remark OP)</p>\n\n<p>The following operations make more sense. They can be overloads next to the existing original <code>Get</code>.</p>\n\n<pre><code>public static V Get&lt;T, V&gt;(this IDictionary&lt;string, object&gt; dictionary, TypedKey&lt;T&gt; key)\n{\n return (V)Convert.ChangeType(dictionary[key.Name], typeof(T));\n}\n\npublic static T Get&lt;T&gt;(this IDictionary&lt;string, object&gt; dictionary, string key)\n{\n return (T)Convert.ChangeType(dictionary[key], typeof(T));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T18:22:18.853", "Id": "426766", "Score": "0", "body": "I don't understand, how does that help? If I have e.g. `TypedKey<int>`, I know the value will always be an `int`, so `Convert.ChangeType` does not help at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T18:26:39.360", "Id": "426768", "Score": "0", "body": "@svick you are right, I meant to implement this with the overload where key is of type string. Not sure whether I am still allowed to update my post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T18:33:08.763", "Id": "426769", "Score": "0", "body": "Feel free to update your answer. [Editing a *question* after you received answers is frowned upon here](https://codereview.stackexchange.com/help/someone-answers), but that's not the case here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-23T18:34:31.757", "Id": "426770", "Score": "0", "body": "@svick I will leave my initial post, but add your remarks in. This way we don't loose any history on the subject ;-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T19:39:05.883", "Id": "220757", "ParentId": "12291", "Score": "1" } }, { "body": "<p>I have spent a long time grappling with this problem. I have finally come to the conclusion that it actually is a non-problem!</p>\n<p>The thing is that once you have pushed the object into a collection you have lost the compile time binding. Type safety is really a compile time issue rather than a runtime issue.</p>\n<p>My understanding is that when you create a generic the compiler creates new methods to call depending on the generic type passed. So if you have a method</p>\n<pre><code>public void Foo&lt;T&gt;(){}\n</code></pre>\n<p>and call it using</p>\n<pre><code>Foo&lt;int&gt;();\n</code></pre>\n<p>then</p>\n<pre><code>Foo&lt;string&gt;();\n</code></pre>\n<p>the compiler creates 2 methods (I have used pseudo code signatures for the sake of accessibility.)</p>\n<pre><code>public Foo&lt;int&gt;(){}\npublic Foo&lt;string&gt;(){}\n</code></pre>\n<p>If you assign methods to aggregate these to a collection for retrieval you the compiler cannot know what the type of the object that is retrieved from the collection is. So you can no longer have type safety.</p>\n<p>The upshot of this is no matter how many hoops you try to jump through to make the generic store undefined types, it cannot be done. I have come to the conclusion it is better to store the type that was saved explicitly, rather than creating an overload that is actually being used as a type member and explicitly store the types separately in a collection for validation at runtime. The resulting code is leaner and can be understood without knowledge of any 'patterns'.</p>\n<p>I do not think it is impossible to do, but it would require a significant language change to c# and one or more new object types to facilitate it. I am more than open to correction on any of this.</p>\n<h3>In Summary:</h3>\n<p>Preferable to use Dictionary&lt;T,object&gt; then cast the returned object.\nso you would have</p>\n<p>example 1</p>\n<pre><code>var dic = new Dictionary &lt;string, object&gt;();\nstring item1=&quot;item1&quot;;\nint item2=2;\ndic.Add(&quot;item1&quot;,item1);\ndic.Add(&quot;item2&quot;,item2);\nvar retrievedItem1=(string)dic[&quot;item1&quot;];\nvar retrievedItem2=(int)dic[&quot;item2&quot;];\n</code></pre>\n<p>compared to example 2</p>\n<pre><code>var dic = new DictionaryWithLotsOfExtraFunkyCode &lt;string&gt;();\nstring item1=&quot;item1&quot;;\nint item2=2;\ndic.Add(&quot;item1&quot;,item1);\ndic.Add(&quot;item2&quot;,item2);\nvar retrievedItem1=dic.Get&lt;string&gt;(&quot;item1&quot;);\nvar retrievedItem2=dic.Get&lt;int&gt;(&quot;item2&quot;);\n</code></pre>\n<p>There is no extra type safety (both will compile and both will throw runtime errors if attempting to access the wrong type). In example 2 there is just extra code to maintain.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T13:06:30.563", "Id": "245919", "ParentId": "12291", "Score": "2" } } ]
{ "AcceptedAnswerId": "12292", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T12:29:50.800", "Id": "12291", "Score": "28", "Tags": [ "c#", ".net", "hash-map", "type-safety" ], "Title": "Type-safe Dictionary for various types" }
12291
<p>I have tried to incorporate comments from my <a href="https://codereview.stackexchange.com/q/12155/13768">previous code review</a> into this. So, I am hoping for less mistakes. If you spot any, please let me know mercilessly!</p> <pre><code>#include &lt;iostream&gt; #include &lt;queue&gt; void printsub(int* p, int len, std::queue&lt;int&gt; q) { if (!len) { while(!q.empty()) { std::cout &lt;&lt; q.front() &lt;&lt; " "; q.pop(); } std::cout &lt;&lt; "\n"; return; } std::queue&lt;int&gt; t1(q); t1.push(p[0]); printsub(&amp;(p[1]), len - 1, t1); std::queue&lt;int&gt; t2(q); printsub(&amp;(p[1]), len - 1, t2); } int main() { int arr[] = {1, 2, 3, 4, 5, 6}; std::queue&lt;int&gt; q; printsub(arr, ((sizeof(arr))/(sizeof(arr[0]))), q); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-12T10:29:36.057", "Id": "20109", "Score": "0", "body": "Not enough for an answer but consider whether `if(!len)` makes sense. You are treating a number as a boolean value and while C++ allows this due to weak typing, it’s not a meaningful operation. Change it to an explicit check, `if (len != 0)`." } ]
[ { "body": "<p>You could translate <a href=\"https://code.activestate.com/recipes/190465/\" rel=\"nofollow\">this recursive Python code</a>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def xcombinations(items, n):\n if n==0: yield []\n else:\n for i in xrange(len(items)):\n for cc in xcombinations(items[:i]+items[i+1:],n-1):\n yield [items[i]]+cc\n</code></pre>\n\n<p>in C++ roughly (untested, but you get the idea):</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>using std::set;\n\nset&lt;set&lt;int&gt;&gt; xcombinations(const set&lt;int&gt; &amp;items, size_t n) {\n set&lt;set&lt;int&gt;&gt; result; // collect for 'return' instead of pythons 'yield'\n if(n==0) return result;\n for(int elem : items) { // ranged-for from C++11\n // 'items' without 'elem', python 'items[:i]+items[i+1:]'\n set&lt;int&gt; temp(items); // copy\n temp.erase(elem); // ...or use 'std::remove_copy_if'\n for(auto cc : xcombinations(temp, n-1)) { // ranged-for from C++11\n cc.insert(elem);\n result.insert(cc); // python yield;\n }\n }\n return result;\n}\n</code></pre>\n\n<p>Note that <code>auto cc</code> creates a copy in the inner loop, where one can add <code>elem</code> before adding it to <code>result</code>.</p>\n\n<p>Instead if the new C++11 <em>ranged-<code>for</code></em> and <code>auto</code> one can of course just use lengthy iterator-based <code>for</code>-loops.</p>\n\n<p>Using <code>vector</code> instead of <code>set</code> would also work, I guess. There are no set-operations involved here. Actually, now that I think of it, <strong><code>vector</code> would be much better</strong>... hmm... </p>\n\n<p>One could save some copying by pulling <code>temp</code> out of the loop, initialize it with a a size of <code>n-1</code> and use <code>std::remove_copy_if</code> to put the values into it. And if one does that, one can even save the copy of <em>all</em> values by just replacing <em>one</em> in the inner loop, but I can not see how right away.</p>\n\n<p>Ah, well and you need a printing routine, of course.</p>\n\n<pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream &amp;os, const set&lt;int&gt;&amp; items) {\n for(int elem: items)\n os &lt;&lt; elem &lt;&lt; \" \";\n return os;\n}\nstd::ostream operator&lt;&lt;(std::ostream &amp;os, const set&lt;set&lt;int&gt;&gt;&amp; itemss) {\n for(const auto &amp;cc: itemss)\n os &lt;&lt; \" {\" &lt;&lt; cc &lt;&lt; \"}\\n\"; // or use 'ostream_iterator' on 'cc'\n return os;\n}\n\nint main(/*...*/) {\n set&lt;int&gt; data = {1, 2, 3, 4, 5, 6}; // C++11 init-list\n std::cout &lt;&lt; xcombinations(data, data.size()) &lt;&lt; std::endl;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-12T09:31:17.270", "Id": "12482", "ParentId": "12293", "Score": "3" } } ]
{ "AcceptedAnswerId": "12482", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T13:07:07.220", "Id": "12293", "Score": "3", "Tags": [ "c++", "algorithm" ], "Title": "Printing all subsets" }
12293
<p>I'm attempting to write a bit of code that allows for easy and safe access to objects in a file. It seems to work great but I was curious if there was an easier way to do this or if Java already has something like this. If there isn't anything like this any critiques of my code would be appreciated as I'm trying to learn to be a better Java programmer.</p> <p>The main objectives I have are...</p> <ul> <li>Modularity (I want to be able to load any object type)</li> <li>Type-safety (I want all the object returned to be of the correct type give no warnings)</li> <li>Thread-safety (I want to be able to read and write multiple files, multiple times, concurrently)</li> </ul> <p>loadFile is just a basic implementation of using a Loader, this code assumes those three files contain a Map object in the first, a Set object in the second, and a Set object in the third. You can either make those files using any standard method or else using the FileHandler class.</p> <pre><code>private void loadFiles() { long time = System.currentTimeMillis(); Loader&lt;Map&lt;?, ?&gt;, Map&lt;String, Long&gt;&gt; loader1 = new Loader&lt;Map&lt;?, ?&gt;, Map&lt;String, Long&gt;&gt;(new File("file1.bin"), object1); Loader&lt;Set&lt;?&gt;, Set&lt;Integer&gt;&gt; loader2 = new Loader&lt;Set&lt;?&gt;, Set&lt;Integer&gt;&gt;(new File("file2.bin"), object2); Loader&lt;Set&lt;?&gt;, Set&lt;File&gt;&gt; loader3 = new Loader&lt;Set&lt;?&gt;, Set&lt;&lt;File&gt;&gt;(new File("file3.bin"), object3); boolean OK1 = loader1.load(); boolean OK2 = loader2.load(); boolean OK3 = loader3.load(); if(OK1) { object1 = loader1.getVariable(); } if(OK2) { object2 = loader2.getVariable(); } if(OK3) { object3 = loader3.getVariable(); } System.out.println("File load took " + (System.currentTimeMillis() - time) + "ms."); } </code></pre> <p>The FileHandler class is used to handle file reads and writes in a thread safe way.</p> <pre><code>public class FileHandler { private static Set&lt;File&gt; fileSet = Collections.synchronizedSet(new HashSet&lt;File&gt;()); private final ReentrantReadWriteLock readWriteLock; private final Lock read; private final Lock write; private final File file; /** * Creates a new thread-safe FileHandler for reading and writing objects to a file. * There can be at most one FileHandler associated with any given file, if a FileHandler is created * that is to contain a File that another FileHandler already contains an IllegalArgumentException is thrown. * @param f - the file to be used for reading and writing. * @throws IllegalArgumentException */ public FileHandler(File f) throws IllegalArgumentException { if(!fileSet.add(f)) { throw new IllegalArgumentException("There is already a FileHandler associated with " + f.getName()); } file = f; readWriteLock = new ReentrantReadWriteLock(); read = readWriteLock.readLock(); write = readWriteLock.writeLock(); } /** * Loads an Object whose class is "type" from "file" and returns it if valid, else it returns null. * @param file - the file to be opened for reading. * @param type - the type of the object to be read. * @return the object that was loaded from the file. */ public &lt;T&gt; T loadObject(Class&lt;T&gt; type) { read.lock(); try { InputStream is = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(is)); try { return type.cast(ois.readObject()); } finally { ois.close(); } } catch (FileNotFoundException e) { System.err.println("File load failed with error: " + e.getLocalizedMessage()); } catch (IOException e) { System.err.println("File read failed with error: " + e.getLocalizedMessage()); } catch (ClassNotFoundException e) { System.err.println("Object class definition failed with error: " + e.getLocalizedMessage()); } catch (ClassCastException e) { System.err.println("Object cast failed with error: " + e.getLocalizedMessage()); } finally { read.unlock(); } return null; } /** * Saves an Object of the specified class to "file" and returns true on success. * @param file - the file to be opened for writing. * @param object - the object to be written to file. * @return true if the save was successful. */ public &lt;T&gt; boolean saveObject(T object) { write.lock(); try { OutputStream os = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(os)); try { oos.writeObject(object); } finally { oos.close(); } return true; } catch (FileNotFoundException e) { System.err.println("File save failed with error: " + e.getLocalizedMessage()); } catch (IOException e) { System.err.println("File write failed with error: " + e.getLocalizedMessage()); } finally { write.unlock(); } return false; } @Override protected void finalize() { fileSet.remove(file); } } </code></pre> <p>The FileLoader class is the class that does the typecasting and the actual loading of the object via a FileHandler.</p> <pre><code>public class FileLoader &lt;G, F&gt; implements Runnable { private F variable = null; private FileHandler fileHandler = null; public FileLoader(FileHandler fh, F var) { fileHandler = fh; variable = var; } public F getVariable() { return variable; } @SuppressWarnings("unchecked") @Override public void run() { G temp = (G) fileHandler.loadObject(variable.getClass()); variable = (F) temp; } } </code></pre> <p>Loader is the class that loads the object from the file. It has two type parameters, the first being the generic type of the Object you want to load and the second being the formal type of the object. It takes in a file and an "example object". The example object cannot be null and must have the same type as the object you want to load. The Loader class is the class that is generally used to load the objects from file and contains the high level methods that make use of the other classes.</p> <pre><code>public class Loader &lt;G, F&gt; { private File file = null; private FileHandler handler = null; private FileLoader&lt;G, F&gt; fileLoader = null; private Thread thread = null; private F variable = null; /** * Creates a new Loader. A Loader is used for loading an object from a file with type-safety and thread-safety. * @param f - The file to be loaded from. * @param var - The object to load from the file. */ public Loader(File f, F var) { file = f; variable = var; } /** * Attempts to start loading an object from the file. * @return true if the load started successfully or false if the file cannot be loaded. */ public boolean load() { if(file.exists()) { try { handler = new FileHandler(file); } catch (IllegalArgumentException e) {} if(handler != null) { fileLoader = new FileLoader&lt;G, F&gt;(handler, variable); thread = new Thread(fileLoader); thread.start(); return true; } } return false; } /** * This blocking method waits for the Loader thread to finish and then returns its variable. * If the Loader thread has not started or is null this method returns null. * @return the value loaded from the file. */ public F getVariable() { if(thread != null &amp;&amp; !thread.getState().equals(Thread.State.NEW)) { try { thread.join(); } catch (InterruptedException e) {} return fileLoader.getVariable(); } return null; } } </code></pre>
[]
[ { "body": "<ol>\n<li><p>The <code>Loader</code> class could use Java's built-in <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html\" rel=\"nofollow noreferrer\">ExecutorService</a> with a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Callable.html\" rel=\"nofollow noreferrer\">Callable</a> and a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html\" rel=\"nofollow noreferrer\">Future</a> instead of reinventing the wheel. See: <em>Effective Java Second Edition, Item 47: Know and use the libraries</em></p></li>\n<li><p>Instead of printing error messages you should use a logger framework (for example, SLF4J and Logback). See: <a href=\"https://stackoverflow.com/questions/2727500/log4j-vs-system-out-println-logger-advantages\">log4j vs. System.out.println - logger advantages?</a></p></li>\n</ol>\n\n<p>Some notes about the current code:</p>\n\n<ol>\n<li><p>The static <code>fileSet</code> field in the <code>FileHandler</code> class makes testing really hard. Actually, this class does not fulfill the Single Responsibility Principle. It loads/saves the objects and stores the handled files. I'd separate it to two class. One (<code>FileStorage</code>, for example) is responsible for loading and saving and another class creates <code>FileStorage</code> instances and checks that there is no more than one <code>FileStorage</code> instance for the same file.</p></li>\n<li><p>Do not rely on the finalize method. Make the releasing explicit. For example, create a <code>close()</code> method in the <code>FileHandler</code> which unregisters the file and sets a flag/sets the <code>file</code> field to <code>null</code>. Then check the flag in the <code>loadObject</code> and <code>saveObject</code> methods. If the flag is set throw an <code>IllegalStateException</code>. See <em>Effective Java Second Edition, Item 7: Avoid finalizers</em>.</p></li>\n<li><p>In the <code>Loader.load</code> method I'd use <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">guard clauses</a>:</p>\n\n<pre><code>public boolean load() {\n if (!file.exists()) {\n return false;\n }\n try {\n handler = new FileHandler(file);\n } catch (IllegalArgumentException e) {\n return false;\n }\n\n fileLoader = new FileLoader&lt;G, F&gt;(handler, variable);\n thread = new Thread(fileLoader);\n thread.start();\n return true;\n}\n</code></pre></li>\n<li><p>Consider throwing a non-<code>RuntimeException</code> (a custom <code>Exception</code> subclass, not an <code>IllegalArgumentException</code>) when a client tries to create a <code>FileHandler</code> multiple times for the same file. Another idea is returning the former <code>FileHandler</code> again instead of throwing an exception, since <code>FileHandler</code> is thread-safe.</p></li>\n<li><p>You should check parameters for validity. The majority of the methods and constructors should check at least <code>null</code> input references. See <em>Effective Java Second Edition, Item 38: Check parameters for validity</em></p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T13:05:54.727", "Id": "12416", "ParentId": "12299", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T15:55:38.973", "Id": "12299", "Score": "3", "Tags": [ "java", "multithreading", "thread-safety", "casting", "type-safety" ], "Title": "Loading an Object from File with Type-Safety and Thread-Safe access" }
12299
<p><strong>Summary:</strong></p> <p>I've implemented what I think is a complete Java implementation of the Scala <code>Option</code> class. Could you please review and let me know if I have correctly and completely implemented it? And if not, could you please indicate where I have security, multi-threading, persistence, etc. defects?</p> <p><strong>Details:</strong></p> <p>I'm learning Scala, but still not able to use it in my projects at work. However, I have fallen in love with Scala's <code>Option</code> class. It's the equivalent to Haskell's Maybe. It's a great way to consistently implement the "null object" pattern; i.e. type safely getting rid of tons of potentially hidden NullPointerExceptions.</p> <p>While working on bringing some legacy Java code forward in time (written by me +10 years ago), I kept wanting to use something like Scala's <code>Option</code>, only written in Java for Java. Thus began my hunt for an effective Java version of Scala's option class.</p> <p>First, I googled and found something simple from Daniel Spiewak written in 2008: <a href="http://www.codecommit.com/blog/scala/the-option-pattern" rel="nofollow"><em>The Option Pattern</em></a>.</p> <p>A comment by Tony Morris on Daniel's blog article (above) lead me to an article by Tony Morris where Daniel's idea was made a bit more "complete", also adding to it a bit more complexity (at least to me): <a href="http://blog.tmorris.net/maybe-in-java/" rel="nofollow"><em>Maybe in Java</em></a>.</p> <p>Then, while doing further research to try and find something already written, rather than my writing it myself, I found this one. Written earlier this year (2012), it seemed quite up-to-date: <a href="http://www.synhaptein.com/synhaptein/2012/02/14/scala-option-in-java.html" rel="nofollow"><em>Another Scala option in Java</em></a>.</p> <p>However, once I brought this latest code into my project to use, it started putting yellow squigglies under any references to None. Basically, the singleton the author used was leaking "raw types" into my code generating warnings. That was particularly annoying as I had just finished eliminating all the raw type code warnings from this particular code base the previous week.</p> <p>I was now hooked on getting something working that might resemble a work that could/would appear in the high-quality Java libraries, eliminating raw type leakage, adding things like serialization support, etc.</p> <p>Below is the result as three separate Java class files:</p> <ol> <li>Option - public interface</li> <li>Optional - factory for safely producing instances of Some and None</li> <li>Main - JUnit4 test suite to ensure proper functionality</li> </ol> <p>Please review and then give me any feedback and/or corrections you are willing to contribute.</p> <p><strong>1. Interface Option - public interface</strong></p> <pre><code>package org.public_domain.option; import java.util.Iterator; import java.io.Serializable; public interface Option&lt;T&gt; extends Iterable&lt;T&gt;, Serializable { @Override Iterator&lt;T&gt; iterator(); T get(); T getOrElse(T value); } </code></pre> <p><strong>2. Class Optional - Option instance factory</strong></p> <pre><code>package org.public_domain.option; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; public final class Optional&lt;T&gt; { @SuppressWarnings("rawtypes") private static volatile Option NONE_SINGLETON = new OptionImpl(); public static &lt;T&gt; Option&lt;T&gt; getSome(T value) { if (value == null) { throw new NullPointerException("value must not be null"); } return new OptionImpl&lt;T&gt;(value); } @SuppressWarnings({"unchecked", "cast"}) public static &lt;T&gt; Option&lt;T&gt; getNone() { return (Option&lt;T&gt;)getNoneSingleton(); } @SuppressWarnings("unchecked") public static &lt;T&gt; Option&lt;T&gt; getOptionWithNullAsNone(T value) { return (value != null) ? new OptionImpl&lt;T&gt;(value) : (Option&lt;T&gt;)getNoneSingleton() ; } public static &lt;T&gt; Option&lt;T&gt; getOptionWithNullAsValidValue(T value) { return new OptionImpl&lt;T&gt;(value); } @SuppressWarnings("rawtypes") static Option getNoneSingleton() { return NONE_SINGLETON; } private Optional() { //no instances may be created } private static final class OptionImpl&lt;T&gt; implements Option&lt;T&gt; { private static final long serialVersionUID = -5019534835296036482L; private List&lt;T&gt; values; //contains exactly 0 or 1 value protected OptionImpl() { if (getNoneSingleton() != null) { throw new IllegalStateException("NONE_SINGLETON already defined"); } this.values = Collections.&lt;T&gt;emptyList(); } protected OptionImpl(T value) { List&lt;T&gt; temp = new ArrayList&lt;T&gt;(1); temp.add(value); //even if it might be a null this.values = temp; } @Override public int hashCode() { return this.values.hashCode(); } @Override public boolean equals(Object o) { boolean result = (o == this); if (!result &amp;&amp; (o instanceof OptionImpl&lt;?&gt;)) { result = this.values.equals(((OptionImpl&lt;?&gt;)o).values); } return result; } protected Object readResolve() { Object result = this; if (this.values.isEmpty()) { result = getNoneSingleton(); } return result; } @Override public Iterator&lt;T&gt; iterator() { return (!this.values.isEmpty()) ? Collections.unmodifiableList(new ArrayList&lt;T&gt;(this.values)).iterator() : this.values.iterator() ; } @Override public T get() { if (this.values.isEmpty()) { throw new UnsupportedOperationException("Invalid to attempt to use get() on None"); } return this.values.get(0); } @Override public T getOrElse(T valueArg) { return (!this.values.isEmpty()) ? get() : valueArg ; } } } </code></pre> <p><strong>3. Class Main - JUnit4 test suite</strong></p> <pre><code>package org.public_domain.option.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.junit.Test; import org.public_domain.option.Option; import org.public_domain.option.Optional; public class Main { @Test public void simpleUseCasesSome() { String value = "simpleUseCases"; String valueOther = "simpleUseCases Other"; //Some Option&lt;String&gt; optionSome = Optional.getSome(value); assertEquals(value, optionSome.get()); assertEquals(value, optionSome.getOrElse(valueOther)); assertNotSame(valueOther, optionSome.get()); assertNotSame(valueOther, optionSome.getOrElse(valueOther)); //validate simple iterator state (each call is a newly created iterator) assertTrue(optionSome.iterator().hasNext()); assertEquals(value, optionSome.iterator().next()); assertNotSame(valueOther, optionSome.iterator().next()); //ensure iterator exhausted after single return value (all on the same iterator) Iterator&lt;String&gt; iterator = optionSome.iterator(); assertTrue(iterator.hasNext()); assertEquals(value, iterator.next()); assertFalse(iterator.hasNext()); } @Test public void simpleUseCasesNone() { String value = "simpleUseCases"; String valueOther = "simpleUseCases Other"; Option&lt;String&gt; optionNone = Optional.getNone(); assertEquals(valueOther, optionNone.getOrElse(valueOther)); assertNotSame(value, optionNone.getOrElse(valueOther)); //ensure iterator is already exhausted assertFalse(optionNone.iterator().hasNext()); } @Test (expected=NullPointerException.class) public void simpleInvalidUseCaseSomePassedNull() { @SuppressWarnings("unused") Option&lt;String&gt; optionSome = Optional.getSome(null); } @Test (expected=UnsupportedOperationException.class) public void simpleInvalidUseCaseNoneGet() { Option&lt;String&gt; optionNone = Optional.getNone(); @SuppressWarnings("unused") String value = optionNone.get(); } @Test public void simpleUseCaseEquals() { String value = "simpleUseCases"; String valueSame = value; String valueDifferent = "simpleUseCases Other"; Option&lt;String&gt; optionSome = Optional.getSome(value); Option&lt;String&gt; optionSomeSame = Optional.getSome(valueSame); Option&lt;String&gt; optionSomeDifferent = Optional.getSome(valueDifferent); Option&lt;String&gt; optionNone = Optional.getNone(); Option&lt;String&gt; optionNoneSame = Optional.getNone(); //Some - self-consistency assertSame(optionSome, optionSome); //identity check assertEquals(optionSome, optionSomeSame); //content check assertEquals(optionSomeSame, optionSome); //symmetry check assertNotSame(optionSome, optionSomeDifferent); //identity and content check assertNotSame(optionSomeDifferent, optionSome); //symmetry check //None - self-consistency assertSame(optionNone, optionNoneSame); //identity check assertSame(optionNoneSame, optionNone); //symmetry check //Some-vs-None consistency assertNotSame(optionSome, optionNone); //identity check assertNotSame(optionNone, optionSome); //symmetry check } @Test public void useCaseSomeWithNullAsNone() { String value = null; String valueSame = value; String valueDifferent = "simpleUseCases"; Option&lt;String&gt; option = Optional.getOptionWithNullAsNone(value); Option&lt;String&gt; optionSame = Optional.getOptionWithNullAsNone(valueSame); Option&lt;String&gt; optionDifferent = Optional.getOptionWithNullAsNone(valueDifferent); //Some - self-consistency assertSame(option, option); //identity check assertEquals(option, optionSame); //content check assertEquals(optionSame, option); //symmetry check assertNotSame(option, optionDifferent); //identity and content check assertNotSame(optionDifferent, option); //symmetry check //None consistency Option&lt;String&gt; optionNone = Optional.getNone(); assertSame(option, optionNone); assertSame(optionNone, option); //symmetry check } @Test public void useCaseSomeWithNullAsValidValue() { String value = null; String valueSame = value; String valueDifferent = "simpleUseCases"; Option&lt;String&gt; option = Optional.getOptionWithNullAsValidValue(value); Option&lt;String&gt; optionSame = Optional.getOptionWithNullAsValidValue(valueSame); Option&lt;String&gt; optionDifferent = Optional.getOptionWithNullAsValidValue(valueDifferent); //Some - self-consistency assertSame(option, option); //identity check assertEquals(option, optionSame); //content check assertEquals(optionSame, option); //symmetry check assertNotSame(option, optionDifferent); //identity and content check assertNotSame(optionDifferent, option); //symmetry check //None consistency Option&lt;String&gt; optionNone = Optional.getNone(); assertNotSame(option, optionNone); assertNotSame(optionNone, option); //symmetry check } private byte[] transformToByteArray(Object root) { ByteArrayOutputStream baos = new ByteArrayOutputStream(65536); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(root); } catch (IOException e) { e.printStackTrace(); } return baos.toByteArray(); } private Object transformFromByteArray(byte[] content) { Object result = null; ByteArrayInputStream bais = new ByteArrayInputStream(content); ObjectInputStream ois; try { ois = new ObjectInputStream(bais); result = ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return result; } @Test public void useCaseSerialzation() { String value = "simpleUseCases"; String valueSame = value; String valueDifferent = "simpleUseCases Other"; Option&lt;String&gt; optionSome = Optional.getSome(value); Option&lt;String&gt; optionSomeSame = Optional.getSome(valueSame); Option&lt;String&gt; optionSomeDifferent = Optional.getSome(valueDifferent); Option&lt;String&gt; optionNone = Optional.getNone(); Option&lt;String&gt; optionNoneSame = Optional.getNone(); Map&lt;String, Option&lt;String&gt;&gt; dataIn = new HashMap&lt;String, Option&lt;String&gt;&gt;(); dataIn.put("optionSome", optionSome); dataIn.put("optionSomeSame", optionSomeSame); dataIn.put("optionSomeDifferent", optionSomeDifferent); dataIn.put("optionNone", optionNone); dataIn.put("optionNoneSame", optionNoneSame); byte[] dataInAsByteArray = transformToByteArray(dataIn); @SuppressWarnings("unchecked") Map&lt;String, Option&lt;String&gt;&gt; dataOut = (Map&lt;String, Option&lt;String&gt;&gt;)transformFromByteArray(dataInAsByteArray); assertEquals(optionSome, dataOut.get("optionSome")); assertEquals(optionSomeSame, dataOut.get("optionSomeSame")); assertEquals(optionSomeDifferent, dataOut.get("optionSomeDifferent")); assertSame(optionNone, dataOut.get("optionNone")); assertSame(optionNoneSame, dataOut.get("optionNoneSame")); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T19:53:23.553", "Id": "19757", "Score": "0", "body": "Here's a great comment by Daniel Spiewak regarding the proper context and effective use of Scala's Option: http://beust.com/weblog/2010/07/28/why-scalas-option-and-haskells-maybe-types-wont-save-you-from-null/comment-page-1/#comment-8204" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T14:21:06.650", "Id": "19793", "Score": "1", "body": "FYI: The [\"Functional Java\" library](http://functionaljava.org/) has a `Option` implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-10T02:22:05.997", "Id": "20035", "Score": "0", "body": "Awesome video covering Scala's Option described from the perspective of Monads: http://www.youtube.com/watch?v=Mw_Jnn_Y5iA" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T23:57:30.800", "Id": "20985", "Score": "1", "body": "Options are monads and monads have certain laws they must follow (what methods they should have and those methods should do). If you want to learn more about the monad laws a great place to start is by checking out James Iry's series of posts \"Monads are not Elephants\" starting at http://james-iry.blogspot.com/2007/09/monads-are-elephants-part-1.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-25T14:52:58.990", "Id": "324249", "Score": "0", "body": "3 years later, Java 8 has `Optional<T>`. What we need even more is something similar to Scala's `Try[T]`." } ]
[ { "body": "<p>The main problem of your code is that it is written in Java. ;)</p>\n\n<p>Unfortunately Java doesn't support Lambdas, Pattern-Matching and Type-Inference - three main points for effective using Options. Without these features you can't use Option as they should be used.</p>\n\n<p>Option is a Monad but your implementation isn't and probably will it never be because Javas syntax is not powerful enough to allow Monad-handling in a useful manner. See the following code example:</p>\n\n<pre><code>val value = for {\n o &lt;- Option(somePotenzialNullValue)\n a &lt;- someOptionValue(o)\n b &lt;- anotherOptionValue\n c = a operateOn b\n if c == anyValue\n} yield c\n</code></pre>\n\n<p>How would you implement this in Java? Even if you use Javas foreach-loop this will always look ugly and not intuitive.</p>\n\n<p>If you wanna know how Options work, how they can implemented in an effective way or to have some fun, than implement Option in Scala - or use Java8 as I did. ;)</p>\n\n<p>Java8 will support Lambdas, thus it allows some useful code lifting. Here is my implementation: <a href=\"https://gist.github.com/1994681\">Java8 Option type</a> (not a perfect implementation but it works)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T13:02:25.173", "Id": "19784", "Score": "0", "body": "LOL! I agree. However, while I am pre-Java 8 land, I still want to get even the minimal value out of the Java type system to catch possible NPE pathways. I get that this Option doesn't provide that entirely. No implementation of the pattern really can. However, if I use Option AND I avoid the use of Option.get(), then I will be more likely to think of and handle possible NPE pathways. In summary, my favorite summary of Option is this - think of it a Set (or List) which either holds a single clearly defined element or the list is empty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T13:40:22.317", "Id": "19788", "Score": "0", "body": "I read through the Java8 version of Option to which you linked. Ugh! Long before Java 8 is prevalent, I will be doing Scala full time on my projects." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T00:37:14.813", "Id": "12311", "ParentId": "12303", "Score": "6" } }, { "body": "<p>If you want to guarantee serializability, the <code>T</code> type parameter must be <code>Serializable</code>, or your <code>Option</code> won't be:</p>\n\n<pre><code>public interface Option&lt;T extends Serializable&gt; extends Iterable&lt;T&gt;, Serializable\n</code></pre>\n\n<p>Also, the use of a public interface to declare <code>Option</code> allows anybody to create their own implementation. The code will break if it is given another implementation of the <code>Option</code> interface, because it assumes the only implementation is an <code>OptionImpl</code>.</p>\n\n<p>Here's an alternate implementation much the same as yours that I'd come up with:</p>\n\n<pre><code>package util;\n\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\npublic abstract class Option&lt;A&gt; implements Iterable&lt;A&gt; {\n\n private Option() {}\n\n public abstract A get();\n public abstract A getOrElse(A defaultResult);\n public abstract Iterator&lt;A&gt; iterator();\n public abstract boolean match(Option&lt;A&gt; other);\n\n @SuppressWarnings(\"unchecked\")\n public static &lt;A&gt; Option&lt;A&gt; Option(final A a) {\n return a == null? (Option&lt;A&gt;)None : Some(a);\n }\n\n public static &lt;A&gt; Option&lt;A&gt; Some(final A a) {\n return new _Some&lt;A&gt;(a);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static &lt;A&gt; Option&lt;A&gt; None() {\n return (Option&lt;A&gt;)None;\n }\n\n\n @SuppressWarnings(\"rawtypes\")\n public static final Option None = new _None();\n\n\n private static final class _Some&lt;A&gt; extends Option&lt;A&gt; {\n private final A value;\n\n private _Some(A a) {\n if (a == null) throw new IllegalArgumentException(\"argument to Some may not be null\");\n this.value = a;\n }\n\n @Override\n public A get() {\n return this.value;\n }\n\n @Override\n public A getOrElse(final A ignored) {\n return this.value;\n }\n\n @Override\n public Iterator&lt;A&gt; iterator() {\n return Collections.&lt;A&gt;singleton(this.value).iterator();\n }\n\n @Override\n public boolean match(final Option&lt;A&gt; other) {\n return other == None? false : value.equals( ((_Some&lt;A&gt;)other).value );\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public boolean equals(final Object obj) {\n return obj instanceof Option? match((Option&lt;A&gt;)obj) : false;\n }\n\n @Override\n public int hashCode() {\n return this.value.hashCode();\n }\n\n @Override\n public String toString() {\n return \"Some(\" + this.value + \")\";\n }\n }\n\n\n private static final class _None&lt;A&gt; extends Option&lt;A&gt; {\n private _None() {}\n\n @Override\n public A get() { throw new NoSuchElementException(\"None.get() called\"); }\n\n @Override\n public A getOrElse(final A result) {\n return result;\n }\n\n @Override\n public Iterator&lt;A&gt; iterator() {\n return Collections.&lt;A&gt;emptyList().iterator();\n }\n\n @Override\n @SuppressWarnings(\"rawtypes\")\n public boolean match(final Option other) {\n return other == None;\n }\n\n @Override\n public boolean equals(final Object obj) {\n return obj == this;\n }\n\n @Override\n public int hashCode() {\n return 0;\n }\n\n @Override\n public String toString() {\n return \"None\";\n }\n }\n}\n</code></pre>\n\n<p>For usage, I use <code>import static</code>:</p>\n\n<pre><code>import util.Option;\nimport static util.Option.*;\n\nOption&lt;Boolean&gt; selfDestruct = getSelfDestructSequence();\nif (selfDestruct.match(Some(true)) {\n blowUpTheShip();\n}\n</code></pre>\n\n<p>That way it reads similar to pattern matching and deconstruction, but of course it's really construction and <code>equals()</code>. And you can compare to <code>None</code> using <code>==</code>.</p>\n\n<p>The only thing I don't like about this is that the <code>None</code> singleton does give unchecked warnings on usage unless you use the factory method to return it. If only we had existential types, we could overcome that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T13:12:39.637", "Id": "19785", "Score": "0", "body": "I wouldn't want to restrict my Option container to just holding a Serializable result, would I? When modeling this, I tried to follow the pattern set in the standard Java SE library for ArrayList/AbstractList/AbstractCollection. It appears that they will hold any Object. And then expect the client to handle any issues with Serialization in their own classes, should they need Java Serialization support. My implementation intended to just make handling Serialization transparent should a client want to use it. I may be missing something completely obvious, though. Thoughts?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T13:22:37.410", "Id": "19786", "Score": "0", "body": "BTW, I really like your use of \"Collections.<A>singleton(this.value)\". I did not know about and am very please to learn about this method. I have updated my implementation to incorporate it above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T13:29:51.253", "Id": "19787", "Score": "0", "body": "What was your reasoning to implement the match() method as opposed to overriding equals?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T14:41:17.897", "Id": "19795", "Score": "1", "body": "Being a bit tired when responding, I took `Serializable` as being more of a contract than a possibility. Of course you can declare the Option as Serializable and it will be if its contents are, so I agree with your assessment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T14:45:49.123", "Id": "19797", "Score": "1", "body": "Re: `match()` vs. `equals()`, part of the goal was to make it read more like Scala. Of course, I'd also implement `equals()` and `hashCode()`, `equals()` almost being an alias for `match()` (match is type-safe, whereas equals cannot be). So part of the reasoning was type safety...the compiler won't let you call `Option<A>.match(Option<B>)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T15:01:36.027", "Id": "19800", "Score": "1", "body": "There, added `equals` and `hashCode`, as well as a missing factory method `Option` which will take an `A` and turn it into a `None` if null, or `Some(a)` otherwise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T21:32:03.660", "Id": "19814", "Score": "0", "body": "Nice. Okay, so at this point, if you serialize out the Option as defined above, and one of the instance is of None, then when the object graph is read back in, wouldn't the reconstruction create a new instance of None, bypassing your static singleton constructor pattern? If so, your equals() on either None instance (static or deserialized) would now be incorrect due to it being a same reference check, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-07T05:43:44.657", "Id": "19820", "Score": "0", "body": "I didn't implement Serializable in my version. You had it implemented right, and it could be added to my version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-07T13:40:32.163", "Id": "19839", "Score": "0", "body": "Doh! My bad! Makes sense." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T03:54:12.457", "Id": "12314", "ParentId": "12303", "Score": "1" } }, { "body": "<p>Your code essentially does <strong>one</strong> thing:</p>\n\n<p><strong>It replaces a <code>NullPointerException</code> with an <code>UnsupportedOperationException</code> (and even that only in some cases).</strong></p>\n\n<p>This is simply not a useful semantic.</p>\n\n<p>It’s telling that this simple switch of one exception for another requires, in your code,</p>\n\n<ul>\n<li>an interface</li>\n<li>a static final helper class</li>\n<li>a kind-of singleton (which isn’t really one)</li>\n<li>a metric ton of unit tests that only test trivial behaviour.</li>\n</ul>\n\n<p>Not to be blunt, but this code exemplifies everything that you can do wrong when going through the motions in Java. It uses unit tests, design patterns and follows non-fitting interface conventions (Bean-style getters even though your class is clearly <em>not</em> a bean) and achieves … essentially nothing.</p>\n\n<p>Furthermore, this code is quite inefficient since it is implemented in terms of <code>Set</code>, and while that’s certainly very elegant, it results in tremendous runtime performance bloat.</p>\n\n<p>In fact, due to its implementation in terms of <code>Set</code> the whole <code>None</code> special case is redundant since the <code>Set</code> already has this case built in – as an empty set.</p>\n\n<p>Eventually this whole boilerplate code hides a <em>single</em> useful method<sup>1</sup>, namely <code>getOrElse</code> – and that method (which should be called just <code>orElse</code>) could just as easily be a static method in some helper class. And I’m not convinced that writing <code>obj.orElse(other)</code> is so much more readable than <code>obj != null ? obj : other</code> that it requires its own method.</p>\n\n<hr>\n\n<p><sup>1</sup> The iterator interface is actually also potentially useful but also doesn’t justify this amount of boilerplate.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T10:26:54.897", "Id": "19900", "Score": "0", "body": "I do not completely agree with you. The exception replacement is true. I would prefer a simple orElse method. But one other thing that this code is contributing to is communication. It tells the user of the class what to expect from the method. It is impossible to tell if a function can return null, while an Option is clearly communicating that you cannot depend on getting what you are requesting from that method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T10:29:26.497", "Id": "19901", "Score": "1", "body": "@daramarak Unfortunately, due to Java’s semantics, a null value is *always* to expected, unless documented otherwise. So I really don’t think using `Option` adds anything. The *opposite* would, i.e. some class `Value` (or `NonNull` or similar) that *guarantees* a non-null value. And yes, such a class is actually a useful tool." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T10:46:07.750", "Id": "19902", "Score": "0", "body": "True, but with this class it is possible to write a library or application simply state that all methods will return a value unless actually returning a Option. But I feel this is more a weakness to the language, it should support option rather than supporting null (if it could be implemented cost free of course :D)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T23:16:38.583", "Id": "19977", "Score": "0", "body": "@KonradRudolph Your response is pretty strong. I disagree that it only replaces one thing for another. After having used it in code I was writing just today, there were several instances where it substantially eliminated a series of intricate constructors based on parameters which could be passed null. Using Option, I was able to drop it to a single constructor and then used Option as my means to direct defaults, all with substantially less null checking boilerplate than I had there before. It also delightfully simplified understanding the parameters to the constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T23:19:17.460", "Id": "19978", "Score": "0", "body": "BTW, I wouldn't have posted this if my google search for \"scala option for Java\" had turned up the Functional Java link posted in a comment on the main thread: http://functionaljava.googlecode.com/svn/artifacts/3.0/javadoc/fj/data/Option.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T11:21:10.647", "Id": "20005", "Score": "0", "body": "@chaotic3quilibrium I’d be interested to see that code, then. Because I don’t believe it. I don’t see how that code reduces the number of checks in any way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T21:27:13.597", "Id": "20013", "Score": "0", "body": "@KonradRudolph No worries. Best of luck to you given your obvious openness and your practiced experience. {smirk}" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-10T08:13:37.083", "Id": "20041", "Score": "1", "body": "@chaotic3quilibrium If you can’t deal with criticism I’d rather suggest you don’t post on a code review site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T23:24:37.603", "Id": "20927", "Score": "0", "body": "@KonradRudolph If you can't do your own research, I wouldn't post comments: http://james-iry.blogspot.com/2010/08/why-scalas-and-haskells-types-will-save.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T08:27:35.430", "Id": "20934", "Score": "0", "body": "@chaotic3quilibrium You’re assuming things about me. But how is that relevant? I know Cedric’s misguided essay on the topic. If anything, this nice rebuttal you linked to bolsters *my* arguments above. I didn’t say that you can’t have meaningful `Option` in Java (though it’s hard due to lacking syntax) – the accepted answer shows such a type. All I said that *your* particular implementation almost exclusively replaces NPE by a custom exception." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T13:25:22.410", "Id": "20942", "Score": "0", "body": "@KonradRudolph Ah. Got it. And I'm much more in alignment with you than before. However, I have been using it now for 3 weeks. And using the assumption at my immutable class constructors must accept an object reference or an Option<T>, I've experienced reduced code bloat, enhanced readability and much easier reasoning than with the standard Java null patterns I had been exploiting before. If I get some time here soon, I will post some examples of what I mean. You may not see the value as high as I do. That's understandable. :)" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T09:06:38.393", "Id": "12379", "ParentId": "12303", "Score": "1" } }, { "body": "<p>Just a few notes about the tests:</p>\n\n<p>Too many asserts in one test is a bad smell. It's <a href=\"http://xunitpatterns.com/Assertion%20Roulette.html\" rel=\"nofollow\">Assertion Roulette</a> and you lost <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow\">Defect Localization</a>. If the first assert method throws an exception you won't know anything about the results of the other assert calls which could be important because they could help debugging and defect localization.</p>\n\n<p>Furthermore, adding a <a href=\"http://xunitpatterns.com/Assertion%20Message.html\" rel=\"nofollow\">message parameter</a> to every assert is a good practice and helps debugging. Usually you get the line number in a stack trace when a test fails but a unique message makes debugging faster. Small unique numbers or short unique strings are usually enough if you have more than one assert in a test method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T18:09:18.337", "Id": "14462", "ParentId": "12303", "Score": "1" } } ]
{ "AcceptedAnswerId": "12314", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T18:49:58.343", "Id": "12303", "Score": "2", "Tags": [ "java", "generics" ], "Title": "Scala Option conversion to Java" }
12303
<p>My background is with C and python, and Javascript is fairly new to me, so I'm wondering if this is reasonable code.</p> <p>In particular, is it appropriate to use the higher order function <code>makecb</code> in this context, or is there a better/shorter/clearer way of writing it?</p> <pre><code>$(function(){ var controllers = { "#showhelp": { name: "Help", id: "#help" }, "#showlog": { name: "Log", id: "#log" } }; function hideModals(){ for(cter in controllers){ $(controllers[cter].id).css("display", "none"); $(cter).text("Show "+controllers[cter].name); } } function showModal(cter){ hideModals(); $(controllers[cter].id).css("display","block"); $(cter).text("Hide "+controllers[cter].name); } function makecb(controller){ return function(){ if($(controllers[controller].id).css("display")=='none'){ showModal(controller); }else{ hideModals(); } } } for(cter in controllers){ $(cter).click(makecb(cter)); } }); </code></pre> <p>The idea is that the only thing that has to be done to add a new modal dialogue is to add the description. The appropriate html is as follows:</p> <pre><code>&lt;div id="bottombar"&gt; &lt;a id="showlog" href="#"&gt;Show Log&lt;/a&gt; &lt;a id="showhelp" href="#"&gt;Show Help&lt;/a&gt; &lt;/div&gt; &lt;div id="log" style="display:none"&gt;&lt;/div&gt; &lt;div id="help" style="display:none"&gt;&lt;/div&gt; </code></pre> <p>PS: If you have the privileges needed to add the tags <code>data-driven-programming</code> or <code>idiom</code> and you feel it would be appropriate, I'd appreciate it.</p>
[]
[ { "body": "<p>While the use of high order functions in JavaScript is fine and normal, your code has other issues.</p>\n<h1>Symptoms</h1>\n<p>Your usage of the <a href=\"http://api.jquery.com/css/\" rel=\"nofollow noreferrer\"><code>$.fn.css</code></a> method here is to do 3 things:</p>\n<ol>\n<li>show the element</li>\n<li>hide the element (more precisely: exact opposite of state 1)</li>\n<li>enumerate the state of the visibility of the element (check if it is in state 1 or state 2)</li>\n</ol>\n<p>It would be better code to have cases 1 and 2 be the same method call, differentiated by a <code>boolean</code> parameter. In this case I would use <a href=\"http://api.jquery.com/toggle/\" rel=\"nofollow noreferrer\"><code>$.fn.toggle()</code></a>. In general it is better to say <strong>what</strong> you want, rather than <strong>how</strong> to do something you want to do. This is because the details of how to do something tend to change, while the logic remains the same. To complete this separation you now should use some function that checks the state of this item; enter in this case <a href=\"http://api.jquery.com/visible-selector/\" rel=\"nofollow noreferrer\"><code>:visible</code></a>; thus those 3 uses become:</p>\n<ol>\n<li><code>$(element).toggle(true);</code></li>\n<li><code>$(element).toggle(false);</code></li>\n<li><code>$(element).is(':visible');</code></li>\n</ol>\n<p>However, you aren't just toggling a single element's visibility here; the link text is changing at the same time. Atop that, the overall logic is that the system can only have at most one dialog open at a time.</p>\n<h1>Cause</h1>\n<p>I think the structure of this code fails to make that logic immediately obvious.</p>\n<h1>Solution</h1>\n<p>Let's abstract the implementation away a little into a method (to be written farther down) and rewrite the click event as if it already exists:</p>\n<pre><code>$(function () {\n var $buttons = $('#bottombar a'),\n controllers = {\n &quot;showhelp&quot;: { name: &quot;Help&quot;, id: &quot;#help&quot; },\n &quot;showlog&quot;: { name: &quot;Log&quot;, id: &quot;#log&quot; }\n };\n\n $buttons.click(function (e) {\n var that = this;\n e.preventDefault();\n toggleModal(function () {\n return that === this &amp;&amp; !$(controllers[this.id].id).is(':visible');\n });\n });\n});\n</code></pre>\n<p>Here now there are a few things I am not particularly fond of:</p>\n<ol>\n<li>not caching the inner jQuery object</li>\n<li>checking the state of each dialog by checking its implementation when we already have a structure modeling it</li>\n</ol>\n<p>We can easily kill both of those with a simple modification to the controllers object:</p>\n<pre><code>$(function () {\n var $buttons = $('#bottombar a'),\n controllers = {\n &quot;showhelp&quot;: {\n name: &quot;Help&quot;,\n dialog: $(&quot;#help&quot;),\n visible: false\n },\n &quot;showlog&quot;: {\n name: &quot;Log&quot;,\n dialog: $(&quot;#log&quot;),\n visible: false\n }\n };\n\n $buttons.click(function (e) {\n var that = this;\n e.preventDefault();\n\n toggleDialogs(function () {\n return that === this &amp;&amp; !controllers[this.id].visible;\n });\n });\n});\n</code></pre>\n<p>All that is left is actually writing the implementation of <code>toggleDialogs</code>.</p>\n<h1>End Result</h1>\n<pre><code>$(function () {\n var $buttons = $('#bottombar a'),\n controllers = {\n &quot;showhelp&quot;: {\n name: &quot;Help&quot;,\n dialog: $(&quot;#help&quot;),\n visible: false\n },\n &quot;showlog&quot;: {\n name: &quot;Log&quot;,\n dialog: $(&quot;#log&quot;),\n visible: false\n }\n };\n \n function toggleDialogs(visiblefn) {\n $buttons.each(function () {\n var isVisible = visiblefn.call(this),\n model = controllers[this.id];\n model.dialog.toggle(isVisible);\n if (isVisible) {\n $(this).text('Hide ' + model.name);\n } else {\n $(this).text('Show ' + model.name);\n }\n model.visible = isVisible;\n });\n }\n\n $buttons.click(function (e) {\n var that = this;\n e.preventDefault();\n\n toggleDialogs(function () {\n return that === this &amp;&amp; !controllers[this.id].visible;\n });\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T23:28:22.603", "Id": "19764", "Score": "0", "body": "[jsFiddle here](http://jsfiddle.net/QCNAe/2/)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T11:21:21.650", "Id": "19773", "Score": "0", "body": "Cheers Bill! I didn't even know about `preventDefault()`, and never thought about grabbing the object for the dialog using jquery to put it in the conrtroller. +1" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T23:24:25.777", "Id": "12308", "ParentId": "12304", "Score": "1" } }, { "body": "<p>General tips:</p>\n\n<ul>\n<li>For calls done more than once and return the same results, cache them in a variable</li>\n<li>Look out for variable declarations. Always use <code>var</code> unless they are known to be somewhere in the outer scope. Otherwise, forgetting it would make it an implied global - which is bad.</li>\n<li>Localize variables whenever necessary. This is to prevent global conflict from destroying your references.</li>\n<li>Hard-coding is bad enough. Hard-coding in two or more places is worse. In your code, you are hard coding the ids to for modals, the links, and on the JS to link them both. Better use existing references and modify it to fit other references. In this case, use the href hashes. They were built to point to ids.</li>\n<li>DRY (Don't Repeat Yourself). Factor out common operations and turn them into their own functions. For example, the link text replace operation.</li>\n<li>In jQuery, chain when necessary, especially when the previous operation returns the elements needed for the next operation. This avoids multiple calls to jQuery just to re-reference the element for the next operation.</li>\n</ul>\n\n<p><a href=\"http://jsfiddle.net/9KyzY/\" rel=\"nofollow\">Here's a working fiddle</a></p>\n\n<p>Here's a modified HTML</p>\n\n<pre><code>&lt;div id=\"bottombar\"&gt;\n &lt;!--semantics and progressive enhancement tip: use hash to point to id'ed sections--&gt;\n &lt;a href=\"#log\"&gt;Show Log&lt;/a&gt;\n &lt;a href=\"#help\"&gt;Show Help&lt;/a&gt; \n&lt;/div&gt;\n\n&lt;!--HTML sections should be id'ed so hash links can jump to them if JS is off--&gt;\n&lt;!--Use classes to refer to element of common functionality, both in CSS and JS--&gt;\n&lt;div id=\"log\" class=\"modal\"&gt;&lt;/div&gt;\n&lt;div id=\"help\" class=\"modal\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>/*use external style instead of inline*/\n.modal{\n display:none;\n}\n</code></pre>\n\n<p>here's a packed version (no comments):</p>\n\n<pre><code>$(function ($) {\n var modals = $('.modal');\n function setText(prependText, oldText) {\n return prependText + ' ' + oldText.substring(oldText.indexOf(' ') + 1)\n }\n $('#bottombar').on('click', 'a', function (event) {\n event.preventDefault();\n var $this = $(this),\n modalid = $this.attr('href'),\n modal = modals.filter(modalid);\n if (modal.is(':visible')) {\n modal.hide();\n $this.text(function (index, oldText) {\n return setText('Show', oldText)\n })\n } else {\n modals.hide();\n modal.show();\n $this.text(function (index, oldText) {\n return setText('Hide', oldText)\n }).siblings().text(function (index, oldText) {\n return setText('Show', oldText)\n })\n }\n })\n});\n</code></pre>\n\n<p>here's a commented version:</p>\n\n<pre><code>//use the provided local jQuery and don't rely on the global.\n//That way, name conflicts won't affect your inner code\n$(function ($) {\n\n //get all modals and reference them\n var modals = $('.modal');\n\n //factor out the link text replace operation\n //avoid regex on minor operations as it is slow\n function setText(prependText, oldText) {\n return prependText + ' ' +oldText.substring(oldText.indexOf(' ')+ 1);\n }\n\n //use delegation to add your handler. This avoids putting handlers on each link\n $('#bottombar').on('click', 'a', function (event) {\n\n //prevent the default action. Although hashes work, this one prevents\n //the page from jumping upwards\n event.preventDefault();\n\n //cache items used over and over again in the following operations\n var $this = $(this),\n modalid = $this.attr('href'),\n modal = modals.filter(modalid);\n\n if (modal.is(':visible')) {\n\n //if modal is visible\n\n //hide the current modal\n modal.hide();\n\n //replace the current link text\n $this.text(function (index, oldText) {\n return setText('Show', oldText);\n });\n\n } else {\n\n //if modal is not visible\n\n //hide other modals\n modals.hide();\n\n //show the current modal\n modal.show();\n\n //set link texts accordingly\n $this\n .text(function (index, oldText) {\n return setText('Hide', oldText);\n })\n .siblings()\n .text(function (index, oldText) {\n return setText('Show', oldText);\n });\n }\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T11:27:10.050", "Id": "19774", "Score": "0", "body": "Thanks Joseph. It felt wrong while writing it, and removing the `controllers` object is much cleaner. I feel stupid for not thinking of grabbing all the modals using a class too! Much yet unlearned, it seems..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-06T00:01:51.947", "Id": "12310", "ParentId": "12304", "Score": "2" } } ]
{ "AcceptedAnswerId": "12310", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T20:22:26.527", "Id": "12304", "Score": "-1", "Tags": [ "javascript", "jquery" ], "Title": "Is there a better way of writing this JavaScript, or is it idiomatic?" }
12304