body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<blockquote> <p><strong>Goal:</strong></p> <p>Write a character creator program for a role-playing game. The player should be given a pool of 30 points to spend on four attributes: strength, health, wisdom, and dexterity. The player should be able to spend points from the pool on any attribute and should also be able to take points from an attribute and put them back into the pool.</p> <p><em>Python Programming for the Absolute Beginner</em> by Michael Dawson</p> </blockquote> <p>My attempt:</p> <pre><code>print "create a character! you have points to assign to strength, health, wisdom, and dexterity." name=raw_input("what's your character's name? ") points=30 attributes=("health", "strength", "wisdom", "dexterity") strength=0 health=0 wisdom=0 dexterity=0 while True: print print "you have", points, "points left." print \ """ 1-add points 2-take points 3-see points per attribute 4-exit """ choice=raw_input("choice: ") if choice=="1": attribute=raw_input("which attribute? strength, health, wisdom, or dexterity? ") if attribute in attributes: add=int(raw_input("how many points? ")) if add&lt;=points and add&gt;0: if attribute=="strength": strength+=add print name, "now has", strength, "strength points." elif attribute=="health": health+=add print name, "now has", health, "health points." elif attribute=="wisdom": wisdom+=add print name, "now has", wisdom, "wisdom points." elif attribute=="dexterity": dexterity+=add print name, "now has", dexterity, "dexterity points." points-=add else: print "invalid number of points." else: print "invalid attribute." elif choice=="2": attribute=raw_input("which attribute? strength, health, wisdom, or dexterity? ") if attribute in attributes: take=int(raw_input("how many points? ")) if attribute=="strength" and take&lt;=strength and take&gt;0: strength-=take print name, "now has", strength, "strength points." points+=take elif attribute=="health" and take&lt;=health and take&gt;0: health-=take print name, "now has", health, "health points." points+=take elif attribute=="wisdom" and take&lt;=wisdom and take&gt;0: wisdom-=take print name, "now has", wisdom, "wisdom points." points+=take elif attribute=="dexterity" and take&lt;=dexterity and take&gt;0: dexterity-=take print name, "now has", dexterity, "dexterity points." points+=take else: print "invalid number of points." else: print "invalid attribute." elif choice=="3": print "strength -", strength print "health -", health print "wisdom -", wisdom print "dexterity -", dexterity elif choice=="4": if points==0: break else: print "use all your points!" else: print "invalid choice." print "congrats! you're done designing "+name+'.' print name, "has", strength, "strength points,", health, "health points,", wisdom, "wisdom points, and", dexterity, "dexterity points." </code></pre> <p>I'm learning my first language, Python, and would really appreciate it if anyone could tell me if I'm writing the most efficient code possible.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T18:25:46.937", "Id": "12943", "Score": "1", "body": "what do you mean by efficient? Running speed? This kind of program will never be slow, you should focus more about readability than speed. and the mandatory link: http://c2.com/cgi/wiki?PrematureOptimization" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T23:34:09.430", "Id": "12955", "Score": "0", "body": "I meant readability and efficiency in expression (am I writing more than I need to to achieve my goal?), but thanks anyway for the interesting link!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-06T14:21:44.107", "Id": "13622", "Score": "0", "body": "You may notice that when entering incorrect input, the error handling of this solution is not great - while my solution is class-based the error-handling could be applied to either representation" } ]
[ { "body": "<p>One of the first things I would do is try and group your information into neater packages, rather than having a bunch of free variables. I assume you're not too familiar with classes, but try putting your character's attributes into a data structure like a List, or even better - a Dictionary:</p>\n\n<pre><code>attributes = {'health': 0, 'strength': 0, 'wisdom': 0, 'dexterity': 0 }\n</code></pre>\n\n<p>If you want to change <code>attributes</code>, you can then do</p>\n\n<pre><code>attributes['health'] = some_value\n</code></pre>\n\n<p>or to increment,</p>\n\n<pre><code>attributes['health'] += some_value\n</code></pre>\n\n<p>Secondly, the best way to improve your program is to make it more readable by splitting your code up into functions. For instance, the code below is an example of what it may look like if you took some of the stat changing logic out of the main program:</p>\n\n<pre><code>if choice==\"1\":\n stat = input(\"Which stat? \")\n modifier = input(\"By how much? \")\n add_stats(modifier, stat)\nelif choice==\"2\":\n stat = input(\"Which stat? \")\n modifier = input(\"By how much? \")\n take_stats(modifier, stat)\nelif choice==\"3\":\n print(show_player_stats())\n</code></pre>\n\n<p>In general, any where you find yourself getting \"too deep\" in nests of <code>if</code> statements and loops, or you find yourself repeating your code, try and break it out into a function. Bear in mind this is a crude example, and you'll have to develop your own solution, but in terms of readability it's a vast improvement.</p>\n\n<p>I've made a start on a version of your game using my own approach, although I haven't implemented all of it (you can't subtract points for instance). However, you can probably already see where the program has improved on things.</p>\n\n<p>Things to note about my version compared to yours:</p>\n\n<ul>\n<li>There is commenting (although basic). Commenting code is a MUST, even if it's for yourself. It will help you understand your own code and help anyone else who uses it, even if it's just to show different parts of the program.</li>\n<li>The code is broken down into functions, which improves readability and allows you to re-use bits of code in the future. For instance, every time you want to print your character's info, you just call <code>print_character()</code>!</li>\n<li>The code is neater - I'm packing information into a data structure, strings are formatted with linebreaks, logic is compartmented into smaller, manageable chunks.</li>\n</ul>\n\n<p>However, I have used some Python you may not be familiar with, like the <code>keys()</code> method. But it's important to go through the code and try and work out what's happening. This will help to expose you to the \"Python\" way of doing things.</p>\n\n<pre><code>##### GAME FUNCTIONS #####\n\ndef add_character_points():\n attribute = raw_input(\"\\nWhich attribute? Strength, Health, Wisdom or Dexterity?\\n\")\n\n if attribute in my_character.keys():\n amount = int(raw_input(\"By how much?\"))\n\n if (amount &gt; my_character['points']) or (my_character['points'] &lt;= 0):\n print \"Not enough points!\"\n else:\n my_character[attribute] += amount\n my_character['points'] -= amount\n else:\n print \"\\nThat attribute doesn't exist!\\n\"\n\n\ndef print_character():\n for attribute in my_character.keys():\n print attribute, \" : \", my_character[attribute]\n\n\n##### MAIN FUNCTION #####\n\nmy_character = {'name': '', 'strength': 0, 'health': 0, 'wisdom': 0, 'dexterity': 0, 'points': 20}\nrunning = True\n\nprint \"Create a character! You have points to assign to strength, health, wisdom, and dexterity.\"\n\nmy_character['name'] = raw_input(\"What is your character's name? \")\n\nwhile running:\n print \"\\nYou have \", my_character['points'], \" points left.\\n\"\n print \"1. Add points\\n2. Remove points\\n3. See current attributes\\n4. Exit\\n\"\n\n choice = raw_input(\"Choice:\")\n\n if choice == \"1\":\n add_character_points()\n elif choice == \"3\":\n print_character()\n elif choice == \"4\":\n running = False \n else:\n pass\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T23:30:08.577", "Id": "12954", "Score": "0", "body": "Wow, thank you so much. I'm just learning about dictionaries (and their methods) and functions, so thanks for showing me these great ways to implement them. I will definitely comment my code from now on. One question though: why did you use the \"running\" variable to control the loop? Why not create an infinite loop with \"while True\" and end it with \"break\" when the user chooses \"4\"? Is it for readability? Thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T23:42:26.147", "Id": "12956", "Score": "0", "body": "@krushers In this particular scenario there's no difference between using \"while True\" and breaking, but a `break` would exit the loop immediately where as `running = False` would execute any code after the if statement. But the main reason is, as you say, `while running` and `running = False` is perhaps more readable. Nothing beats a good comment if you're worried something is ambiguous, though!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T23:49:18.873", "Id": "12957", "Score": "0", "body": "Might I just also re-iterate as a caveat that my code example is not by any means the best way to do this, I've tried to keep it simple so you can get a general \"idea\" of the kind of way to structure your program. One thing you might notice is that `my_character` is not passed as the argument to a function, when in a larger program this might not be such a good idea..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T10:11:29.057", "Id": "12975", "Score": "1", "body": "I think you have a small mistake in your code, where you wrote `(amount > my_character['points']) or (my_character['points'] <= 0)` I think you actually meant to write, `(amount > my_character['points']) or (amount <= 0)`, correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T13:32:44.527", "Id": "12979", "Score": "0", "body": "@JoãoPortela : Actually, I did intend to write that, but your version of the code is an improvement because it covers mine plus the case where amount is nonpositive. But like I say, I threw this together to demonstrate the overall structural improvement for the code, not as a complete solution." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T21:14:33.527", "Id": "8292", "ParentId": "8285", "Score": "8" } }, { "body": "<p>I'm also a beginner in programming. Here's how I would have done it. It's probably not any better than yours at all, but maybe slightly more readable. Good answer from persepolis btw!</p>\n\n<pre><code>points = int(30)\nattributes = {u'strength': 0, u'health': 0, u'wisdom': 0, u'dexerity': 0}\nfunctions = [u'add points', u'take points', u'see points', u'exit']\n\ndef add_points(): #Function that let the user add points to the attributes\n global points\n print u\"You have \" + unicode(points) + u\" points left\"\n choice = raw_input(u\"Which attribute? Strength, health, wisdom, or dexterity? \")\n print u\"\\n\"\n if choice in attributes: #If the user types a valid attribute\n add = int(raw_input(u\"How many points? \"))\n if add &lt;= points: #If there is enough points left\n attributes[choice] += add\n points -= add\n print choice + u': ' + unicode(attributes[choice])\n else:\n print u\"Invalid number of points\"\n else:\n print u\"Invalid attribute\"\n\ndef sub_point(): #Function that let the user add points to the attributes\n choice = raw_input(u\"Which attribute? Strength, health, wisdom, or dexterity? \")\n if choice in attributes: #If the user types a valid attribute\n sub = int(raw_input(u\"How many points? \"))\n if sub &gt;= attributes[choice]: #If there is enough points in that attribute\n attributes[choice] -= sub\n points += sub\n print choice + u': ' + unicode(attributes[choice])\n else:\n print u\"Invalid number of points\"\n else:\n print u\"Invalid attribute\"\n\ndef see_points(): #Function that let the user see the attributes and points\n for x in attributes:\n print x + u\": \" + unicode(attributes[x])\n\n# Main loop\n\nname = raw_input(u\"What is your characters name? \")\nprint u\"Hi \" + name\nwhile True:\n print u\"\\n\"\n print u\"Would you like to add points, take points, see points per attribute or exit?\"\n print u\"\\n\"\n for x in functions: #Prints out the user's choices\n print x + u': ' + u'press ' + unicode(functions.index(x) + 1)\n print u\"\\n\"\n func = int(raw_input())\n if func == 1:\n add_points()\n if func == 2:\n sub_points()\n if func == 3:\n see_points()\n if func == 4:\n break\nprint u\"Congratz, you have created a caracter!\"\n</code></pre>\n\n<p>I apologize for small faults in the function. I use 3.2 and converted it to 2.x</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T01:23:39.577", "Id": "12961", "Score": "0", "body": "Cool, thanks for your answer! I really like your use of functions; makes the final product much easier to understand. I have a few questions: Is there any reason you used \"int(30)\" to define \"points\"? I think you can just say \"points=30\" and Python would understand that it's an integer value. Also, why are there \"u\"s before all your strings? Lastly, what is the purpose of the \"global\" statement and the \"unicode()\" method? I looked them up online but couldn't really understand the point of using them in this context. Thanks again for your answer. I appreciate it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T05:28:21.453", "Id": "12965", "Score": "0", "body": "For some weird reason, python wouldn't accept it without the int(). I usally dont use it. the \"u\"'s is something that happens in the conversion from 3.x to 2.x. There is some differences in unicode/string and especially the print() function. The global thing should also not be neccesary, but something was wrong with python(or me) today." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-06T11:47:46.513", "Id": "13611", "Score": "0", "body": "@mart0903 `global points` would be required before modifying `points`, as `x += 1` expands to `x = x + 1`. If `x` is in the global scope, then at the start of that expression it defines a new local variable `x`, and then assigns it the value of the global variable `x` plus 1. This is because integars are immutable, and so you are not in fact modifying `points`, but changing what the name resolves to within your current scope. Using the `global` keyword explicitly tells python how to resolve `points`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T00:49:58.687", "Id": "8298", "ParentId": "8285", "Score": "3" } }, { "body": "<p>While the answer by persepolis is great for this small task, if this were for part of a game where you were going to use this data, you may wish to do something like this:</p>\n\n<pre><code>class Character(object):\n name = ''\n strength = 0\n health = 0\n wisdom = 0\n dexterity = 0\n points = 20\n _attributes = ['name', 'strength', 'health', 'wisdom', 'dexterity', 'points']\n def __init__(self, name):\n assert self.valid_name(name)\n self.name = name\n def add_points(self):\n accepted = ['strength', 'health', 'wisdom', 'dexterity']\n accepted_dict = dict(enumerate(accepted, start=1))\n prompt = \"\\nWhich attribute?\\n\\t\" + \"\\n\\t\".join(\"%d. %s\"%n for n in accepted_dict.items())+\"\\n?\"\n attribute = False\n while attribute not in accepted:\n attribute = raw_input(prompt)\n try:\n attribute = accepted_dict[int(attribute)]\n except:\n print \"Input was invalid. Please enter either an attribute or its corresponding number\"\n amount = None\n while type(amount) != int or amount &gt; self.points:\n try:\n amount = int(raw_input(\"By how much?\"))\n assert amount &lt;= self.points\n except AssertionError:\n print \"You do not have that many points remaining\"\n except:\n print \"You must enter an integer amount\"\n self.__setattr__(attribute, self.__getattribute__(attribute) + amount)\n self.points -= amount\n def __str__(self):\n return \"\\n\".join(\"%s\\t:\\t%s\"%(n, self.__getattribute__(n)) for n in self._attributes)\n @staticmethod\n def valid_name(name):\n if bool(name) and type(name) == str:\n return True\n else:\n return False\nif __name__ == \"__main__\":\n running = True\n print \"Create a character! You have points to assign to strength, health, wisdom, and dexterity.\"\n name = ''\n while not Character.valid_name(name):\n name = raw_input(\"Please enter your character's name:\")\n CHAR = Character(name)\n OPTIONS_LIST = [\"Add points\", \"Remove points\", \"See current attributes\", \"Exit\"]\n OPTIONS_DICT = dict(enumerate(OPTIONS_LIST, start=1))\n PROMPT = \"\\n\".join(\"\\t%d. %s\"%n for n in OPTIONS_DICT.items())+\"\\nChoice:\"\n while running:\n CHOICE = raw_input(PROMPT)\n try:\n CHOICE = int(CHOICE)\n except:\n pass\n if CHOICE in OPTIONS_DICT.keys():\n CHOICE = OPTIONS_DICT[CHOICE]\n if CHOICE == \"Add points\":\n CHAR.add_points()\n elif CHOICE == \"Remove points\":\n raise NotImplementedError()\n elif CHOICE == \"See current attributes\":\n print CHAR\n elif CHOICE == \"Exit\":\n running = False\n</code></pre>\n\n<p>As the character is now an object it can be passed around. Notice also how use of enumerate can give more intuitive menus - these will accept either the number, or the text. Using the text in your <code>if ... elif ... elif ... else</code> block also helps the clarity of the code. For instance while typing the above code out I put the NotImplementedError in the wrong bit - when I re-read the code it was obvious I had made a mistake. While this code is not perfect, it may give an idea of slightly better practices that will help you when you attack larger projects.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-06T13:22:21.187", "Id": "8698", "ParentId": "8285", "Score": "1" } } ]
{ "AcceptedAnswerId": "8292", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T17:49:38.840", "Id": "8285", "Score": "14", "Tags": [ "python", "beginner", "python-2.x", "role-playing-game" ], "Title": "Character creator for a role-playing game" }
8285
<p>I'm generating a table to use on jQuery visualize plugin and generate a chart. The code is pretty good, but maybe there is a way to improve it. Maybe do more work on the LINQ query and less stuff on the rest of the code.</p> <p>The idea is get every content and the launch date of them for each region. Separate all dates and the the amount of content launched that day. But maybe there is a better way. Anyone?</p> <p>Here is the method i use:</p> <pre><code> public KeyValuePair&lt;DateTime[], List&lt;KeyValuePair&lt;string, int[]&gt;&gt;&gt; TimeGrowth(int days, params string[] locales) { DateTime startdate = DateTime.Today.AddDays(days * (-1)); var qry = from r in GlobalVariables.Regions where locales.Contains(r.ID) select new { Region = r, Launches = (from d in r.RegionalContents where d.RegionId == r.ID &amp;&amp; d.PublishDate != null group d by d.PublishDate into groupeddates select new { Date = groupeddates.Key, Count = groupeddates.Count() }).OrderBy(x =&gt; x.Date) }; var regions = qry.ToArray(); var dates = new List&lt;DateTime&gt;(); var datesbeforestart = new List&lt;DateTime&gt;(); var countries = new List&lt;KeyValuePair&lt;string, int[]&gt;&gt;(); for (int i = 0; i &lt; regions.Length; i++) { for (int j = 0; j &lt; regions[i].Launches.Count(); j++) { var data = regions[i].Launches.ElementAt(j).Date.Value; if (data &gt; startdate) dates.Add(data); else datesbeforestart.Add(data); } } dates = dates.Distinct().OrderBy(x =&gt; x.Date).ToList(); for (int i = 0; i &lt; regions.Length; i++) { var values = new int[dates.Count]; values[0] = CountDateInterval(datesbeforestart.Min(), startdate, regions[i].Region.ID); int acum = values[0]; for (int j = 1; j &lt; dates.Count; j++) { int valor = 0; if (regions[i].Launches.Any(x =&gt; x.Date == dates[j])) valor = regions[i].Launches.Single(x =&gt; x.Date == dates[j]).Count; acum += valor; values[j] = acum; } var country = new KeyValuePair&lt;string, int[]&gt;(regions[i].Region.CountryEnglish, values); countries.Add(country); } countries = countries.OrderByDescending(x =&gt; x.Value.Max()).ToList(); var finalresult = new KeyValuePair&lt;DateTime[], List&lt;KeyValuePair&lt;string, int[]&gt;&gt;&gt;(dates.ToArray(), countries); return finalresult; } </code></pre> <p>You can see the actual running code here on the last chart: <a href="http://programad.net/xbltoolsv2beta/Stats" rel="nofollow">http://programad.net/xbltoolsv2beta/Stats</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T11:10:55.293", "Id": "13046", "Score": "1", "body": "I'd start by splitting the method into several smaller methods with descripting names. Makes the logic easier to follow, and hopefully also exposes possible refactorings, field candidates etc.\n\nContents of for loops are a prime candidate for methods of their own.\n\nYou can also extract lambda expressions to methods. (Tried JetBrains' Resharper?)" } ]
[ { "body": "<p>A few general points:</p>\n\n<p>(1) <code>GlobalVariables.Regions</code> -- I don't know how big your application is, but if I'm looking at a code base and I see some static class called \"GlobalVariables\" that usually makes me leery. In a pure object-oriented language, all data can (and arguably ought to be) associated with some object. A GlobalVariables class with a bunch of statics on it is the kind of thing that is likely to grow and rot with as the application grows (and rots).</p>\n\n<p>(2) As mentioned by Lars-Erik, I think that breaking some of that functionality out into other methods would be beneficial. Personally, I look at control statements, especially nested ones for opportunities to do that. Looking at your code, the logic inside <code>for (int i = 0; i &lt; regions.Length; i++)</code> would be a good candidate. Just by looking at the code casually, it's hard to tell what all is going on inside that loop. But if you pulled it out into a method and gave it a descriptive name, someone looking at your code could easily understand what the loop was doing.</p>\n\n<p>(3) You have a lot of code (as Linq tends to) with sequences of statements like <code>Foo.Bar().Baz().Rebar();</code> Generally speaking, if anything in those sequence chains returns null, you're going to get null reference exceptions. Perhaps clients of this method handle exceptions that it generates, but I can't see that you're handling anything but the \"happy path\" in this method. What happens if things go unexpectedly?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T18:09:39.223", "Id": "8368", "ParentId": "8286", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T18:34:29.763", "Id": "8286", "Score": "4", "Tags": [ "c#", "linq", "asp.net-mvc-3", "entity-framework" ], "Title": "LINQ generating chart" }
8286
<p>I wrote a method that gathers data from an Oracle server, formats and encrypts the data then inserts it into a MS SQL server. The method moves about 60000 records and takes a bit long and is a little sloppy. Can anyone see places to clean it up and make it faster?</p> <p>Two of the areas that I see might need improvements are when the result set is being added to the <code>List</code>. And when the <code>List</code> is being inserted 1000 rows at a time into the MS SQL table.</p> <p>Here is the code:</p> <pre><code>public static void get_random_selection(Connection ora_conn, Connection sql_conn) throws Exception, SQLException{ Statement sql_stmt = sql_conn.createStatement(); Statement ora_stmt = ora_conn.createStatement(); ResultSet sql_rs = null; ResultSet ora_rs = null; //Select the max QUARTER from RANDOM_SELECTION in MS SQL sql_rs = sql_stmt.executeQuery("SELECT MAX(QUARTER) FROM RANDOM_SELECTION"); sql_rs.next(); int max_from_mssql = sql_rs.getInt(1); ora_rs = ora_stmt.executeQuery("SELECT MAX(QUARTER) FROM RANDOM_SELECTION"); ora_rs.next(); int max_from_oracle = ora_rs.getInt(1); //If the max_from_oracle is larger than max_from_mssql than the AL's and RL's in Oracle //are fresher and need to be moved to MS SQL //if (max_from_oracle &gt; max_from_mssql){ if(1==1){ System.out.println("The RANDOM_SELECTION table in Oracle is more up to date than the RANDOM_SELECTION table in MS SQL."); System.out.println("Retrieving RANDOM_SELECTION data from Oracle."); //select items from RANDOM_SELECTION and DROPPER_CITY_BRK_2 that need to be moved ora_rs = ora_stmt.executeQuery("select distinct(random_selection.randnum), " + "random_selection.quarter, " + "random_selection.ozip3, " + "random_selection.boxid, " + "random_selection.boxaddr, " + "random_selection.locdesc, " + "random_selection.loccity, " + "random_selection.lastmf, " + "random_selection.lastsat, " + "random_selection.boxtype, " + "random_selection.svcclas, " + "random_selection.dropzip5, " + "random_selection.dropper_id " + "from random_selection " + "where random_selection.dropper_id is not null " + "and random_selection.quarter = " + max_from_oracle + " " + "union " + "select distinct(random_selection.randnum), " + "random_selection.quarter, " + "random_selection.ozip3, " + "random_selection.boxid, " + "random_selection.boxaddr, " + "random_selection.locdesc, " + "random_selection.loccity, " + "random_selection.lastmf, " + "random_selection.lastsat, " + "random_selection.boxtype, " + "random_selection.svcclas, " + "random_selection.dropzip5, " + "dropper_city_brk_2.dropper_id " + "from random_selection, dropper_city_brk_2, dropper " + "where random_selection.ozip3 = dropper_city_brk_2.zip3 " + "and dropper.dropper_id = dropper_city_brk_2.dropper_id " + "and dropper.active = 1 " + "and dropper_city_brk_2.dropper_id &lt;&gt; 10002 " + "and random_selection.quarter = " + max_from_oracle + " " + "and random_selection.dropper_id is null"); System.out.println("Retrieved RANDOM_SELECTION data from Oracle."); List&lt;String[]&gt; random_selection = new ArrayList&lt;String[]&gt;(); System.out.println("Assigning ResultSet to List."); while (ora_rs.next()){ random_selection.add(new String[]{ ora_rs.getString("RANDNUM"), ora_rs.getString("QUARTER"), ora_rs.getString("OZIP3"), ora_rs.getString("BOXID"), ora_rs.getString("BOXADDR").replace("'"," "), ora_rs.getString("LOCDESC") == null ? ora_rs.getString("LOCDESC") : ora_rs.getString("LOCDESC").replace("'",""), ora_rs.getString("LOCCITY").replace("'", " "), ora_rs.getString("LASTMF"), ora_rs.getString("LASTSAT").equals("11:58pm") ? "null": ora_rs.getString("LASTSAT"), ora_rs.getString("BOXTYPE"), ora_rs.getString("SVCCLAS"), ora_rs.getString("DROPZIP5"), ora_rs.getString("DROPPER_ID")}); System.out.println(ora_rs.getRow()); } System.out.println("Finished assigning ResultSet to List."); //leading statement for the following loop String query = "insert into random_selection " + "(RANDNUM,QUARTER,OZIP3,BOXID,BOXADDR,LOCDESC,LOCCITY,LASTMF,LASTSAT,BOXTYPE,SVCCLAS,DROPZIP5,DROPPER_ID) VALUES"; int jj = 0; //loop through random_selection_array creating an INSERT statement to insert 999 entries at a time //this is done to speed up the process for(int ii = 0;ii&lt;random_selection.size();ii++){ String[] array_holder = random_selection.get(ii); query = query + "(" + "'"+array_holder[0]+"'," + "'"+array_holder[1]+"'," + "'"+array_holder[2]+"'," + "'"+array_holder[3]+"'," + "'"+array_holder[4]+"'," + "'"+array_holder[5]+"'," + "'"+array_holder[6]+"'," + "'"+array_holder[7]+"'," + "'"+array_holder[8]+"'," + "'"+array_holder[9]+"'," + "'"+array_holder[10]+"'," + "'"+array_holder[11]+"'," + "'"+new sun.misc.BASE64Encoder().encode(encrypt(array_holder[12]))+"'),"; //every 999 iterations enter here if (jj &gt; 998){ //add |%| to the end of the string so that you can remove the final ',' query = query+"|%|"; query = query.replace(",|%|",""); System.out.println(query); //sql_stmt.executeUpdate(query); query = "insert into random_selection (RANDNUM,QUARTER,OZIP3,BOXID,BOXADDR,LOCDESC,LOCCITY,LASTMF,LASTSAT,BOXTYPE,SVCCLAS,DROPZIP5,DROPPER_ID) VALUES"; jj = 0; } jj++; //the last few entries will be added one at a time to prevent nulls records from being inserted if (ii &gt; (random_selection.size() / 999) * 999){ //add |%| to the end of the string so that you can remove the final ',' query = query+"|%|"; query = query.replace(",|%|",""); System.out.println(query); //sql_stmt.executeUpdate(query); query = "insert into random_selection (RANDNUM,QUARTER,OZIP3,BOXID,BOXADDR,LOCDESC,LOCCITY,LASTMF,LASTSAT,BOXTYPE,SVCCLAS,DROPZIP5,DROPPER_ID) VALUES"; } } } } </code></pre> <p>The client wants to refrain from any open connections between the two servers.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:18:44.747", "Id": "13007", "Score": "0", "body": "Or try this http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=16742 and pray it works like they say it does." } ]
[ { "body": "<p>First of all, profile the code to find the bottleneck. </p>\n\n<p>Some other idea:</p>\n\n<ul>\n<li>Use threads. One thread retrieves the data from Oracle and one or more threads upload it to MSSQL.</li>\n<li>Use <a href=\"https://stackoverflow.com/questions/2099425/when-we-use-preparedstatement-instead-of-statement\">PreparedStatement</a>s for inserting data.</li>\n<li>Disable indexes in MSSQL during the migration.</li>\n</ul>\n\n<p>Some generic notes:</p>\n\n<ol>\n<li><p>It's unnecessary to assign <code>null</code> to variables:</p>\n\n<pre><code>ResultSet sql_rs = null;\n...\nsql_rs = sql_stmt.executeQuery(\"SELECT MAX(QUARTER) FROM RANDOM_SELECTION\");\n</code></pre>\n\n<p>You could simply write this:</p>\n\n<pre><code>...\nResultSet sql_rs = sql_stmt.executeQuery(\"SELECT MAX(QUARTER) FROM RANDOM_SELECTION\");\n</code></pre></li>\n<li><p>Instead of the <code>String[]</code> array (whose indexes are <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants\" rel=\"nofollow noreferrer\">magic numbers</a>) I'd use a data object with named fields.</p>\n\n<pre><code>public class RandomSelection {\n private String randNum;\n private String quater;\n ...\n\n}\n</code></pre></li>\n<li><p>Use the <a href=\"http://www.oracle.com/technetwork/java/codeconv-138413.html\" rel=\"nofollow noreferrer\">Code Conventions for the Java Programming Language</a>.</p>\n\n<ul>\n<li><code>get_random_selection</code> should be <code>getRandomSelection</code>,</li>\n<li><code>ora_stmt</code> should be <code>oracleStatement</code>,</li>\n<li>etc.</li>\n</ul></li>\n<li><p>Split the method at least to two smaller one: one should handle retrieving and another one should create the <code>insert</code> statements.</p></li>\n<li><p>Keep it <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>, repeated codes should be moved to a new method.</p>\n\n<pre><code>query = query+\"|%|\";\nquery = query.replace(\",|%|\",\"\");\n\nSystem.out.println(query);\n\n//sql_stmt.executeUpdate(query);\nquery = \"insert into random_selection (RANDNUM,QUARTER,OZIP3,BOXID,BOXADDR,LOCDESC,LOCCITY,LASTMF,LASTSAT,BOXTYPE,SVCCLAS,DROPZIP5,DROPPER_ID) VALUES\";\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T11:35:24.530", "Id": "8318", "ParentId": "8290", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T19:58:36.690", "Id": "8290", "Score": "3", "Tags": [ "java", "sql-server", "oracle" ], "Title": "Oracle to MSSQL data migration is slow on INSERT" }
8290
<p>The model looks like this, with <em>no attributes</em>:</p> <pre><code>public class PersonalModel : Validatable { public string Name { get; set; } public string Email { get; set; } public override void Validate(dynamic item) { if (this.ValidatesPresenceOf(item.Name, "Name is required")) { if (((String)item.Name).Length &gt; 5) { Errors.Add("name is too long less than 5 chars please!"); } } } } </code></pre> <p>and the action looks like this:</p> <pre><code> [HttpPost] [ValidateAntiForgeryToken] public ActionResult PersonalInfo(PersonalModel model) { if (model.IsValid(model)) { this.FlashInfo("Your Personal info was successfully received"); return RedirectToAction("ThankYou"); } else { ModelState.AddModelError(string.Empty, String.Join("; ", model.Errors.ToArray())) ; return View(model); } } </code></pre> <p>This is the baseclass <code>Validatable</code>:</p> <pre><code>public class Validatable : DynamicObject { //Hooks public virtual void Validate(dynamic item) { } //Temporary holder for error messages public IList&lt;string&gt; Errors = new List&lt;string&gt;(); public bool IsValid(dynamic item) { Errors.Clear(); Validate(item); return Errors.Count == 0; } //validation methods public virtual bool ValidatesPresenceOf(object value, string message = "Required") { if (value == null || String.IsNullOrEmpty(value.ToString())) { Errors.Add(message); return false; } return true; } } </code></pre>
[]
[ { "body": "<p>I wholeheartedly agree that the attributes are evil.\nBut in my opinion having to derive from a base class is just as bad as having to add attributes. Both makes you depend on framework infrastructure you don't need to depend on. (Models should be model logic, and model logic only.)</p>\n\n<p>In MVC (3 at least) you can implement a <code>ModelValidatorProvider</code> and a <code>ModelMetadataProvider</code>. The validator provider can be added in <code>Application_Start</code> using <code>ModelValidatorProviders.Providers.Add(...)</code>, and the metdata provider can be injected using the standard IoC container.</p>\n\n<p>The guys who wrote <a href=\"http://rads.stackoverflow.com/amzn/click/1118076583\">Professional ASP.NET MVC 3</a> also created fluent implementations of those, so you can have configuration like this:</p>\n\n<pre><code>validationProvider.ForModel&lt;PersonModel&gt;()\n .ForProperty(p =&gt; p.Name).Required()\n .ForProperty(p =&gt; p.Email).Required().Email();\n</code></pre>\n\n<p>This will also be picked up by the unobtrusive validation jQuery plugin, and everything else in MVC that would've used the attributes for.</p>\n\n<p>As a sidenote, since you also derive from <code>DynamicObject</code> in your base class, the compiler won't complain if someone inadvertedly attempts to set <code>person.name</code> instead of <code>person.Name</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T15:35:25.047", "Id": "12990", "Score": "0", "body": "Looking at this again I agree with your thoughts 'having to derive from a base class is just as bad as having to add attributes' Thanks Lars-Erik" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T09:44:27.837", "Id": "8315", "ParentId": "8293", "Score": "8" } } ]
{ "AcceptedAnswerId": "8315", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T22:11:18.660", "Id": "8293", "Score": "4", "Tags": [ "c#", "asp.net-mvc-3" ], "Title": "ASP.NET MVC models that can be validated without using attributes" }
8293
<p>Goal: Create a simple battleship game to test what I've learned so far.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; void buff_clr(void) { char junk; do{ junk=getchar(); }while(junk!='\n'); } struct coord { int y; int x; }coords; int randgen(int **ships_ptr,int n) { int i,j,count=0; srand((unsigned)time(NULL)); for(i=0;i&lt;n;i++) { for(j=0;j&lt;n;j++) { ships_ptr[i][j]=rand()%2; if(ships_ptr[i][j]==1) { count++; } } } return count; } void draw_gui(char **pseudo_gui_ptr,int n) { int i,j; pseudo_gui_ptr[0][0]=' '; for(i=1;i&lt;(n+1);i++) { pseudo_gui_ptr[0][i]=i+48; pseudo_gui_ptr[i][0]=i+48; } for(i=1;i&lt;(n+1);i++) { for(j=1;j&lt;(n+1);j++) { pseudo_gui_ptr[i][j]='+'; } } } void battle(int **ships_ptr, char **pseudo_gui_ptr,int n, struct coord x,int* count,int* miss) { int i,j; for(i=0;i&lt;n;i++) { for(j=0;j&lt;n;j++) { if(x.x-1 == i &amp;&amp; x.y-1 == j) { if(ships_ptr[i][j]==1) { if(pseudo_gui_ptr[i+1][j+1]=='O') { printf("\nYou've already uncovered this field!\n"); break; } printf("\nHit!\n"); pseudo_gui_ptr[i+1][j+1]='O'; (*count)--; } else { if(pseudo_gui_ptr[i+1][j+1]=='X') { printf("\nYou've already uncovered this field!\n\n"); break; } printf("\nMiss!\n"); pseudo_gui_ptr[i+1][j+1]='X'; (*miss)++; } } } } } void result(char **pseudo_gui_ptr,int n) { int i,j; for(i=0;i&lt;(n+1);i++) { for(j=0;j&lt;(n+1);j++) { printf("%6c",pseudo_gui_ptr[i][j]); } printf("\n\n"); } } int main(){ int **ships; char **pseudo_gui; int i,j; int n; char switch_size,switch_difficulty; int difficulty=0; int shipcount=0; int x_count=0; printf("\t\t\tSink the ships v0.1b"); printf("\nChoose size(S,M,L):"); scanf("%c",&amp;switch_size); buff_clr(); switch(switch_size) { case 's': case 'S':n=3;break; case 'm': case 'M':n=5;break; case 'l': case 'L':n=8;break; default:printf("\nYou've choosen poorly!"); getch(); exit(EXIT_FAILURE); } printf("\nChoose difficulty(E,H):"); scanf("%c",&amp;switch_difficulty); buff_clr(); switch(switch_difficulty) { case 'e': case 'E':difficulty=(n*2)-2;break; case 'h': case 'H':difficulty=(n/2);break; default:printf("\nYou've choosen poorly!"); getch(); exit(EXIT_FAILURE); } ships=(int**)malloc(n*sizeof(int*)); for(i=0;i&lt;n;i++) { ships[i]=(int*)malloc(n*sizeof(int)); } pseudo_gui=(char**)malloc((n+1)*sizeof(char*)); for(i=0;i&lt;(n+1);i++) { pseudo_gui[i]=(char*)malloc((n+1)*sizeof(char)); } shipcount=randgen(ships,n); printf("\n\nNumber of ships to be sunk:%d",shipcount); printf("\nNumber of misses allowed: %d\n\n",difficulty); draw_gui(pseudo_gui,n); result(pseudo_gui,n); while(shipcount!=0 &amp;&amp; x_count!=difficulty) { printf("\nEnter coordinates (x,y):"); scanf("%d,%d",&amp;coords.x,&amp;coords.y); buff_clr(); system("cls"); battle(ships,pseudo_gui,n,coords,&amp;shipcount,&amp;x_count); result(pseudo_gui,n); printf("Number of ships to be sunk:%d",shipcount); printf("\nNumber of misses(out of %d): %d\n\n",difficulty,x_count); } if(shipcount==0) { printf("\nWinner!\n\n"); getch(); } else if(x_count==difficulty) { printf("\nYou Lose!\n\n"); getch(); } return 0; } </code></pre> <p>This what I've made so far but i'm in doubt if my code is: </p> <ol> <li>Easy to understand </li> <li>Straightforward </li> <li>Could have I done anything in a different, easier, or more convenient way?</li> </ol> <p>Also, what would be the most optimal way of solving wrong input when it comes to size and difficulty? I first made the default in switch request the input again, but the problem is that it only requests twice (once for the initial request and 2nd time in the default). I've tried to add a do-while function for <code>scanf</code>s, but it seems I can't have more than one condition (I tried adding multiple checks if input is != to the letter).</p> <p>Also, could you help me pitch some ideas how I could add longer ships which would span over 2 tiles since I'm using a random generator? I know I can check for 1's and then add code to put a 1 in (i+n) which would make a vertical ship spanning 2 tiles and for horizontal (i+1, i-1), but I would need some checks (I'm thinking of adding a few <code>if</code>s to check if I'm on n tile) to see if the 1 is by the 'edge'. However, would that work and is it the most efficient method? If not, give me an idea. </p>
[]
[ { "body": "<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n\nvoid buff_clr(void)\n{\n char junk;\n do{\n junk=getchar();\n }while(junk!='\\n');\n}\n\nstruct coord\n{\n int y;\n int x;\n\n}coords;\n\nint randgen(int **ships_ptr,int n)\n</code></pre>\n\n<p><code>randgen</code> tells me that I'm doing some random generation. I'd include something about map in the title.</p>\n\n<pre><code>{\n int i,j,count=0;\n srand((unsigned)time(NULL));\n</code></pre>\n\n<p>I wouldn't put this here. You should call this once per program, and you might generate multiple maps per program.</p>\n\n<pre><code> for(i=0;i&lt;n;i++)\n {\n for(j=0;j&lt;n;j++)\n {\n ships_ptr[i][j]=rand()%2;\n if(ships_ptr[i][j]==1)\n {\n count++;\n }\n }\n }\n return count;\n}\nvoid draw_gui(char **pseudo_gui_ptr,int n)\n{\n int i,j;\n\n pseudo_gui_ptr[0][0]=' ';\n for(i=1;i&lt;(n+1);i++)\n {\n pseudo_gui_ptr[0][i]=i+48;\n pseudo_gui_ptr[i][0]=i+48;\n</code></pre>\n\n<p>Use '0' instead of 48 to make it clearer what you are doing</p>\n\n<pre><code> }\n\n for(i=1;i&lt;(n+1);i++)\n</code></pre>\n\n<p>You don't need the parens around <code>(n+1)</code></p>\n\n<pre><code> {\n for(j=1;j&lt;(n+1);j++)\n {\n pseudo_gui_ptr[i][j]='+';\n }\n }\n}\nvoid battle(int **ships_ptr, char **pseudo_gui_ptr,int n, struct coord x,int* count,int* miss)\n</code></pre>\n\n<p>That's getting to be a rather lot of parameters. I'd put everything inside a Game or Map struct. That way you just pass one pointer, and the everything else comes as part of that.</p>\n\n<pre><code>{\n\n int i,j;\n\n for(i=0;i&lt;n;i++)\n {\n for(j=0;j&lt;n;j++)\n {\n if(x.x-1 == i &amp;&amp; x.y-1 == j)\n {\n</code></pre>\n\n<p>What are you doing? You don't want to do anything multiple times, so you shouldn't be using a loop. You know exactly what i and j will be so just calculate those values.</p>\n\n<pre><code> if(ships_ptr[i][j]==1)\n {\n if(pseudo_gui_ptr[i+1][j+1]=='O')\n</code></pre>\n\n<p>Reading back the GUI is generally not helpful. What if the GUI changes? Instead, I'd have a struct Tile to hold the map. Inside would be a ship and uncovered booleans. That would make things a bit simpler</p>\n\n<pre><code> {\n printf(\"\\nYou've already uncovered this field!\\n\");\n break;\n }\n printf(\"\\nHit!\\n\");\n pseudo_gui_ptr[i+1][j+1]='O';\n (*count)--;\n }\n else\n {\n if(pseudo_gui_ptr[i+1][j+1]=='X')\n {\n printf(\"\\nYou've already uncovered this field!\\n\\n\");\n break;\n }\n printf(\"\\nMiss!\\n\");\n pseudo_gui_ptr[i+1][j+1]='X';\n (*miss)++;\n }\n\n }\n }\n }\n\n\n}\nvoid result(char **pseudo_gui_ptr,int n)\n{\n int i,j;\n\n for(i=0;i&lt;(n+1);i++)\n {\n for(j=0;j&lt;(n+1);j++)\n {\n printf(\"%6c\",pseudo_gui_ptr[i][j]);\n }\n printf(\"\\n\\n\");\n }\n</code></pre>\n\n<p>I'd get rid of pseudo_gui_ptr and regenerate the output each time based on the Tile data.</p>\n\n<pre><code>}\nint main(){\n\n int **ships;\n char **pseudo_gui;\n int i,j;\n int n;\n char switch_size,switch_difficulty;\n int difficulty=0;\n int shipcount=0;\n int x_count=0;\n\n\n printf(\"\\t\\t\\tSink the ships v0.1b\");\n\n printf(\"\\nChoose size(S,M,L):\");\n scanf(\"%c\",&amp;switch_size);\n</code></pre>\n\n<p>switch_size? Name it after what it means, not the control structure you are going to hand it to.</p>\n\n<pre><code> buff_clr();\n\n switch(switch_size)\n {\n case 's':\n case 'S':n=3;break;\n case 'm':\n case 'M':n=5;break;\n case 'l':\n case 'L':n=8;break;\n default:printf(\"\\nYou've choosen poorly!\");\n</code></pre>\n\n<p>:P</p>\n\n<pre><code> getch();\n exit(EXIT_FAILURE);\n }\n\n printf(\"\\nChoose difficulty(E,H):\");\n scanf(\"%c\",&amp;switch_difficulty);\n buff_clr();\n\n switch(switch_difficulty)\n {\n case 'e':\n case 'E':difficulty=(n*2)-2;break;\n case 'h':\n case 'H':difficulty=(n/2);break;\n default:printf(\"\\nYou've choosen poorly!\");\n getch();\n exit(EXIT_FAILURE);\n }\n\n ships=(int**)malloc(n*sizeof(int*));\n\n for(i=0;i&lt;n;i++)\n {\n ships[i]=(int*)malloc(n*sizeof(int));\n }\n\n pseudo_gui=(char**)malloc((n+1)*sizeof(char*));\n\n for(i=0;i&lt;(n+1);i++)\n {\n pseudo_gui[i]=(char*)malloc((n+1)*sizeof(char));\n }\n\n shipcount=randgen(ships,n);\n\n printf(\"\\n\\nNumber of ships to be sunk:%d\",shipcount);\n printf(\"\\nNumber of misses allowed: %d\\n\\n\",difficulty);\n\n draw_gui(pseudo_gui,n);\n result(pseudo_gui,n);\n\n while(shipcount!=0 &amp;&amp; x_count!=difficulty)\n {\n\n printf(\"\\nEnter coordinates (x,y):\");\n scanf(\"%d,%d\",&amp;coords.x,&amp;coords.y);\n buff_clr();\n</code></pre>\n\n<p>Make you indent consistently!</p>\n\n<pre><code> system(\"cls\");\n\n battle(ships,pseudo_gui,n,coords,&amp;shipcount,&amp;x_count);\n result(pseudo_gui,n);\n\n printf(\"Number of ships to be sunk:%d\",shipcount);\n printf(\"\\nNumber of misses(out of %d): %d\\n\\n\",difficulty,x_count);\n\n }\n if(shipcount==0)\n {\n printf(\"\\nWinner!\\n\\n\");\n getch();\n }\n else if(x_count==difficulty)\n {\n printf(\"\\nYou Lose!\\n\\n\");\n getch();\n }\n\n\n return 0;\n}\n</code></pre>\n\n<p>Overall pretty good. The only really crazy thing is the for-for-if. </p>\n\n<blockquote>\n <p>Also what would be the most optimal way of solving wrong input when it comes to size and difficulty? I first made the default in\n switch request the input again but the problem is that it only\n requests twice(once for the initial request and 2nd time in the\n default) so tried to add a do-while function for scanfs but it seems i\n can't have more than one condition(i tried adding multiple checks if\n input is != to the letter).</p>\n</blockquote>\n\n<p>Some sort of while loop is the way to go. I'm not sure exactly where you had trouble. You may want to consider asking that as a question on Stackoverflow.</p>\n\n<blockquote>\n <p>Also could you help me pitch some ideas how i could add longer ships which would span over 2 tiles since i'm using a random\n generator. I know i can check for 1's and then add a code to put a 1\n in (i+n) which would make a vertical ship spanning 2 tiles and for\n horizontal(i+1, i-1) but i would need some checks(i'm thinking of\n adding a few if's to check if i'm on n tile) to see if the 1 is by the\n 'edge'. However would that work and is it the most efficient method?\n If not give me an idea.</p>\n</blockquote>\n\n<p>I'd suggest you add a function like:</p>\n\n<pre><code>int is_occupied(Map * map, int i, int j)\n{\n if(i &lt; 0 || j &lt; 0 || i &gt; map-&gt;n || j &gt; map-&gt;n)\n return true;\n return map.tiles[i][j].ship;\n}\n</code></pre>\n\n<p>Then only place ships where is_occupied() returns false. It'll return true if there is already a ship there, or if the tile goes off the edge of the map.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Here is what I'm thinking you could do with tile:</p>\n\n<pre><code>struct tile\n{\n int ship;\n int uncovered;\n};\n\nstruct game\n{\n struct tile **tiles;\n char **pseudo_gui;\n int shipcount;\n int x_count;\n};\n\nvoid map_gen(struct game *data,int n)\n{\n int i,j;\n for(i=0;i&lt;n;i++)\n {\n for(j=0;j&lt;n;j++)\n {\n data-&gt;tiles[i][j].ship =rand()%2;\n data-&gt;tiles[i][j].uncovered = 0;\n if(data-&gt;ships[i][j]==1)\n {\n data-&gt;shipcount++;\n }\n }\n }\n}\nvoid battle(struct game *data, struct coord x)\n{\n\n int i,j;\n\n Tile * tile = &amp;tiles[x.x-1][x.y-1];\n if(tile-&gt;uncovered)\n {\n printf(\"\\nYou've already uncovered this field!\\n\");\n }\n else\n {\n if(tile-&gt;ship)\n {\n printf(\"\\nHit!\\n\");\n data-&gt;pseudo_gui[x.x][x.y]='O';\n data-&gt;shipcount--;\n }\n else\n {\n printf(\"\\nMiss!\\n\");\n data-&gt;pseudo_gui[x.x][x.y]='X';\n data-&gt;x_count++;\n }\n }\n}\n</code></pre>\n\n<p>Other comments on update:</p>\n\n<ol>\n<li>I'd make a create_game function to setup the fields in game rather then doing it main</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T22:26:42.897", "Id": "13029", "Score": "1", "body": "Reading back the GUI is generally not helpful. What if the GUI changes? Instead, I'd have a struct Tile to hold the map. Inside would be a ship and uncovered booleans. That would make things a bit simpler.\n\nI'm afraid i don't quite get that. Create a Tile struct which would hold a ship and uncovered booleans? So basically i should create a struct out of my generated hidden field? I'm kind of confused. I did change some of the things though, i'll update the main code soon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T22:55:58.467", "Id": "13030", "Score": "1", "body": "Whoops i butchered that comment. Anyway i updated the main post and tell me if i did anything wrong? I'm still a newbie with structs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T23:01:37.943", "Id": "13031", "Score": "0", "body": "@MrPlow, I've added an edit that will hopefully help" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T14:47:16.750", "Id": "13051", "Score": "0", "body": "a little question. What exactly is \n`Tile * tile = &tiles[x.x-1][x.y-1];`\n\nTo me it looks like a pointer to struct tiles, however the `Tile` confuses me. Where did that come from? I didn't see any typedef on tile struct so i'm kind of confused. I'm still new to structs so i hope i'm not too much of a bother" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T14:59:28.667", "Id": "13052", "Score": "1", "body": "@MrPlow, I inadvertently switched into C++ writing that. It should be `struct Tile`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T15:44:13.753", "Id": "13055", "Score": "0", "body": "I'm sorry i'm just confused.\n\nI tried doing what you've told me but i ran into some problems.\n`game_data.tiles=(int**)malloc(n*sizeof(int*));` - `assignment from incompatible pointer type` and i tried adding `struct Tile *tile = &tiles[x.x-1][x.y-1]` in multiple variants such as `struct tiles *tile=&tiles[x.x-1][x.y-1]` which seems the most sensible to me. Here is my current non-working code [Pastebin](http://pastebin.com/myLpkcY1) . I really like your idea so i guess it's time for me to try to learn structs" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T15:59:39.957", "Id": "13058", "Score": "0", "body": "@MrPlow, you need to change the references to `int` in your malloc call to `struct tile`. `Tile` should be `tile`, I usually capitalize my struct names so I slipped back into that. And structs are very important, learn them. In fact, I recall reading that the first attempt to implement Unix in C failed because the version of C they were using didn't have structs yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T16:54:17.353", "Id": "13060", "Score": "0", "body": "Of course, i love programming and learning new things. I thank you for your patience, if everything goes well i'll update my code soon for your review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T19:15:54.277", "Id": "13078", "Score": "0", "body": "Ok i think i've wrote everything as you suggested but `uncovered` does nothing. On a further note i've become a bit more confused now with the whole thing. Do i now have an array of structures consisting of `ship` and `uncovered` ? how do they come into play? As far as i can see `ship` is an array of `n` elements filled with random generated booleans while `uncovered` is a an array of `n` elements filled with 0's. I don't know the purpose of uncovered here since there is nothing to change it's value. Also how exactly does that struct now work as an array(not an exact array but a pointer)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T19:33:29.180", "Id": "13079", "Score": "0", "body": "i edited the code in the main post. Everything works now i think. Tell me is this ok and if it's not what should i change?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T19:57:26.470", "Id": "13082", "Score": "0", "body": "@MrPlow, it looks pretty good. I'd fix the inconsistent indentation in `battle`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T12:27:51.847", "Id": "13174", "Score": "0", "body": "i added destroyer ships to medium and large maps, though i have to tweak and/or possibly remake the code. Anything i could improve?" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T00:54:40.150", "Id": "8299", "ParentId": "8294", "Score": "11" } } ]
{ "AcceptedAnswerId": "8299", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T22:49:33.277", "Id": "8294", "Score": "13", "Tags": [ "c", "game" ], "Title": "Battleship game in C" }
8294
ActionScript is an object-oriented scripting language used for RIAs, mobile applications, web applications, etc. ActionScript was initially developed by Macromedia and then acquired by Adobe. It targets to compile for Flash Player runtime which can be deployed in various platforms, including mobile platforms.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T23:16:53.793", "Id": "8296", "Score": "0", "Tags": null, "Title": null }
8296
<p>I was wondering if it's normal/efficient to have this many static collections in my state based game? I started doing it for ease of access but it looks sloppy to me and I was just wondering what conventions other people use to maintain references to game objects?</p> <pre><code>public class DungeonDigger extends StateBasedGame { public static NetworkPlayer myCharacter; public static Server SERVER = new Server(); public static Client CLIENT = new Client(); public static int CHOSEN_GAME_STATE; public static final int MAINMENU = 0; public static final int LOBBY = 3; public static final int SINGLEPLAYERDUNGEON = 1; public static final int MULTIPLAYERDUNGEON = 2; public static String ACCOUNT_NAME; public static String IP_CONNECT; public static int MAX_MESSAGE_LENGTH = 50; public static ConnectionState STATE; public static HashMap&lt;String, Image&gt; IMAGES = new HashMap&lt;String, Image&gt;(); public static ArrayList&lt;TextPacket&gt; TEXTS = new ArrayList&lt;TextPacket&gt;(); public static LinkedList&lt;ChatPacket&gt; CHATS = new LinkedList&lt;ChatPacket&gt;(); public static HashMap&lt;String, NetworkPlayer&gt; CHARACTERBANK = new HashMap&lt;String, NetworkPlayer&gt;(); public static HashSet&lt;String&gt; ACTIVESESSIONNAMES = new HashSet&lt;String&gt;(); public static HashMap&lt;Integer, String&gt; KEY_BINDINGS = new HashMap&lt;Integer, String&gt;(); public static HashMap&lt;String, String&gt; SLOT_BINDINGS = new HashMap&lt;String, String&gt;(); public static HashMap&lt;String, Ability&gt; ABILITY_TEMPLATES = new HashMap&lt;String, Ability&gt;(); public static HashMap&lt;String, Mob&gt; MOB_TEMPLATES = new HashMap&lt;String, Mob&gt;(); public static Vector&lt;Ability&gt; ACTIVE_ABILITIES = new Vector&lt;&gt;(); public static AbilityFactory ABILITY_FACTORY = new AbilityFactory(); public static MobFactory MOB_FACTORY = new MobFactory(); public DungeonDigger(String title) { super(title); } // Start game public static void main(String[] args) { try { System.setProperty("org.lwjgl.librarypath", new File(System.getProperty("user.dir"), "natives").getAbsolutePath()); System.setProperty("net.java.games.input.librarypath", System.getProperty("org.lwjgl.librarypath")); AppGameContainer app = new AppGameContainer(new DungeonDigger("Dungeon Digger")); app.setDisplayMode(640, 640, false); app.setTargetFrameRate(40); app.setUpdateOnlyWhenVisible(false); app.setAlwaysRender(true); app.start(); } catch (SlickException e) { e.printStackTrace(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T13:43:06.070", "Id": "12980", "Score": "0", "body": "[Single responsibility principle](http://en.wikipedia.org/wiki/Single_responsibility_principle)" } ]
[ { "body": "<p>Overall, separate your code, make it modular. Store state where it needs to be stored, but keep it separate, and expose the minimum amount of functionality that you have to.</p>\n\n<p>I would highly recommend that you read the book Effective Java, and then read it again. Feedback below, separate thoughts separated by . . .</p>\n\n<p>. . .</p>\n\n<p>First, don't use ints for storing flags, use enums.</p>\n\n<pre><code>public static int CHOSEN_GAME_STATE;\npublic static final int MAINMENU = 0;\npublic static final int LOBBY = 3;\npublic static final int SINGLEPLAYERDUNGEON = 1;\npublic static final int MULTIPLAYERDUNGEON = 2;\n</code></pre>\n\n<p>What does <code>(MAINMENU - LOBBY * SINGLEPLAYERDUNGEON / MULTIPLAYERDUNGEON)</code> mean? It's nonsense, but it's a valid expression in your API.</p>\n\n<p>Instead, it would be much better annotated as:</p>\n\n<pre><code>enum GameState {\n MAIN_MENU, LOBBY, SINGLEPLAYER_DUNGEON, MULTIPLAYER_DUNGEON\n}\nprivate static GameState sCurrentGameState = GameState.MAIN_MENU;\n</code></pre>\n\n<p>. . .</p>\n\n<p>With</p>\n\n<pre><code>public static HashMap&lt;String, Image&gt; IMAGES = new HashMap&lt;String, Image&gt;();\n</code></pre>\n\n<p>You have no control over who modifies your images. Instead I'd make your images stored and loaded via their own structure, something like:</p>\n\n<pre><code>class ImageCache {\n private HashMap&lt;String, Image&gt; mImages = new HashMap&lt;String, Image&gt;();\n\n public Image getImage(String imageName) {\n Image result = mImages.get(imageName); //returns null if image not present.\n if (result == null) {\n result = Image.loadFromFile(imageName);\n mImages.put(imageName, result);\n }\n return result;\n }\n\n public boolean imageCached(String imageName) {\n return sImages.contains(imageName);\n }\n}\n</code></pre>\n\n<p>This will give you a lot of things. First, let's say that you have too many images to store in memory, now you can easily implement an LRU cache or something to load on demand. And better yet, so long as <code>getImage</code> and <code>imageCached</code> work as they did before, this will all be hidden from the people using the <code>ImageCache</code>.</p>\n\n<p>. . .</p>\n\n<p>Instead of instantiating factories, I would recommend that you use static factories. So instead of (assuming <code>MobFactory</code> returns <code>Mob</code> objects):</p>\n\n<pre><code>public static MobFactory MOB_FACTORY = new MobFactory();\n</code></pre>\n\n<p>You would have something like:</p>\n\n<pre><code>class Mob {\n //Private ctor means that nobody can instantiate this directly.\n private Mob(String name, int hp, int mp) { ... }\n\n //Create the Ability, give it to the entity\n public static Mob create(String name, int hp, int mp) {\n assert hp &gt; 0 : \"Tried to create a mob with \" + hp + \" HP!\";\n assert mp &gt;= 0 : \"Tried to create a mob with \" + mp + \" MP!\";\n Mob mob = new Mob(name, hp, mp);\n //optionally manipulate the mob further\n mob.giveAbility(Ability.DANCE);\n //...\n return mob;\n }\n}\n</code></pre>\n\n<p>You could be even more clever, and roll your templates into this, so that they are entirely hidden from the user.</p>\n\n<p>. . .</p>\n\n<p>Don't use <code>Vector</code>, it is a concurrent data structure. Since it doesn't look like you are using concurrency, stick with <code>ArrayList</code>.</p>\n\n<p>. . .</p>\n\n<p>I find it's useful to have a static settings class for things like <code>MAX_MESSAGE_LENGTH</code>. That way it's easy to figure out where constants are defined, and to save/load them from disk.\n. . .</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T03:22:55.667", "Id": "12962", "Score": "0", "body": "I'll be taking a great many of your suggestions into my code. Thank you very much for the feedback." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T03:13:55.043", "Id": "13276", "Score": "0", "body": "@Sarophym: No problem! Post your next iteration, I can rip that one apart too :P" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T01:57:08.867", "Id": "8301", "ParentId": "8297", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T00:22:52.360", "Id": "8297", "Score": "7", "Tags": [ "java", "design-patterns" ], "Title": "Java Slick StateBasedGame managing resources across states" }
8297
<p>Model:</p> <pre><code>public class UserBean { @JsonProperty private String userId; @JsonProperty private int limit; @JsonProperty private int page; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } } public class ResponseJSON { private Map&lt;String, Object&gt; response = new LinkedHashMap&lt;String, Object&gt;(); public void setStatus(String status) { response.put("status", status); } public void setMessage(String message) { response.put("message", message); } public void add(String key, Object value) { response.put(key, value); } public Map&lt;String, Object&gt; get() { return this.response; } } </code></pre> <p>Controller:</p> <pre><code>@ResponseBody @RequestMapping(value = "/user/products", method = RequestMethod.POST) public Object getProductListByUser(@RequestBody UserBean userBean) { ResponseJSON responseJSON = new ResponseJSON(); try { List&lt;Object&gt; result = userRepository.getProductListByUser(userBean); int resultCount = result.size(); List&lt;Object&gt; productList = new ArrayList&lt;Object&gt;(); for (int i = 0; i &lt; resultCount; i++) { ProductInfo product = (ProductInfo) result.get(i); Map&lt;String, Object&gt; productInfo = new LinkedHashMap&lt;String, Object&gt;(); productInfo.put("id", product.getId()); productInfo.put("title", product.getTitle()); productInfo.put("description", product.getDescription()); productInfo.put("iconImage", product.getIconImage()); productInfo.put("updateDatetime", product.getUpdateDatetime()); productInfo.put("createDatetime", product.getCreateDatetime()); productList.add(productInfo); } responseJSON.setStatus(Constants.SUCCESS); responseJSON.add("items", productList); } catch (Exception e) { responseJSON.setStatus(Constants.FAIL); responseJSON.setMessage(e.getMessage()); logger.error(e.getMessage()); } return responseJSON.get(); } </code></pre> <p>Repository:</p> <pre><code>@SuppressWarnings("unchecked") @Transactional public List&lt;Object&gt; getProductListByUser(UserBean userBean) { Session session = sessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(ProductInfo.class, "product") .createAlias("product.productOptions", "options", CriteriaSpecification.LEFT_JOIN) .add(Restrictions.eq("product.userId", userBean.getUserId())) .addOrder(Order.asc("productOptions.size")) .setFirstResult((userBean.getPage() - 1) * userBean.getLimit()); .setMaxResults(userBean.getLimit()); return criteria.list(); } </code></pre> <p>I'm developing some back-end APIs. This API returns product lists of some user. Purpose of this API is returning result of JSON data. So, I get datas from repository and assign to <code>ResponseJSON</code> object in the controller. Is this approach efficient or not? Which way is better?</p>
[]
[ { "body": "<p>It would be easier to follow the <code>getProductListByUser</code> method if you use two <code>ResponseJSON</code> instance. One for normal execution and one for the exceptional cases:</p>\n\n<pre><code>try {\n ...\n\n final ResponseJSON responseJSON = new ResponseJSON();\n ...\n\n responseJSON.setStatus(Constants.SUCCESS);\n responseJSON.add(\"items\", productList); \n return responseJSON.get();\n} catch (final Exception e) {\n final ResponseJSON responseJSON = new ResponseJSON();\n responseJSON.setStatus(Constants.FAIL);\n responseJSON.setMessage(e.getMessage());\n logger.error(e.getMessage());\n return responseJSON.get();\n}\n</code></pre>\n\n<p>It also ensures that nobody modifies accidentally the exception case result in the <code>try</code> block and there isn't any incomplete <code>ProductInfo</code> data in the error response.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T09:13:28.233", "Id": "8313", "ParentId": "8300", "Score": "1" } } ]
{ "AcceptedAnswerId": "8313", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T01:15:38.477", "Id": "8300", "Score": "1", "Tags": [ "java", "api", "spring" ], "Title": "Java API code with Spring" }
8300
<p>Does this look right to you? What are its shortcomings? Strengths?</p> <pre><code>import Control.Monad import Control.Monad.Trans.Class import Control.Pipe.Common import Data.Conduit c2p :: (Resource m, Monad m) =&gt; Conduit a m b -&gt; Pipe a b m () c2p = do PreparedConduit push close &lt;- lift $ runResourceT $ prepareConduit c loop push close where loop push close = do input &lt;- await stepResult &lt;- lift $ runResourceT $ push input case stepResult of Producing output -&gt; do mapM_ yield output loop push close Finished _ output -&gt; do mapM_ yield output lift $ runResourceT $ close return () </code></pre>
[]
[ { "body": "<p>I can see three problems with this approach:</p>\n\n<p>1) Calling <code>runResourceT</code> at each step releases all the scarse resources allocated by the original conduit. This is not what you want, since a conduit can depend on the availability of those resources until the point where it terminates.</p>\n\n<p>2) You cannot call <code>close</code> after <code>push</code> returns <code>Finished</code>. This is <a href=\"http://hackage.haskell.org/packages/archive/conduit/0.1.1.1/doc/html/Data-Conduit.html#t%3aPreparedConduit\" rel=\"nofollow\">explicitly stated</a> in the documentation of <code>PreparedConduit</code>.</p>\n\n<p>3) You need to call <code>close</code> on the conduit when the upstream pipe terminates. Unfortunately, I think this is impossible to do with vanilla pipes. That's why I am currently experimenting with what I call \"guarded pipes\". You can find them <a href=\"https://github.com/pcapriotti/pipes-extra\" rel=\"nofollow\">here</a>, together with some other utilities ported over from conduits.</p>\n\n<p>Using guarded pipes, you can write something like:</p>\n\n<pre><code>c2p :: Resource m =&gt; Conduit a m b -&gt; Pipe a b (ResourceT m) ()\nc2p c = do\n PreparedConduit push close &lt;- lift $ prepareConduit c\n loop push close\n where\n loop push close = do\n input &lt;- tryAwait\n case input of\n Nothing -&gt; do\n output &lt;- lift $ close\n mapM_ yield output\n Just input -&gt; do\n stepResult &lt;- lift $ push input\n case stepResult of\n Producing output -&gt; do\n mapM_ yield output\n loop push close\n Finished _ output -&gt;\n mapM_ yield output\n</code></pre>\n\n<p>You can try it, for example, with:</p>\n\n<pre><code>main = runResourceT . runPipe $\n fileProducer \"sample.txt.gz\" &gt;+&gt; c2p CZ.ungzip &gt;+&gt; fileConsumer \"sample.txt\"\n</code></pre>\n\n<p>where <code>fileProducer</code> and <code>fileConsumer</code> are also contained in the above pipes-extra package.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T17:41:42.513", "Id": "12998", "Score": "0", "body": "Nice! Producing a `Pipe a b (ResourceT m) ()` is what I tried at first, but the types didn't line up." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T16:31:05.080", "Id": "8333", "ParentId": "8302", "Score": "3" } } ]
{ "AcceptedAnswerId": "8333", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T03:32:18.430", "Id": "8302", "Score": "6", "Tags": [ "haskell" ], "Title": "Turning Conduits into Pipes" }
8302
<p>I am trying to solve a problem at <a href="http://www.codechef.com/problems/SUMTRIAN" rel="nofollow">Codechef</a>. As I am new to programming, I am not familiar with dynamic programming. However, I do know the basics of recursion and memoization. Hence I implemented a solution to the above mentioned problem. The problem with my solution is that it exceeds the time limit given. As far as I can guess, the problem seems to be with my memoization logic. Please help me optimize the code.</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;string&gt; using namespace std; typedef vector&lt;int&gt; vector1D ; typedef vector&lt;vector1D &gt; vector2D ; // Two Dimensional vector int rownum; int noOfCalls = 0; vector2D a; vector2D cache; // The cache to implement memoization int solve (int i, int j) { int t1,t2,total; if( i &gt; rownum-1 ) { return 0; } else { if (cache[i][j] != 0 &amp;&amp; ( i &lt; 50) &amp;&amp; ( j &lt; 50)) { //for small values use memoization return cache[i][j]; } t1 = solve(i+1,j); t2 = solve(i+1,j+1); total = max(t1,t2) + a[i][j]; cache[i][j] = total;//store in cache } return total; } int main(int argc, char *argv[]) { int tries; cin&gt;&gt;tries; while(tries--) { cin&gt;&gt;rownum; int temp = rownum; for ( int i = 0 ; i &lt; rownum ; i++) { a.push_back(vector1D(rownum,0));//initialize memory } for ( int j = 0; j &lt; 10; j++) { cache.push_back(vector1D(10,0));//initialize cache } for ( int i = 0; i &lt; rownum; i++) { for ( int j = 0 ; j &lt;= i; j++) { cin&gt;&gt;a[i][j]; } } cout&lt;&lt;solve(0,0)&lt;&lt;endl;//call the solving function cache.clear(); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T19:38:52.630", "Id": "12963", "Score": "2", "body": "your solution overall looks Ok. You should extend the memoization for all values. Max no of lines is <=100 and `100X100` vector is Ok to have." } ]
[ { "body": "<p>Why only use memoization for \"small\" values of <code>i</code> and <code>j</code>?</p>\n\n<p>Without memoization, your program runs in exponential time. The problem, which memoization intends to solve, is that you tend to compute the same value many times along the way.</p>\n\n<p>So you memoize some of the values, to save time. On those areas of the table you aren't memoizing, you still suffer the exponential slowdown. And you're only memoizing 1/4 of your domain.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T19:48:32.550", "Id": "8304", "ParentId": "8303", "Score": "0" } }, { "body": "<p>If your priority is performance with this, in addition to having a memoizing cache for up to the size of about the L1 cache - maybe 4K or so, I'd also get rid of the use of the vector of vector. </p>\n\n<p>You're spending a disproportionate amount of time in your vectors' [] operator() functions which will cause an over-abundance of stack pushes and context switches - you're using that operator in at least four places in each pass through solve() - six when not cached already. You can see this if you profile your code. I'd keep it to a vector with dynamically allocated columns and use only pointer arithmetic so that all accesses are happening from the same stack frame in solve(). I'd pre-calculate base pointers in advance and use those as much as possible in the pointer calculations using the bitwise &lt;&lt; sizeof(int) to traverse.</p>\n\n<p>I would also stay local and convert your max(t1,t2) call to use a bit-twiddle trick so that total is now:</p>\n\n<pre><code>total = t1 ^ ((t1 ^ t2) &amp; -(t1 &lt; t2)) + *paij; \n</code></pre>\n\n<p>where *paij is the dereferenced arithmetically calc'ed pointer instead of a[i][j]. That should keep the pipeline full more often.</p>\n\n<p>To get to the next level from there, I would probably move from recursion to an iterative approach if you're not married to recursion. </p>\n\n<p>That should buy you some performance gain, although more could be done depending on your machine configuration. </p>\n\n<h3>Edit: Test for speed.</h3>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n#include &lt;sys/time.h&gt; \n\nusing namespace std; \n\ninline int getmax( int a, int b ) { if ( a &lt; b ) return b; else return a; }\nint main()\n{\n time_t timev;\n timeval t1, t2; \n double elapsed_time; \n const unsigned int RUNL = 1000000000; \n\n int i = 0; \n int j = 1; \n int k = 1; \n int total;\n\n gettimeofday( &amp;t1, NULL );\n while ( i++ &lt; RUNL )\n {\n total = j ^ ( ( j ^ k ) &amp; -( j &lt; k ) );\n k ^= 1;\n }\n gettimeofday( &amp;t2, NULL );\n elapsed_time = ( t2.tv_sec - t1.tv_sec ) * 1000.0;\n elapsed_time += ( t2.tv_usec - t1.tv_usec ) / 1000.0;\n cout &lt;&lt; \"Elapsed time for the bitop was: \" &lt;&lt; elapsed_time &lt;&lt; \" ms\\n\" &lt;&lt; endl;\n i = 0;\n k = 1;\n gettimeofday( &amp;t1, NULL );\n while ( i++ &lt; RUNL )\n {\n total = max( j, k ); k ^= 1;\n }\n gettimeofday( &amp;t2, NULL );\n elapsed_time = ( t2.tv_sec - t1.tv_sec ) * 1000.0;\n elapsed_time += ( t2.tv_usec - t1.tv_usec ) / 1000.0;\n cout &lt;&lt; \"Elapsed time for the stl call was: \" &lt;&lt; elapsed_time &lt;&lt; \" ms\\n\" &lt;&lt; endl;\n i = 0;\n k = 1;\n gettimeofday( &amp;t1, NULL );\n while ( i++ &lt; RUNL )\n {\n total = getmax( j, k ); k ^= 1;\n }\n gettimeofday( &amp;t2, NULL );\n elapsed_time = ( t2.tv_sec - t1.tv_sec ) * 1000.0;\n elapsed_time += ( t2.tv_usec - t1.tv_usec ) / 1000.0;\n cout &lt;&lt; \"Elapsed time for the getmax call was: \" &lt;&lt; elapsed_time &lt;&lt; \" ms\\n\" &lt;&lt; endl; \n\n}\n</code></pre>\n\n<h3>Edit (Edit) Fixed Speed Test:</h3>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n#include &lt;sys/time.h&gt;\n#include &lt;vector&gt;\n\nusing namespace std;\nvoid printTime(int total, std::string const&amp; name, timeval&amp; t1, timeval&amp; t2)\n{\n double elapsed_time;\n\n elapsed_time = ( t2.tv_sec - t1.tv_sec ) * 1000.0;\n elapsed_time += ( t2.tv_usec - t1.tv_usec ) / 1000.0;\n\n std::cout &lt;&lt; \"Result(\" &lt;&lt; total &lt;&lt; \") Elapsed time for the \" &lt;&lt; name &lt;&lt; \" call was: \" &lt;&lt; elapsed_time &lt;&lt; \" ms\\n\" &lt;&lt; std::endl;\n}\n\n\ninline int getmax( int a, int b ) { if ( a &lt; b ) return b; else return a; }\n\nint main()\n{\n timeval t1, t2;\n const unsigned int RUNL = 1000000000;\n\n std::cout &lt;&lt; \"LoadData\" &lt;&lt; std::endl;\n std::vector&lt;int&gt; data(RUNL);\n for(int loop=0;loop &lt; RUNL;++loop)\n {\n data[loop] = rand();\n }\n std::cout &lt;&lt; \"LoadData DONE\" &lt;&lt; std::endl;\n\n\n int j = data[0];\n int k;\n gettimeofday( &amp;t1, NULL );\n for(int loop = 1;loop &lt; RUNL;++loop)\n {\n k = data[loop];\n j = j ^ ( ( j ^ k ) &amp; -( j &lt; k ) );\n }\n gettimeofday( &amp;t2, NULL );\n printTime(j, \"BIT TWIDDLE\", t1, t2);\n\n j = data[0];\n gettimeofday( &amp;t1, NULL );\n for(int loop = 1;loop &lt; RUNL;++loop)\n {\n k = data[loop];\n j = max( j, k );\n }\n gettimeofday( &amp;t2, NULL );\n printTime(j, \"std::max\", t1, t2);\n\n j = data[0];\n gettimeofday( &amp;t1, NULL );\n for(int loop = 1;loop &lt; RUNL;++loop)\n {\n k = data[loop];\n j = getmax( j, k );\n }\n gettimeofday( &amp;t2, NULL );\n printTime(j, \"inline max\", t1, t2);\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>&gt; g++ -O3 x.cpp\n&gt; ./a.out\nLoadData\nLoadData DONE\nResult: total( 2147483645) Elapsed time for the BIT TWIDDLE call was: 1968.2 ms\n\nResult: total( 2147483645) Elapsed time for the std::max call was: 1170.83 ms\n\nResult: total( 2147483645) Elapsed time for the inline max call was: 1178.05 ms\n</code></pre>\n\n<p>It's easy to see why the optimizer runs so much faster than the bit hack from this code from between the gettimeofday calls):</p>\n\n<pre><code>STLMAX\n movl 28(%esp), %ecx\n movl $1, %edx\n movl $1, %eax\n .p2align 4,,7\nL34:\n movl (%ecx,%edx,4), %edx\n cmpl %edx, %ebx\n cmovl %edx, %ebx\n addl $1, %eax\n cmpl $1000000000, %eax\n movl %eax, %edx\n jne L34\n leal 40(%esp), %eax\n movl $0, 4(%esp)\n movl %eax, (%esp)\n\n\nBIT HACK\n movl 28(%esp), %edi\n movl $1, %eax\n movl $1, %edx\n .p2align 4,,7\nL25:\n movl (%edi,%eax,4), %ecx\n xorl %eax, %eax\n cmpl %ebx, %ecx\n setg %al\n xorl %ebx, %ecx\n negl %eax\n addl $1, %edx\n andl %ecx, %eax\n xorl %eax, %ebx\n cmpl $1000000000, %edx\n movl %edx, %eax\n jne L25\n leal 40(%esp), %eax\n movl $0, 4(%esp)\n movl %eax, (%esp)\n</code></pre>\n\n<p>Basically two effective instructions in the loop doing the actual max in optimized STL compiler compared with seven for the bit hack. Lesson learned.</p>\n\n<p>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</p>\n\n<p>Code for hasZeroByte which gave about 2.5x improvement for the bit hack over the other two under -O3 optimization conditions:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n#include &lt;sys/time.h&gt;\n#include &lt;vector&gt;\n\nusing namespace std;\nvoid printTime(int total, std::string const&amp; name, timeval&amp; t1, timeval&amp; t2)\n{\n double elapsed_time;\n\n elapsed_time = ( t2.tv_sec - t1.tv_sec ) * 1000.0;\n elapsed_time += ( t2.tv_usec - t1.tv_usec ) / 1000.0;\n\n std::cout &lt;&lt; \"Result(\" &lt;&lt; total &lt;&lt; \") Elapsed time for the \" &lt;&lt; name &lt;&lt; \" call was: \" &lt;&lt; elapsed_time &lt;&lt; \" ms\\n\" &lt;&lt; std::endl;\n}\n\n\ninline bool checkZbyte1( int a ) \n{ \n for ( int i = 0; i &lt; sizeof( int ); i++ )\n {\n if ( !( 0xff &amp; a ) )\n return true;\n else\n a &gt;&gt;= 8;\n }\n return false;\n}\n\ninline bool checkZbyte2( int a ) \n{ \n if ( !( 0xff &amp; a ) || !( 0xff00 &amp; a ) || !( 0xff0000 &amp; a ) || !( 0xff000000 &amp; a ) )\n return true;\n return false;\n}\n\nint main()\n{\n timeval t1, t2;\n const unsigned int RUNL = 100000000;\n\n std::cout &lt;&lt; \"LoadData\" &lt;&lt; std::endl;\n std::vector&lt;int&gt; data(RUNL);\n for(int loop=0; loop &lt; RUNL; ++loop)\n data[loop] = rand();\n std::cout &lt;&lt; \"LoadData DONE\" &lt;&lt; std::endl;\n\n int j;\n int count = 0;\n\n gettimeofday( &amp;t1, NULL );\n for(int loop = 0; loop &lt; RUNL ;++loop)\n {\n if ( checkZbyte1( data[loop] ) )\n count++;\n }\n gettimeofday( &amp;t2, NULL );\n printTime( count, \"inline version #1\", t1, t2 );\n\n count = 0;\n gettimeofday( &amp;t1, NULL );\n for( int loop = 0; loop &lt; RUNL; ++loop )\n {\n if ( checkZbyte2( data[loop] ) )\n count++;\n }\n gettimeofday( &amp;t2, NULL );\n printTime( count, \"inline version #2\", t1, t2 );\n\n count = 0;\n gettimeofday( &amp;t1, NULL );\n for( int loop = 0; loop &lt; RUNL; ++loop )\n {\n j = data[loop];\n if ( ~( ( ( (j &amp; 0x7F7F7F7F ) + 0x7F7F7F7F ) | j ) | 0x7F7F7F7F ) )\n count++;\n }\n gettimeofday( &amp;t2, NULL );\n printTime( count, \"BIT HACK\", t1, t2 );\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T02:22:55.807", "Id": "12964", "Score": "0", "body": "Unless your compiler is extremely ancient/stupid, it will generate better code for `max` than any bit-twidding hack you come up with. Otherwise these are good ideas :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T13:50:33.037", "Id": "12982", "Score": "0", "body": "I think bit twiddling is silly. Also I am not sure I agree that operator[] is a problem. This is simply `returns base[index]` and as such is probably inlined and is no more expensive than a normal array access. If you are saying that the 2D array is the problem then maybe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T00:58:28.707", "Id": "13033", "Score": "0", "body": "hmm.. Why are bit hacks silly? I just ran 3 different cases of max using 1Billion of each all in identical loops. The results:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T01:09:55.880", "Id": "13034", "Score": "0", "body": "Thing cut me off for taking to long... ironic... the results:\n\n bit hack max as above: 3.052s\n stl max() call: 4.238s\n my own getmax() call: 4.470s\n\nthe results were consistent. I'm using cygwin with gcc 4.5 on a quad 2.5GHz Dell M6400. Try it yourself... I don't think we could disregard an improvement of 29%." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T03:10:02.543", "Id": "13037", "Score": "0", "body": "They are silly because the compiler will always do as well and usually better. If you have found a new optimization to max (unlikely) then it will be introduced into the compiler and the next evolution of the compiler will be just as quick as your code. Post your code. :-) we will see how well it really does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T06:39:18.513", "Id": "13038", "Score": "0", "body": "Loki - I didn't invent or discover this bit hack. It's well known. I think you'll find this link rocks: http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax \n\nThe reason why this is much faster is as I mentioned: it's inline and completely arithmetic with no branches and no context switches due to stack pushes. Branches will flush the CPU pipe, which with intel processors these days are about 16 deep. This will help keep the CPU pipes full and continuous. I don't know that the compiler can be told to use this optimization in any way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T07:03:01.650", "Id": "13041", "Score": "0", "body": "Guess what. Compiler writers can read as well (thus if it is well known (and quicker) it is being used already (automatically)). I don't believe your results are legitimate. Please as requested above **Post Your Code** so we can validate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T17:16:45.440", "Id": "13065", "Score": "0", "body": "1st of four parts:\n\n#include <iostream>\n#include <algorithm>\n#include <sys/time.h>\nusing namespace std;\n\ninline int getmax( int a, int b )\n{\n if ( a < b )\n return b;\n else\n return a;\n}\n\nint main()\n{\n time_t timev;\n timeval t1, t2;\n double elapsed_time;\n\n const unsigned int RUNL = 1000000000;\n\n int i = 0;\n int j = 1;\n int k = 1;\n int total;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T17:17:34.487", "Id": "13066", "Score": "0", "body": "gettimeofday( &t1, NULL );\n while ( i++ < RUNL )\n {\n total = j ^ ( ( j ^ k ) & -( j < k ) );\n k ^= 1;\n }\n gettimeofday( &t2, NULL );\n\n elapsed_time = ( t2.tv_sec - t1.tv_sec ) * 1000.0;\n elapsed_time += ( t2.tv_usec - t1.tv_usec ) / 1000.0;\n cout << \"Elapsed time for the bitop was: \" << elapsed_time << \" ms\\n\" << endl;\n\n i = 0;\n k = 1;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T17:18:16.733", "Id": "13067", "Score": "0", "body": "gettimeofday( &t1, NULL );\n while ( i++ < RUNL )\n {\n total = max( j, k );\n k ^= 1;\n }\n gettimeofday( &t2, NULL );\n\n elapsed_time = ( t2.tv_sec - t1.tv_sec ) * 1000.0;\n elapsed_time += ( t2.tv_usec - t1.tv_usec ) / 1000.0;\n cout << \"Elapsed time for the stl call was: \" << elapsed_time << \" ms\\n\" << endl;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T17:18:26.653", "Id": "13068", "Score": "0", "body": "i = 0;\n k = 1;\n\n gettimeofday( &t1, NULL );\n while ( i++ < RUNL )\n {\n total = getmax( j, k );\n k ^= 1;\n }\n gettimeofday( &t2, NULL );\n\n elapsed_time = ( t2.tv_sec - t1.tv_sec ) * 1000.0;\n elapsed_time += ( t2.tv_usec - t1.tv_usec ) / 1000.0;\n cout << \"Elapsed time for the getmax call was: \" << elapsed_time << \" ms\\n\" << endl;\n\n}" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T17:24:43.277", "Id": "13071", "Score": "0", "body": "You can delete the comments I added the code to your question. I will take a closer look this afternoon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T18:01:27.910", "Id": "13072", "Score": "0", "body": "I just tried it again with -O3 ... you'll need to declare k and total volatile int so the optimizer doesn't optimize them out on MSVC... on gcc -O3 will optimize the variables out and stl max isn't allowing a volatile cast, so nothing will happen. -O1 will actually optimize... and ... you're right. I see no real difference between the bit hack and the stl call for max. In fact, in another, less contrived case I'm working on right now, max was faster than the bit hack. I wasn't optimizing when I tested the code. I guess max is too utilized for compiler people to mess that one up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T18:50:25.723", "Id": "13076", "Score": "0", "body": "I fixed a couple of problems with your test. And re-ran. The test consistently show that the bit twiddle is about half the speed of std::max." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T19:57:19.353", "Id": "13081", "Score": "0", "body": "What happens if you move the bit hack to run as the last test. My concern is that you're suffering a performance hit for the first test due to the initial caches misses at every level for the first test, and many fewer for the subsequent tests. My tests showed that all three tests wound up about the same for all three regardless of compiler on this one intel machine - given optimization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T21:54:34.057", "Id": "13089", "Score": "0", "body": "No difference (ie bit twiddling twice as slow). The cache has already been warmed up by the init (setting everything to rand()). So you get the same cache effects on each test. But I changed the order and got the same results." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T21:58:21.300", "Id": "13090", "Score": "0", "body": "But this just supports my theory. The compiler is using the best max algorithm for the platform. On my platform (Mac/gcc) it has a faster implementation; on your platform it is the same (may us bit twiddling underneath). The point being the compiler will always have the fastest version you are not going to beat it. If you do beat it then tell the compiler vendor and the implementation will be updated for your platform and next version of the compiler will equal the hand coded version thus you will never beat the compiler (especially in the long run)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T01:02:51.207", "Id": "13103", "Score": "0", "body": "Performance could be better in bit hacks in some useful functions not in the library (unlike this one) since the compiler wouldn't know what's intended in aggregate. Esp. in hacks that avoid branches. Like would the optimizer do better in assembling the obvious method than: // 32-bit word check if any 8-bit byte in it is 0: bool hasZeroByte = ~((((v & 0x7F7F7F7F) + 0x7F7F7F7F) | v) | 0x7F7F7F7F); (I don't have time now to check) ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T01:17:01.253", "Id": "13105", "Score": "0", "body": "**Totally disagree**. The test we did just proved that your thinking is not correct. That was the whole point of this conversation. You will always loose to a compiler. Any decent optimizing compiler already does all the optimizations that you can think off. If you think of an optimization that is not in the compilers vocab (**very very** unlikely) it will be added the next iteration of the compiler. Thus you will never beat it and your code will be unmaintainable so a **DOUBLE** loss." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T17:21:09.217", "Id": "13183", "Score": "0", "body": "See toy code post above for has ZeroByte = ~((((v & 0x7F7F7F7F) + 0x7F7F7F7F) | v) | 0x7F7F7F7F). Even with -O3 optimization this got 2.5x better on my setup. I used two inlined variants of the alternatives. I agree with you, if it is better than the compiler can do, it could be rolled into a library. But not all bit hacks could reasonably be added. These are one-liners - maybe just good to educate people on what is out there and where, and then add to that store of knowledge which ones are useless and less efficient than what the libs/compiler opt will provide" } ], "meta_data": { "CommentCount": "20", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T23:05:29.893", "Id": "8305", "ParentId": "8303", "Score": "1" } }, { "body": "<h3>General Comments.</h3>\n<p>I hate your use of global variables.</p>\n<pre><code>int rownum;\nint noOfCalls = 0;\nvector2D a;\nvector2D cache; // The cache to implement memoization\n</code></pre>\n<p>I suppose it is an attempt at better performance.</p>\n<p>The test for j here is redundant:</p>\n<pre><code>if (cache[i][j] != 0 &amp;&amp; ( i &lt; 50) &amp;&amp; ( j &lt; 50)) \n</code></pre>\n<p>If i is smaller than 50 then j can not be greater than 50. If i is greater than 50 then the test will fail and there is no need to test what the value of j is.</p>\n<h3>Bugs</h3>\n<pre><code> for ( int i = 0 ; i &lt; rownum ; i++) {\n a.push_back(vector1D(rownum,0));//initialize memory\n }\n</code></pre>\n<p>As you never clear <code>a</code> the size increases for every puzzle.<br />\nThis can become quite expensive as <code>a</code> will continuously keep breaking its buffer and have to be re-allocated (copying all those internal arrays).</p>\n<h3>Speed</h3>\n<p>If you are solely going for speed then <code>operator&gt;&gt;</code> is about half the speed of <code>scanf</code> as it (operator&gt;&gt;) takes into account a lot of local stuff that is not done with scanf.</p>\n<p>Your recursive algorithm is computing some spots multiple times.</p>\n<pre><code>// Your Triangle\n1\n2 3\n4 5 6\n7 8 9 10\n11 12 13 14 15\n\n// Number of times each spot is hit with recursion\n1\n1 1\n1 2 1\n1 3 3 1\n1 4 6 4 1\n</code></pre>\n<p>As you can see some of the spots in the center bottom of the triangle are being hit many many times by recursion when you only want to hit each location once. Thus an iterative solution is probably better.</p>\n<p>You are using a 2D array to represent the triangle which requires two de-references (which can be inefficient (but without measuring I am not convinced this is a major issue)). Rather than do that use a 1-D array given the number of rows n you can quickly compute the number of elements in the triangle as <code>n*(n+1)/2</code> and thus re-size the array in one statement. Element access for a child of m is <code>m+row(m)+0</code> and <code>m+row(m)+1</code> (note the calculation of row(m) does not need to be done each time you can keep track of this as you increment m).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T14:38:54.063", "Id": "8328", "ParentId": "8303", "Score": "2" } } ]
{ "AcceptedAnswerId": "8328", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T19:24:33.497", "Id": "8303", "Score": "2", "Tags": [ "c++", "optimization", "algorithm", "memoization" ], "Title": "Memoization-based puzzle solution - sums in a triangle" }
8303
<p>In this new project I'm working on I need to create objects on runtime by data from the DB, right now I have two groups of classes, each group implementing a different interface.</p> <p>I started working on a factory class, <strong>which will map id to a type</strong>, an abstract one so I can extend with a factory for each group.</p> <p>The constructor parameter is the type of the interface common to all implementors of the group.</p> <pre><code>abstract class Factory { private Dictionary&lt;int, Type&gt; idsToTypes; private Type type; public Factory(Type _type) { idsToTypes = new Dictionary&lt;int, Type&gt;(); type = _type; } protected Object GetProduct(int id, params object[] args) { if (idsToTypes.ContainsKey(id)) { return Activator.CreateInstance(idsToTypes[id], args); } else { return null; } } public void RegisterProductType(int id, Type _type) { if (_type.IsInterface || _type.IsAbstract) throw new ArgumentException(String.Format("Registered type, {0}, is interface or abstract and cannot be registered",_type)); if (type.IsAssignableFrom(_type)) { idsToTypes.Add(id, _type); } else { throw new ArgumentException(String.Format("Registered type, {0}, was not assignable from {1}",_type,type)); } } </code></pre> <p>Then I noticed both extending factories look the same, and in the end with the use of generics I got to this class:</p> <pre><code> class GenericSingletonFactory&lt;T&gt; : Factory { static public GenericSingletonFactory&lt;T&gt; Instance = new GenericSingletonFactory&lt;T&gt;(); private GenericSingletonFactory() : base(typeof(T)) { } public T GetObject(int id, params object[] args) { Object obj = base.GetProduct(id, args); if (obj != null) { T product = (T)obj; return product; } else return default(T); } } </code></pre> <p>So I can just use like so:</p> <pre><code>GenericSingletonFactory&lt;ISomething&gt;.Instance.RegisterProductType(1, typeof(ImplementingISomething)); ISomething something = GenericSingletonFactory&lt;ISomething&gt;.Instance.GetObject(1); </code></pre> <p>It seems ok... but am I missing something here? is this a good way to do this kind of things? I'm a little weary that this will fall apart on runtime somehow...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T07:43:32.513", "Id": "12967", "Score": "1", "body": "I think that if you write and run some tests for this, you'll know whether or not it works, with far more confidence than you'll ever get from the well-meaning words of random strangers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T08:13:28.813", "Id": "12969", "Score": "1", "body": "Hi David, of course I tested it. it works. I'm asking if this kind of implementation won't fall to some obscure end-cases or parallelism issues, maybe it will be hard to maintain, maybe it works really slow and there is a faster way to achieve the same thing... anyway, this is why I am asking it here :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T09:15:37.370", "Id": "12970", "Score": "0", "body": "Any good readon you don't want to use an OR mapper like EntityFramework 4 or NHibernate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T09:29:55.210", "Id": "12972", "Score": "0", "body": "Unfortunately our main project, which is in production has no ORM, this new project needs to interact with it, and I don't know if it's a good idea to use ORM in satellite projects and not in the main project. and changing to an ORM in the main project will never pass management..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T09:32:39.650", "Id": "12973", "Score": "0", "body": "As long as you keep clear boundaries, there's nothing in the way of using a mapper in a sattelite assembly. The entities can implement the interfaces needed and interact as intended. Give it a go. Especially if you can use .net 4 and EF 4.2. (biased opinion ;) )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T10:41:10.017", "Id": "12976", "Score": "0", "body": "It looks good to me. It's certainly a perfectly valid way of doing things, and easier to maintain than the alternatives. My earlier comment was because you seemed to be asking whether it was going to work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T06:52:49.667", "Id": "13435", "Score": "1", "body": "Have you considered checking NHibernate for your DAL? It has its own constructs for mapping ids to type instances. Apart from that, your generic class shouldn't inherit from the non generic one. Instead, make your Dictionary a member of this class with T as type parameter to avoid casting. Sry for typos, writing this on a phone." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T09:34:50.260", "Id": "13436", "Score": "0", "body": "@Groo - what if I still want to keep the abstract Factory for other uses?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T09:40:25.037", "Id": "13437", "Score": "0", "body": "@Mithir: I cannot think of a scenario where it would allow you to do something which a generic one couldn't do. Do you have an example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T10:02:30.050", "Id": "13438", "Score": "0", "body": "@Groo actually you may be right :) . you should make this an answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T10:54:45.357", "Id": "13439", "Score": "0", "body": "@Groo although I would still need to cast from Activator, it returns an object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T11:07:58.113", "Id": "13440", "Score": "0", "body": "Ok, I had an hour of spare time waiting for something to finish, so I wrapped up an answer. Yes, maybe I didn't express it clearly enough. I wanted to say it can be merged. I'll post in a minute." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T16:21:38.143", "Id": "13445", "Score": "0", "body": "How did this happen? This question was missing and I asked about it at meta, now it reappeared? Weird..." } ]
[ { "body": "<p>I'm not too familiar with C#, so just two general notes.</p>\n\n<ol>\n<li><p>Instead of structures like this:</p>\n\n<pre><code>if (idsToTypes.ContainsKey(id))\n{\n return Activator.CreateInstance(idsToTypes[id], args);\n}\nelse\n{\n return null;\n}\n</code></pre>\n\n<p>you could write this:</p>\n\n<pre><code>if (idsToTypes.ContainsKey(id))\n{\n return Activator.CreateInstance(idsToTypes[id], args);\n}\nreturn null;\n</code></pre>\n\n<p>The <code>else</code> keyword is unnecessary in these cases.</p></li>\n<li><p>Using guard clauses makes the code flatten and more readable.</p>\n\n<pre><code>if (!type.IsAssignableFrom(_type)) {\n throw new ArgumentException(String.Format(\"Registered type, {0}, was not assignable from {1}\", _type, type));\n}\nidsToTypes.Add(id, _type);\n</code></pre>\n\n<p>References: <em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em>; <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Flattening Arrow Code</a></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T11:50:52.370", "Id": "12977", "Score": "0", "body": "You might want to add a \"return\" after insertion into the dictionary ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T12:05:27.820", "Id": "12978", "Score": "0", "body": "Thank you, @WillemvanRumpt! The example was wrong, I've changed it :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T08:58:51.627", "Id": "8311", "ParentId": "8307", "Score": "4" } }, { "body": "<p>Several considerations: </p>\n\n<ol>\n<li><p>Base <code>Factory</code> class does all the work, so I would simply merge it into the generic method.</p></li>\n<li><p>Your singleton instance is stored in a <strong>public field</strong>. This means any part of your program can easily replace it. You should make it readonly, or (even better) expose it through a readonly <strong>property</strong>.</p></li>\n<li><p>If you are not abstracting the factory (i.e. exposing the <code>Instance</code> property as an interface), it means there is no way to use any other factory in your program. This has two possible consequences:</p>\n\n<ul>\n<li><p>you can either skip accessing <code>Instance</code> every time and use a plain static method (<code>Factory&lt;T&gt;.Instance.DoStuff(...)</code> becomes <code>Factory&lt;T&gt;.DoStuff(...)</code>, which is slightly shorter)</p></li>\n<li><p>or, you can decide that you want to hide the implementation of the factory behind an interface (<code>IFactory&lt;T&gt;</code>, for example), in which case a concrete factory will be stored in an instance of a separate class, which would completely change the call to something like <code>DAL.GetFactory&lt;T&gt;().DoStuff(...)</code> (<code>DoStuff</code> becomes an <strong>instance</strong> method). This leaves allows greater flexibility, since you can pass an <code>IFactory&lt;T&gt;</code> to a part of code which doesn't need to know about your static <code>DAL</code> classes. But it would require additional redesign.</p></li>\n</ul></li>\n<li><p>If you add a new generic parameter to the <code>RegisterProductType</code> method, you can use the <code>where</code> clause to limit the type to derived types at <strong>compile time</strong>. Getting a compile error is much better than getting a run-time one.</p></li>\n<li><p>Are you sure that you need to pass the constructor parameters to the <code>GetProduct</code> method? This part might be slightly unusual (although there might be cases where you would want to instantiate your classes by passing a parameter). What it there is a specific derived type which accepts different parameters than other types? <code>Activator.CreateInstance</code> indicates that you are forcing all your callers to <strong>know</strong> which constructor your method will use.</p></li>\n</ol>\n\n<p>First four points (simplified) would result in something like:</p>\n\n<pre><code>public class Factory&lt;T&gt;\n{\n private Factory() { }\n\n static readonly Dictionary&lt;int, Type&gt; _dict = new Dictionary&lt;int, Type&gt;();\n\n public static T Create(int id, params object[] args)\n {\n Type type = null;\n if (_dict.TryGetValue(id, out type))\n return (T)Activator.CreateInstance(type, args);\n\n throw new ArgumentException(\"No type registered for this id\");\n }\n\n public static void Register&lt;Tderived&gt;(int id) where Tderived : T\n {\n var type = typeof(Tderived);\n\n if (type.IsInterface || type.IsAbstract)\n throw new ArgumentException(\"...\");\n\n _dict.Add(id, type);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Factory&lt;IAnimal&gt;.Register&lt;Dog&gt;(1);\nFactory&lt;IAnimal&gt;.Register&lt;Cat&gt;(2);\n\n// this is the \"suspicious\" part.\n// some instances may require different parameters?\nFactory&lt;IAnimal&gt;.Create(2, \"Garfield\");\n</code></pre>\n\n<p>Fifth point is worth considering. If you change your factory to this:</p>\n\n<pre><code>public class Factory&lt;T&gt;\n{\n private Factory() { }\n\n static readonly Dictionary&lt;int, Func&lt;T&gt;&gt; _dict \n = new Dictionary&lt;int, Func&lt;T&gt;&gt;();\n\n public static T Create(int id)\n {\n Func&lt;T&gt; constructor = null;\n if (_dict.TryGetValue(id, out constructor))\n return constructor();\n\n throw new ArgumentException(\"No type registered for this id\");\n }\n\n public static void Register(int id, Func&lt;T&gt; ctor)\n {\n _dict.Add(id, ctor);\n }\n}\n</code></pre>\n\n<p>Then you can use it like this:</p>\n\n<pre><code>Factory&lt;IAnimal&gt;.Register(1, () =&gt; new Dog(\"Fido\"));\nFactory&lt;IAnimal&gt;.Register(2, () =&gt; new Cat(\"Garfield\", something_else));\n\n// no need to pass parameters now:\nIAnimal animal = Factory&lt;IAnimal&gt;.Create(1);\n</code></pre>\n\n<p>This delegates all construction logic to init time which allows complex scenarios for different object types. You can, for example, make it return a singleton on each call to <code>Create</code>:</p>\n\n<pre><code>// each call to Factory&lt;IAnimal&gt;.Create(3) should return the same monkey\nFactory&lt;IAnimal&gt;.Register(3, () =&gt; Monkey.Instance);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T13:32:05.897", "Id": "8586", "ParentId": "8307", "Score": "40" } } ]
{ "AcceptedAnswerId": "8586", "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T06:46:00.237", "Id": "8307", "Score": "29", "Tags": [ "c#", "design-patterns" ], "Title": "Implementing factory design pattern with generics" }
8307
<p>I want to write a regular expression to determine whether a given string is uppercase and sorted in non-descending order.</p> <pre><code>^A*B*C*D*E*F*G*H*I*J*K*L*M*N*O*P*Q*R*S*T*U*V*Q*X*Y*Z*$ </code></pre> <p>I was just wondering if it is possible to improve the above regex.</p> <p>Examples of correct strings:</p> <blockquote> <p>AEHII<br>EFKLZ</p> </blockquote> <p>Examples of wrong strings:</p> <blockquote> <p>AbCDE<br> YABKL</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T13:50:03.190", "Id": "12981", "Score": "3", "body": "`I want to write a regular expression ...` now you have 2 problems. :) What do you want to improve? A working solution for UTF-8 like ÄÖÜ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T14:16:52.793", "Id": "12983", "Score": "0", "body": "@userunknown No I want to know if it's possible to have a shorter solution" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T17:04:45.353", "Id": "13061", "Score": "0", "body": "@Meysam he means that your Regex might not address all problems. Example: is `AÖU` a correct string, or an incorrect one? What about `AÄ`? And `ÄA`?" } ]
[ { "body": "<h2>No.</h2>\n<p>There is no way to express</p>\n<p>(xy)* | ∀(x, y) =&gt; x &lt;= y ∧ (x, y) ∈ {A..Z}</p>\n<p>with regular expressions in such an abstract way, at least not in popular regex usage I'm aware of. So you have to enumerate all characters explicitly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T14:36:55.347", "Id": "12984", "Score": "0", "body": "I agree that you cannot do this for the *general* case, but it certainly seems like the regex provided in the question would achieve this for the *specific* case cited. Could you please elaborate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T15:24:57.713", "Id": "12988", "Score": "0", "body": "@jdmichal: Meysam uses a shorter expression. (Ok, I correct my answer to claim 'in a shorter way') This would be possible, if it would be possible to say we have an arbitrary number of pairs of characters, such that for each first of them, the first one is smaller or equals to the following (in the meaning of first in ordering)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T17:06:30.157", "Id": "13062", "Score": "0", "body": "@userunknown I really love this answer, but it does not address that the characters must be upper-case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T15:13:14.573", "Id": "13479", "Score": "0", "body": "Well - I concentrated on the part, which is not elegantly expressible with regex. Is it better now? [A-Z] is easy to express with regex." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T14:33:59.793", "Id": "8325", "ParentId": "8308", "Score": "5" } }, { "body": "<p>There is no shorter solution. Because you are enforcing order, you must list every single entity in desired order. And because you are allowing zero to many instances of each entity, you must provide the * operator. And because you want to match the entire string, you must provide the anchors on both ends.</p>\n\n<p>Could you write one that runs faster? Possibly. But shorter? I don't see how.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T14:34:32.633", "Id": "8326", "ParentId": "8308", "Score": "6" } }, { "body": "<p>As already pointed out by @userunknown, there is no way to simplify your regular expression from a purist point of view.</p>\n\n<p>However, if you're using Perl, here's one way to do it that doesn't involve explicitly writing out all the letters A to Z.</p>\n\n<pre><code>my $uppersorted = \"^\" . join(\"\", map {\"$_*\"} ('A'..'Z')) . \"\\$\";\n</code></pre>\n\n<p>Making that into a compiled regex:</p>\n\n<pre><code>$uppersorted = qr/$uppersorted/;\n</code></pre>\n\n<p>Testing it with the given input cases:</p>\n\n<pre><code>my @tests = (\"AEHII\", \"EFKLZ\", \"AbCDE\", \"YABKL\");\n\nforeach my $test (@tests) {\n printf \"%s: %s\\n\",\n $test,\n $test =~ $uppersorted? \"YES\" : \"NO\";\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T17:49:53.880", "Id": "8338", "ParentId": "8308", "Score": "2" } } ]
{ "AcceptedAnswerId": "8326", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T07:12:06.760", "Id": "8308", "Score": "4", "Tags": [ "regex" ], "Title": "How to determine the order of letters by regex?" }
8308
<p>The <a href="https://spring.io/projects/spring-framework" rel="nofollow noreferrer">Spring Framework</a> is an open-source application framework for the <a href="https://codereview.stackexchange.com/tags/java/info">Java</a> platform.</p> <p>Spring is a non-invasive, versatile, powerful <a href="https://en.wikipedia.org/wiki/Software_framework" rel="nofollow noreferrer">framework</a>.</p> <p>Spring framework complements the Java EE APIs but is not a replacement for Java EE. It reduces most boilerplate code, reducing the burden on developers.</p> <p>Spring provides services and functionalities across the application domain, including a core <a href="https://en.wikipedia.org/wiki/Inversion_of_control" rel="nofollow noreferrer">Inversion of Control</a> container, technology-agnostic data-access and <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="nofollow noreferrer">MVC</a> layers, extensive <a href="https://en.wikipedia.org/wiki/Aspect-oriented_programming" rel="nofollow noreferrer">AOP</a> support, task scheduling, and various integration patterns designed to make distributed system development simpler and clearer. While some Spring modules are simple wrappers and helpers over the <a href="https://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition" rel="nofollow noreferrer">Java EE</a> specifications, the majority of them go far beyond the Java EE specification.</p> <p>The latest Spring Framework Reference Documentation can be found <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/" rel="nofollow noreferrer">here</a>.</p> <h3>Guides:</h3> <ul> <li><a href="https://spring.io/guides" rel="nofollow noreferrer">Spring Guides and Tutorials</a></li> <li><a href="https://www.baeldung.com/" rel="nofollow noreferrer">A Spring Guides and Tutorials unofficial website</a></li> </ul> <h3>Video tutorial on Spring Framework</h3> <ul> <li><a href="https://spring.io/video" rel="nofollow noreferrer">Spring's YouTube channel</a></li> <li><a href="https://www.javabrains.io/courses/springboot-quickstart" rel="nofollow noreferrer">Java Brains</a></li> <li><a href="https://javabeat.net/spring-tutorials/" rel="nofollow noreferrer">Spring Tutorials Collections</a></li> </ul> <h3>Blog:</h3> <ul> <li><a href="https://spring.io/blog" rel="nofollow noreferrer">Spring Team Blog</a></li> </ul> <h3>More information:</h3> <ul> <li><a href="https://en.wikipedia.org/wiki/Spring_Framework" rel="nofollow noreferrer">Spring Framework Wikipedia Article</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-01-26T08:34:34.177", "Id": "8309", "Score": "0", "Tags": null, "Title": null }
8309
The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T08:34:34.177", "Id": "8310", "Score": "0", "Tags": null, "Title": null }
8310
<p>I'm running into an issue while playing around with some models in a Rails app. Namely issues of the polymorphic variety. I think I may have solved it, more or less looking for an approval.</p> <p>I have the following models in my app:</p> <pre><code>class Issue &lt; ActiveRecord::Base belongs_to :creator, class_name: 'User', foreign_key: 'creator_id' has_many :user_issues has_many :helpers, through: :user_issues, source: :users end class User &lt; ActiveRecord::Base has_many :issues, foreign_key: 'creator_id' has_many :user_issues has_many :issues_helped, through: :user_issues, source: :issues end class UserIssues &lt; ActiveRecord::Base belongs_to :user belongs_to :issue end </code></pre> <p>Scenario:</p> <p><code>UserOne</code> creates an issue and is saved as the <code>IssueOne</code>'s creator. <code>UserTwo</code> decides to help <code>UserOne</code> and joins/follows <code>IssueOne</code> (<code>has_many :issues_helped</code> declared in the model) and is allowed to post a comment. <code>UserTwo</code> is a helper in this instance.</p> <p>Well, <code>UserTwo</code> is now in need of some help and creates a new issue of his own. <code>UserTwo</code> is the creator of <code>IssueTwo</code>. <code>UserOne</code> decides to help out his new buddy <code>UserTwo</code> on his issue and joins/follows <code>IssueTwo</code>, and is allowed to post a comment. <code>UserOne</code> has now become a helper in this instance.</p> <ol> <li><p>Is this the Rails way of doing it? This is the best solution I have come up with, so far.</p></li> <li><p>Am I misusing the power of <code>has_many :x, through: :y, source: :z</code>?</p></li> </ol>
[]
[ { "body": "<p>The foreign key is not needed for <code>belongs_to :creator</code> since rails will infer this foreign key from the association name. The source has to point to the relation for <code>UserIssue</code> (you pluralized this name but active record class names should be singularized in most cases) so instead of <code>source: users</code>, and <code>source: issues</code>, you want <code>source: user</code>, <code>source: issue</code>. </p>\n\n<p>Another way you could have accomplished the same thing, which IMO is a bit cleaner is the following:</p>\n\n<pre><code>class Issue &lt; ActiveRecord::Base\n belongs_to :creator, class_name: 'User'\n has_many :helpings, :foreign_key =&gt; 'issue_helped_id'\n has_many :helpers, through: :helpings\nend\n\nclass User &lt; ActiveRecord::Base\n has_many :issues, foreign_key: 'creator_id'\n has_many :helpings, foreign_key: 'helper_id'\n has_many :issues_helped, through: :helpings\nend\n\nclass Helping &lt; ActiveRecord::Base\n belongs_to :helper, class_name: 'User'\n belongs_to :issue_helped, class_name: 'Issue'\nend\n</code></pre>\n\n<p>It also gives the join table a more descriptive name. For this to work you need to modify your inflections since rails cannot pluralize <code>issue_helped</code> or singularize <code>issues_helped</code> out of the box. To do this, in <code>config/initializers/inflections.rb</code> add:</p>\n\n<pre><code>ActiveSupport::Inflector.inflections do |inflect|\n inflect.plural 'issue_helped', 'issues_helped'\n inflect.singular 'issues_helped', 'issue_helped'\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T14:20:19.303", "Id": "8360", "ParentId": "8312", "Score": "1" } }, { "body": "<p>I can't for the life of me come up with a name but your code could definitely benefit so I'm going to use an analogous example of how one would use comments(assume User exists -- perhaps making use of devise or similar framework) </p>\n\n<pre><code> class Image &lt; ActiveRecord::Base\n belongs_to :user\n include Commentable\n end \n\n class Post &lt; ActiveRecord::Base\n belongs_to :user\n include Commentable \n end \n class Comments &lt; Active::Record::Base\n belongs_to :commentable, :polymorphic =&gt; true \n belongs_to :user\n end\n\n\n module Commentable \n extend ActiveSupport::Concern\n\n included do\n has_many :comments, :as =&gt; :commentable\n accepts_nested_attributes_for :comments #allows for you to do @image.comments \n end\n end\n</code></pre>\n\n<p>Now you've DRY'd up your code and it looks clean...and if you wanted to make a Video resource -- you can do the same and it looks clean. I'm not sure if it's premature in your case, I'm just learning myself and figured I'd share what I'm learning. &lt;3 </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-22T20:01:28.933", "Id": "110341", "Score": "1", "body": "Welcome to Code Review! We're looking for extended answers that are more than just a link." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-22T20:31:18.940", "Id": "110343", "Score": "0", "body": "I've edited it to be more concrete and included an example...PS a code editor would be nice on StackExchange :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-22T20:38:08.713", "Id": "110344", "Score": "0", "body": "You could in your example make it Helpable but putting code that will be repeated potentially in a concern is good practice" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-22T19:52:33.370", "Id": "60827", "ParentId": "8312", "Score": "0" } } ]
{ "AcceptedAnswerId": "8360", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T09:12:01.650", "Id": "8312", "Score": "3", "Tags": [ "ruby", "ruby-on-rails", "active-record", "polymorphism" ], "Title": "ActiveRecord model for users who have issues or who assist with issues" }
8312
<p>Puzzle Description:</p> <blockquote> <p>A number is called lucky if the sum of its digits, as well as the sum of the squares of its digits is a prime number. How many numbers between A and B are lucky?</p> </blockquote> <p>How can I improve performance of the following code?</p> <pre><code>import java.util.Scanner; public class lucky_num { public static void main(String[] args) { lucky_num sr = new lucky_num(); Scanner scanner = new Scanner(System.in); int no_cases = scanner.nextInt(); for (int i = 0; i &lt; no_cases; i++) { System.out.println(sr.solve(scanner.nextLong(), scanner.nextLong())); } } private int solve(long l, long m) { int count = 0; for (long i = l; i &lt;= m; i++) { if (logic(i)) { count++; } } return count; } private boolean logic(long i) { return (isSUM(i) &amp;&amp; isSUMsq(i)); } private boolean isSUMsq(long i) { int sum = 0; while (i &gt; 9) { long k = i % 10; i = i / 10; sum += k * k; } sum += i * i; return (isPrime(sum)); } private boolean isSUM(long i) { int sum = 0; while (i &gt; 9) { long k = i % 10; i = i / 10; sum += k; } sum += i; return (isPrime(sum)); } private boolean isPrime(int num) { if(num==2) return true; // check if n is a multiple of 2 if (num % 2 == 0 || num==1 ) return false; // if not, then just check the odds for (int i = 3; i * i &lt;= num; i += 2) { if (num % i == 0) return false; } return true; } } </code></pre> <p>Sample input:</p> <pre><code>2 1 20 120 130 </code></pre> <p>Sample output:</p> <pre><code>4 1 </code></pre> <p>Constraints:</p> <pre><code>1 &lt;= T &lt;= 10000 1 &lt;= A &lt;= B &lt;= 10^18 </code></pre>
[]
[ { "body": "<p>You could use <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Eratosthenes sieve</a> to find the prime numbers &lt;= 1000 (or a proper value that can be the max sume of digits) before doing anything else, and not use isPrime function every time you need to check a number. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T13:33:31.837", "Id": "8323", "ParentId": "8319", "Score": "4" } }, { "body": "<pre><code>private boolean logic (long i) {\n if (isSUM (i) &amp;&amp; isSUMsq (i)) {\n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n\n<p>This is a often to be seen pattern - the 'it is true if it's true, else if it's false it's false'-pattern. </p>\n\n<p>Why don't you write: </p>\n\n<pre><code>private boolean logic (long i) {\n if ((isSUM (i) &amp;&amp; isSUMsq (i)) == true) \n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>private boolean logic (long i) {\n if (((isSUM (i) &amp;&amp; isSUMsq (i)) == true) == true) \n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n\n<p>You may as well try to move into the opposite direction: </p>\n\n<pre><code>private boolean logic (long i) {\n boolean tf = (isSUM (i) &amp;&amp; isSUMsq (i));\n return tf;\n}\n</code></pre>\n\n<p>or just</p>\n\n<pre><code>private boolean logic (long i) {\n return (isSUM (i) &amp;&amp; isSUMsq (i));\n}\n</code></pre>\n\n<p>but probably, the compiler does the same for all those alternatives. Similarly, you have 2 places where you just may use:</p>\n\n<pre><code>return isPrime (sum);\n</code></pre>\n\n<p>But for performance reasons there are 3 other points much more relevant: </p>\n\n<ul>\n<li>get a faster prime checking algorithm. They are all over the place, so I don't repeat them here. </li>\n<li>If you perform multiple searches, caching the results should speed up things, depending on the numbers and the prediction you can make about these numbers.</li>\n<li>The build-in isProbablePrime should speed things up for really big numbers.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T13:47:36.360", "Id": "8324", "ParentId": "8319", "Score": "3" } }, { "body": "<p>(So I wrote all this before I noticed your loop conditional used <code>i * i &lt;= num</code>. I still think the below is valuable information, so I'll post it anyway. As far as whether it's cheaper to multiply each time or calculate a square root once at the beginning, it will probably depend on how big the numbers you're checking are.)</p>\n\n<p>I agree with <a href=\"https://codereview.stackexchange.com/a/8323/10355\">gabitzish</a> that the best way to check for primes is using a sieve. However, a quicker improvement to your specific algorithm is to only check up to the square root of the number under question. Any checking above the square root, and you are simply checking for the factor pair of one of the smaller numbers you already checked.</p>\n\n<p>For instance, 21 is not prime, because 3 * 7 = 21. Square-root of 21 is ~4.5826. By checking above that value, what I am really checking for is the 7 factor. But, I would have already found the 3 smaller 3 factor.</p>\n\n<pre><code>private boolean isPrime(int num) {\n if(num==2)\n return true;\n\n // check if n is a multiple of 2\n if (num % 2 == 0 || num==1 )\n return false;\n\n // if not, then just check the odds\n int limit = Math.sqrt(num); // Floor/truncation here is OK.\n for (int i = 3; i * i &lt;= limit; i += 2) {\n if (num % i == 0)\n return false;\n }\n return true;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T15:02:55.197", "Id": "8329", "ParentId": "8319", "Score": "1" } }, { "body": "<p>Additional performance improvements for <code>isPrime</code>:</p>\n\n<ul>\n<li><p>As others have said, you only need to test up to the square root of <code>num</code>, since every composite number has at least one prime factor less than or equal to its square root</p></li>\n<li><p>Additionally, cache known primes as you generate them and test subsequent numbers against only the numbers in this list (instead of every number below <code>sqrt(num)</code>)</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T17:04:25.733", "Id": "8335", "ParentId": "8319", "Score": "2" } }, { "body": "<p>The maximum sum of squares-of-digits of an \\$n\\$-digit number is \\$n\\cdot9\\cdot9 = n\\cdot81\\$. The number of digits in a number \\$B\\$ is \\$\\lceil\\log_{10}(B)\\rceil\\$.</p>\n\n<p>Since you only need to <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">sieve</a> to the <em>square root</em> of the number you're testing for primality, you only need to run your sieve from \\$3\\$ to \\$\\sqrt{\\lceil \\log_{10}(B)\\rceil\\cdot81}\\$. Even for \\$B\\$ = 1 billion, this means the max you need to sieve to is \\$28\\$.</p>\n\n<p>So, run the sieve once, and simply cache the results.</p>\n\n<hr>\n\n<p>Also, if you wanted to be <em>really</em> cool, you could probably get some minor speed-ups by not calculating the sums-of-digits, and looping over them instead.</p>\n\n<p>What I mean by that is this: notice that the sum of digits of \\$32x\\$ <em>(where \\$x\\$ is any digit - read that as \"three hundred and twenty-\\$x\\$\")</em> is always going to be \\$3 + 2 + x\\$, and the sum-of-squares will always be \\$9 + 4 + x^2\\$. Thus, instead of looping from \\$320\\$ to \\$329\\$ and calculating the sum-of-digits and sum-of-square-of-digits every time, you could just loop from \\$x = 0\\$ to \\$x = 9\\$, and check \\$3+2+x\\$ and \\$9+4+x^2\\$ for primality.</p>\n\n<p>Using a bit of recursion, you could loop over all values of all digits.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T18:40:12.860", "Id": "13192", "Score": "0", "body": "i didnt understand how @3+2+x can be generalized if i need to loop b/w 100-300 etc.," } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T18:26:29.523", "Id": "8339", "ParentId": "8319", "Score": "10" } }, { "body": "<p>I completely agree with @gabitzish.You can gain lot of performance improvement by storing all the primes up to some limit in array and access them in O(1). I would also suggest below techniques to improve the performance.</p>\n\n<ul>\n<li>If the number is divisible by 3 or 9 the the sum of digits also divisible by 3 or 9.You can skip many such number by a divisibility test by 3 or 9 and avoid very costly <code>isSUM</code> and <code>isSUMsq</code> calls.Also since you only need to test odd sums you can hop over the numbers once you found first odd sum.\ne.g. For range 120-130 sum of first number 120=1+2+0=3 so you can skip next number 121 since 1+2+1=4 and could not be a prime.The numbers like 11,101,110,100001 i.e. with 2 occurances of 1 can be easily identified with a simple test.</li>\n<li>You can improve the sum method by taking advantage of the fact that all the numbers you need to find the digit sum are in a sequence.</li>\n</ul>\n\n<p>However all these improvements will improve the performance but it will be still not sufficient if n is very very large.With all the optimizations the time complexity would be still >>>>>>>>>n. Use of DP would be the best approach to solve this problem if you are really interested in O(n) or less.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T10:13:23.973", "Id": "15472", "ParentId": "8319", "Score": "5" } }, { "body": "<p>Instead of checking numbers, check the sets of digits in sorted order. Let's say you are looking for six digit solutions. Sum of squares of digits is at most 6 x 81, so you first create an array bool prime [6*81 + 1] and fill it. Then</p>\n\n<pre><code>for (a = 1; a &lt;= 9; ++a)\n for (b = a; b &lt;= 9; ++b)\n for (c = b; c &lt;= 9; ++c)\n for (d = c; d &lt;= 9; ++d)\n for (e = d; e &lt;= 9; ++e)\n for (f = e; f &lt;= 9; ++f)\n if (prime [a + b + c + d + e + f])\n if (prime [a*a + b*b + c*c + d*d + e*e + f*f)\n print all numbers made from the digits a,b,c,d,e,f. \n</code></pre>\n\n<p>Even if you go up to 19 digit numbers, there are only about 1.5 million combinations of digits to check which should take only a few dozen milliseconds. Finding the numbers is then easy. </p>\n\n<p>Even for 63 digit numbers, there are less than 10 billion combinations of digits to check. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-03T16:01:40.427", "Id": "46202", "ParentId": "8319", "Score": "1" } } ]
{ "AcceptedAnswerId": "8339", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T12:21:28.987", "Id": "8319", "Score": "7", "Tags": [ "java", "optimization", "primes" ], "Title": "Sum of the digits is prime or not" }
8319
A cache is a component that transparently stores data so that future requests for that data can be served faster.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T13:27:44.677", "Id": "8321", "Score": "0", "Tags": null, "Title": null }
8321
<p>I have written this <a href="https://github.com/DarkMantisCS/FileMaker-PHP-API-Interface/blob/master/class.fmdb.php" rel="nofollow">piece of code</a> to help the development of FileMaker developers having to use the dog-awful PHP API.</p> <pre><code>&lt;?php require_once ( 'fm_api/FileMaker.php' ); require_once ( 'config/config.php' ); /** * Interface between the FileMaker API and PHP - Written by RichardC */ class FMDB { /** * Setting up the classwide variables */ protected $fm; protected $layout = ''; protected $debugCheck = true; public $lastObj = null; //Filemaker LessThan/Equal to and GreaterThan/Equal to characters - Does not work in all IDEs public $ltet = '≤'; public $gtet = '≥'; /** Constructor of the class */ public function __construct() { $this-&gt;fm = new FileMaker( FMDB_NAME, FMDB_IP, FMDB_USERNAME, FMDB_PASSWORD ); } /** * Checks whether there is an error in the resource given. * * @param obj $request_object * * @return int */ public static function isError( $request_object ) { $preg = preg_grep( '/^([^*)]*)error([^*)]*)$/', array_keys( $request_object ) ); if( is_array( $request_object ) &amp;&amp; !empty( $preg ) ){ return $preg[0]; } return ( FileMaker::isError( $request_object ) ? $request_object-&gt;getCode() : 0 ); } /** * Just a quick debug function that I threw together for testing * * @param string $func * @param array $arrReturn * @param string $type 'file' || 'console' * * @return mixed */ protected function debug( $func, $arrReturn, $type='file' ){ $debugStr = ''; if( $func == '' || empty( $func ) ){ return ''; } switch( $type ){ case 'default': case 'file': $fo = fopen( DEBUG_LOCATION . '/logFile.txt', 'a+'); foreach( $arrReturn as $k =&gt; $v ){ if( is_array( $v ) ){ foreach( $v as $n =&gt; $m ){ //$debugStr .= '&lt;script type="text/javascript"&gt;console.log("[Debug] ' . $func . ' - ['. $n .'] -&gt; ' . $m . ' ");&lt;/script&gt;'; fwrite( $fo, '[Debug ' . date( 'd-m-Y H:i:s' ) . '] ' . $func . ' - ['. $n .'] -&gt; ' . $m . "\n\r" ); } }else{ //$debugStr .= '&lt;script type="text/javascript"&gt;console.log("[Debug] ' . $func . ' - ['. $k .'] ' . $v . ' ");&lt;/script&gt;'; fwrite( $fo, '[Debug '. date( 'd-m-Y H:i:s' ) . '] ' . $func . ' - ['. $k .'] ' . $v . "\n\r" ); } } fclose( $fo ); return true; break; case 'console': foreach( $arrReturn as $k =&gt; $v ){ if( is_array( $v ) ){ foreach( $v as $n =&gt; $m ){ $debugStr .= '&lt;script type="text/javascript"&gt;console.log("[Debug] ' . $func . ' - ['. $n .'] -&gt; ' . $m . ' ");&lt;/script&gt;'; } }else{ $debugStr .= '&lt;script type="text/javascript"&gt;console.log("[Debug] ' . $func . ' - ['. $k .'] ' . $v . ' ");&lt;/script&gt;'; } } return $debugStr; break; } } /** * Selects data from a FileMaker Layout from the given criteria * * @param string $layout * @param array $arrSearchCriteria * @param bool $xml * * @return array */ public function select( $layout, $arrSearchCriteria ) { $arrOut = array(); if ( ( !is_array( $arrSearchCriteria ) ) ) { return false; } $findReq = $this-&gt;fm-&gt;newFindCommand( $layout ); foreach ( $arrSearchCriteria as $field =&gt; $value ) { $findReq-&gt;addFindCriterion( $this-&gt;fm_escape_string( $field ), $this-&gt;fm_escape_string( $value ) ); } $results = $findReq-&gt;execute(); if ( $this-&gt;isError( $results ) === 0 ) { $fields = $results-&gt;getFields(); $records = $results-&gt;getRecords(); //Set the last used layout and object $this-&gt;layout = $layout; $this-&gt;lastObj = $records; //Loops through the records retrieved $i = 0; foreach ( $records as $record ) { $i++; foreach ( $fields as $field ) { $arrOut[$i]['rec_id'] = $record-&gt;getRecordId(); $arrOut[$i][$field] = $record-&gt;getField( $field ); } } } else { $arrOut['errorCode'] = $this-&gt;isError( $results ); } if( $this-&gt;debugCheck ){ foreach( $arrOut as $k =&gt; $v ){ echo $this-&gt;debug( 'SELECT', array( $k =&gt; $v )); } } return $arrOut; } /** * Sets Fields within a given Layout with the given criteria * * @param array $arrFields * * @example $objFMDB-&gt;setFields(array('fieldName' =&gt; 'ValueToUpdate')); * * @return bool */ public function setFields( $arrFields ) { $blOut = false; if ( ( !is_array( $arrFields ) ) ) { return false; } $layout = ( empty( $layout ) ? ( $this-&gt;layout ) : ( $layout ) ); $records = $this-&gt;lastObj; if ( isset( $records ) &amp;&amp; !empty( $records ) ) { foreach ( $records as $record ) { foreach ( $arrFields as $fieldName =&gt; $value ) { $setFields[] = $record-&gt;setField( $this-&gt;fm_escape_string( $fieldName ), $this-&gt;fm_escape_string( $value ) ); } } $commit = $record-&gt;commit(); if ( $this-&gt;isError( $commit ) === 0 ) { $blOut = true; } else { return $this-&gt;isError( $commit ); } } // Housekeeping unset( $record, $commit, $fieldName, $value ); return $blOut; } /** * Updates a set of fields on a layout where the clauses match * * @param string $layout * @param array $arrFields * @param array $arrSearchCriteria * * @return bool */ public function update( $layout, $arrFields, $arrSearchCriteria ){ //Loop through the parameters and check they are set and not empty foreach( func_get_args() as $arg ){ if( ( $arg == '' ) || ( empty( $arg ) ) ){ return false; } } $findReq = $this-&gt;fm-&gt;newFindCommand( $layout ); foreach ( $arrSearchCriteria as $field =&gt; $value ) { $findReq-&gt;addFindCriterion( $this-&gt;fm_escape_string( $field ), $this-&gt;fm_escape_string( $value ) ); } //Perform the find $result = $findReq-&gt;execute(); if ( $this-&gt;isError( $result ) !== 0 ) { return $this-&gt;isError( $findReq ); } $records = $result-&gt;getRecords(); //Loop through the found records foreach ( $records as $record ) { //Loop through the fields given in the argument and set the fields with the values foreach ( $arrFields as $f =&gt; $v ) { $record-&gt;setField( $this-&gt;fm_escape_string( $f ), $this-&gt;fm_escape_string( $v ) ); } //Commit the setFields $commit = $record-&gt;commit(); if ( $this-&gt;isError( $commit ) !== 0 ) { return $this-&gt;isError( $commit ); } } //Housekeeping unset( $result, $commit, $record, $findReq ); return true; } /** * Updates a record by the given ID of the record on a specified layout * * @param string $layout * @param array $arrFields * @param int $iRecordID * * @return bool */ public function updateRecordByID( $layout, $arrFields, $iRecordID ) { $blOut = false; if ( ( $layout == '' ) || ( !is_array( $arrFields ) ) || ( !is_numeric( $iRecordID ) ) ) { return false; } $findReq = $this-&gt;fm-&gt;getRecordById( $layout, $iRecordID ); if ( $this-&gt;isError( $findReq ) === 0 ) { foreach ( $findReq as $record ) { foreach ( $arrFields as $f =&gt; $v ) { $record-&gt;setField( $this-&gt;fm_escape_string( $f ), $this-&gt;fm_escape_string( $v ) ); } $commit = $record-&gt;commit(); } if ( $this-&gt;isError( $commit ) === 0 ) { $blOut = true; } else { return $this-&gt;isError( $commit ); } } else { return $this-&gt;isError( $findReq ); } unset( $result, $commit, $record, $findReq ); return $blOut; } /** * Inserts a record into the layout * * @param string $layout * @param array $arrFields * * @return bool */ public function insert( $layout, $arrFields ) { $blOut = false; if ( ( $layout == '' ) || ( !is_array( $arrFields ) ) ) { return false; } // Auto-Sanitize the input data foreach ( $arrFields as $field =&gt; $value ) { $fields[$this-&gt;fm_escape_string( $field )] = $this-&gt;fm_escape_string( $value ); } $addCmd = $this-&gt;fm-&gt;newAddCommand( $this-&gt;fm_escape_string( $layout ), $fields ); $result = $addCmd-&gt;execute(); if ( $this-&gt;isError( $result ) === 0 ) { $blOut = true; } else { return $this-&gt;isError( $result ); } unset( $addCmd, $result ); return $blOut; } /** * Gets the layout names within a Database * * @return array */ public function get_layout_names() { return $this-&gt;fm-&gt;listLayouts(); } /** * Alias of 'select' * * @param string $layout * @param array $arrSearchCriteria * * @return array */ public function find( $layout, $arrSearchCriteria ) { return $this-&gt;select( $layout, $arrSearchCriteria ); } /** * Counts the number of items in the given array * * @param array $arrResult * * @return int */ public function fm_num_rows( $arrResult ) { $intOut = 0; if ( is_array( $arrResult ) ) { foreach ( $arrResult as $result ) { $intOut = count( $result ); } } else { $intOut = count( $arrResult ); } return $intOut; } /** * Runs a script on the layout * * @param string $layout * @param string $scriptName * @param array $params (optional) * * @return bool */ public function runScript( $layout, $scriptName, $params = array() ) { if ( ( empty( $layout ) ) || ( empty( $scriptName ) ) ) { return false; } if ( $this-&gt;fm-&gt;newPerformScriptCommand( $layout, $scriptName, $params ) ) { return true; } return false; } /** * Get the ID of the last updated/inserted field * * @return int */ public function getLastID() { } /** * Get the ID of the last updated/inserted field * * @return int */ public function getLastID() { } /** * Deletes a record from the table/layout with the given record ID * * @return bool */ public function deleteRecordByID( $layout, $iRecordID ) { foreach( func_get_args() as $arg ){ if( empty( $arg ) || $arg == '' ){ return false; } } $delete = $this-&gt;fm-&gt;newDeleteCommand( $layout, $iRecordID ); $delResult = $delete-&gt;execute(); if( $this-&gt;isError( $delResult ) ){ return $this-&gt;isError( $delResult ); } unset( $delete, $delResult, $layout, $iRecordID ); return true; } /** * Deletes a record where the search criteria matches * * @param string $layout * @param array $arrSearchCriteria * * @return int The amount of records deleted || errorCode */ public function delete( $layout, $arrSearchCriteria ){ if( empty( $layout ) || empty( $arrSearchCriteria ) ){ return 0; } //Performs the search $search = $this-&gt;select( $layout, $arrSearchCriteria ); if( empty( $search ) ){ return 0; } //Checks for an error if( array_key_exists( 'errorCode', $search ) ){ return $search['errorCode']; } $i = 0; foreach( $search as $records ){ $delete = $this-&gt;deleteRecordByID( $layout, $records['rec_id'] ); // Errors return as strings so thats why the check is to make sure its an integer if( !is_int( $delete ) ){ return $delete; //replace $delete with 0; after testing } $i++; } return $i; } /* * Gets the ID of the record in the last Select * * @return int */ public function getRecordId() { return $this-&gt;lastObj-&gt;getRecordId(); } /** * Escapes a string manually * * @param string $input * * @return string */ public function fm_escape_string( $input ) { if ( is_array( $input ) ) { return array_map( __method__, $input ); } if ( !empty( $input ) &amp;&amp; is_string( $input ) ) { return str_replace( array( '\\', '/', "\0", "\n", "\r", "'", '"', "\x1a", '&lt;', '&gt;' ), array( '\\\\', '\/', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z', '\&lt;\\/', '\\/&gt;' ), $input ); } return $input; } } ?&gt; </code></pre> <p>Please let me know what you think!</p> <p><strong>[Edit]</strong> Ps. Please note that this is still a work in progress.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T15:53:11.107", "Id": "12992", "Score": "0", "body": "Please include all relevant code in your post, as suggested in the [FAQ](http://codereview.stackexchange.com/faq)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T15:55:53.350", "Id": "12993", "Score": "1", "body": "Done. The reason I didn't was because its like 600 lines long :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T16:53:30.493", "Id": "12995", "Score": "0", "body": "I did an unconventional edit on your question, removing `@author`, `@since` and `@version` comments, to prune the code a bit. I'm sure you noticed, since you did a subsequent edit, I'm only bringing it up because as it was rather unconventional I asked a [Meta question](http://meta.codereview.stackexchange.com/questions/453/is-it-appropriate-to-prune-code-blocks-by-editing-out-irrelevant-javadoc-comment) about it and would love to hear what you think." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T17:18:26.663", "Id": "12996", "Score": "0", "body": "Yeah that's nto a problem, I Just posted everything that was in my file. Obviously its good to have DocBlocks in your code, but yeah point taken. Maybe it was right to remove the comment. As for the other post, I think that is a good question! Thanks again!" } ]
[ { "body": "<ol>\n<li><p><code>FMDB</code> - A longer class name would help a lot (as a reader).</p></li>\n<li><p>If the following fields are constants they shouldn't be public fields. I'd give them uppercase names too.</p>\n\n<pre><code>public $ltet = '≤';\npublic $gtet = '≥';\n</code></pre></li>\n<li><p>The following comments look unnecessary:</p>\n\n<pre><code>//$debugStr .= '&lt;script type=\"text/javascript\"&gt;console.log(\"[Debug] ' . $func . ' - ['. $n .'] -&gt; ' . $m . ' \");&lt;/script&gt;';\nfwrite( $fo, '[Debug ' . date( 'd-m-Y H:i:s' ) . '] ' . $func . ' - ['. $n .'] -&gt; ' . $m . \"\\n\\r\" );\n</code></pre>\n\n\n\n<pre><code>//$debugStr .= '&lt;script type=\"text/javascript\"&gt;console.log(\"[Debug] ' . $func . ' - ['. $k .'] ' . $v . ' \");&lt;/script&gt;';\nfwrite( $fo, '[Debug '. date( 'd-m-Y H:i:s' ) . '] ' . $func . ' - ['. $k .'] ' . $v . \"\\n\\r\" );\n</code></pre>\n\n<p>The first part of the string (<code>'[Debug '. date( 'd-m-Y H:i:s' ) . '] ' . $func . '</code>) could be extracted to a common local variable or function.</p></li>\n<li><p><code>fopen</code> and <code>fwrite</code> returns with <code>FALSE</code> on error. You should check this.</p></li>\n<li><p>I'd modify the <code>insert</code> function a little bit:</p>\n\n<pre><code>public function insert( $layout, $arrFields ) {\n if ( ( $layout == '' ) || ( !is_array( $arrFields ) ) ) {\n return false;\n }\n ...\n if ( $this-&gt;isError( $result ) !== 0 ) {\n return $this-&gt;isError( $result );\n }\n ...\n return true;\n}\n</code></pre>\n\n<p>The <code>$blOut</code> variable is unnecessary.</p></li>\n<li><p>Using guard clauses makes the code flatten and more readable. An example from <code>updateRecordByID</code>:</p>\n\n<pre><code>if ( $this-&gt;isError( $findReq ) === 0 ) {\n\n foreach ( $findReq as $record ) {\n foreach ( $arrFields as $f =&gt; $v ) {\n $record-&gt;setField( $this-&gt;fm_escape_string( $f ), $this-&gt;fm_escape_string( $v ) );\n }\n $commit = $record-&gt;commit();\n }\n\n if ( $this-&gt;isError( $commit ) === 0 ) {\n $blOut = true;\n } else {\n return $this-&gt;isError( $commit );\n }\n} else {\n return $this-&gt;isError( $findReq );\n}\n</code></pre>\n\n<p>It could be written like this:</p>\n\n<pre><code>if ( $this-&gt;isError( $findReq ) !== 0 ) {\n return $this-&gt;isError( $findReq );\n}\n\nforeach ( $findReq as $record ) {\n foreach ( $arrFields as $f =&gt; $v ) {\n $record-&gt;setField( $this-&gt;fm_escape_string( $f ), $this-&gt;fm_escape_string( $v ) );\n }\n $commit = $record-&gt;commit();\n}\n\nif ( $this-&gt;isError( $commit ) !== 0 ) {\n return $this-&gt;isError( $commit );\n}\n$blOut = true;\n</code></pre>\n\n<p>References: <em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em>; <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Flattening Arrow Code</a></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T08:58:15.457", "Id": "13043", "Score": "1", "body": "Thank you for your comments. I didn't mean to include the comments (issue 3 that you mentioned) that would have been an accident. As for the rest, I will include this in my next push to github. Thanks again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T21:39:49.123", "Id": "8349", "ParentId": "8331", "Score": "1" } } ]
{ "AcceptedAnswerId": "8349", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T15:16:08.960", "Id": "8331", "Score": "2", "Tags": [ "php", "object-oriented" ], "Title": "FileMaker PHP API Interface" }
8331
<p>Deleting folders programmatically is extremely dangerous. It is enough for somebody else to change a configuration file or constant variable including the target folder's name to, say C:\, and that's it: the workstation is paralyzed!</p> <p>The following suggested methods are to prevent such a situation. Their aim is to wrap the low level, possibly recursive file system operation with the necessary validation and clear facade - look twice, delete once.</p> <p><strong>Delete temporary directory created by current user (non recursive!)</strong></p> <pre><code>/// &lt;summary&gt; /// carefully remove directory and its files /// verify the directory is located under the %temp% /// and it is not e.g. C:\ /// &lt;/summary&gt; /// &lt;param name="dir"&gt;&lt;/param&gt; public static void DeleteTempDirShallow(string dir) { // check if it is an invalid directory path, // e.g. a disk drive or just a bad string if (! Directory.Exists(dir)) return; DirectoryInfo userTempDirInfo = new DirectoryInfo(Path.GetTempPath()); DirectoryInfo dirInfo = new DirectoryInfo(dir); if (dirInfo.FullName.Contains(userTempDirInfo.FullName)) { foreach (FileInfo file in dirInfo.GetFiles()) file.Delete(); dirInfo.Delete(); // just clean up the empty dir } } </code></pre> <p><strong>Delete temporary directory created by current user (recursive!)</strong></p> <pre><code>public static void DeleteTempDirRecursive(string dir) { // check if it is an invalid directory path, // e.g. a disk drive or just a bad string if (! Directory.Exists(dir)) return; DirectoryInfo userTempDirInfo = new DirectoryInfo(Path.GetTempPath()); DirectoryInfo dirInfo = new DirectoryInfo(dir); if (dirInfo.FullName.Contains(userTempDirInfo.FullName)) { dirInfo.Delete(recursive: true); } } </code></pre> <p><strong>Do I try to delete any root or system folder?</strong></p> <pre><code>static List&lt;string&gt; systemDirs = new List&lt;string&gt; { Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles), Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFilesX86), Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms), Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu), Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup), Environment.GetFolderPath(Environment.SpecialFolder.Fonts), Environment.GetFolderPath(Environment.SpecialFolder.NetworkShortcuts), Environment.GetFolderPath(Environment.SpecialFolder.PrinterShortcuts), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), Environment.GetFolderPath(Environment.SpecialFolder.Resources), Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), Environment.GetFolderPath(Environment.SpecialFolder.Startup), Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), Environment.GetFolderPath(Environment.SpecialFolder.Templates), Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), Environment.GetFolderPath(Environment.SpecialFolder.Windows), }; /// &lt;summary&gt; /// check if the argument dir is adisk drive, /// is a system (sub-)folder /// and should not be erased /// &lt;/summary&gt; /// &lt;param name="dir"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static bool IsSystemOrRootDir(string dir) { // check if it is an invalid directory path, // or just a bad string if (! Directory.Exists(dir)) return true; DirectoryInfo dirInfo = new DirectoryInfo(dir); // is it a root (disk drive)? if (dirInfo.Parent == null) return true; bool result = false; systemDirs.ForEach(sysDir =&gt; { result = result || dirInfo.FullName.Contains(sysDir); } ); return result; } </code></pre> <p><strong>References</strong></p> <p><a href="https://stackoverflow.com/a/3525950/1171019">How to check if directory 1 is a subdirectory of dir2 and vice versa</a><br> <a href="https://stackoverflow.com/q/1288718">How to delete all files and folders in a directory?</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T18:46:41.820", "Id": "13002", "Score": "1", "body": "This of course won't prevent the program from deleting the folder that _it's_ running from... or the directory of the CLR either. It's also (at the moment) going to only 'work' on one OS, and potentially only specific versions too (are either of the `System` folders \"System32\"?). That entire list should also be loaded from a resource file, so that it would be customizable. Please note that generally speaking, programs should be running in as restricted a mode as possible, which could mean **OS-level** protection (using UAC)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T09:09:02.490", "Id": "13169", "Score": "0", "body": "hi @X-Zero, the `System` points to the `%windir%` environment variable. The `SystemX86` points to either `%windir%\\System` in win32 or to `%windir%\\System32` in win64. This code is supposed to work on all versions of MS Windows, supporting .NET." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T09:19:23.680", "Id": "13170", "Score": "0", "body": "The CLR directory was located under the `%windir%\\assembly` up to .NET 3.5. The .NET 4.0 has moved the location of the GAC to `%windir%\\Microsoft.NET\\assembly\\GAC*` directories. Both the folders are located under the `Environment.SpecialFolder.System` and the `IsSystemOrRootDir(string dir)` would return true. So this case is covered completely with the code suggested." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T16:49:40.600", "Id": "13228", "Score": "0", "body": "Okay, I'll admit that I missed the 'Contains()', but if you're advocating this as library code, you're only going to frustrate people - expecially if `UserProfile` contains the `Users` directory. What happens if somebody is attempting to use it for resource management (for content creation, say)? You've just disabled the ability to reorganize their work... And when I was speaking of different OSes, I was referencing Mac/Linux, not necessarily just Windows (yes, I know running on those platforms isn't common, but if you're claiming safety, it needs to be safe everywhere)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T14:53:07.727", "Id": "13294", "Score": "0", "body": "X-Zero, I agree about the `UserProfile`. I guess it worth splitting the IsSystemOrRootDir method by adding another IsPersonalRootDir function. Now, about the different OSes, would you like to post some code, portable to them? Is it relevant at all the C# on Mac/Linux?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T16:26:46.947", "Id": "13306", "Score": "0", "body": "I don't happen to know right off what the Mac/Linux equivalents are (linux especially), or that they're necessarily all that relevant. Your basic problem is that the list isn't configurable - it's effectively hardcoded. Were I to use something like this, I'd like to be able to pass in my own list - there's no way for a **library** to know all of **my** important folders. It'd probably be better for you to also set it up as a `whitelist` - it's too easy to delete 'something else' important... which by default is what UAC (on win 7) does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T07:58:40.553", "Id": "15047", "Score": "6", "body": "I don't see the point of this code. If you don't want a directory deleted then don't point it at something that deletes folders. ACLs and ordinary permissions should prevent you from doing the worst damage. And if the caller managed to do that kind of damage they presumably can deal with the consequences (or if not, deserve what they get. :-)) Even if you manage to ignore all that... this code is complex and brittle, pulls randomly from environment variables. I would not call it elegant. You also commit the classic misguided file system race condition of `if (exists) { do something }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T09:18:25.693", "Id": "15210", "Score": "0", "body": "@asveikau thanks for your comment. Would you like to get into details about the following:\n\"classic race condition\" -what is the exact scenario?\n\"this code is complex\" - how would you make it more elegant?\n\"they presumably can deal with the consequences (or if not, deserve what they get.\" - there are possibly multiple developers in the project. I'd like to protect my code from quick and dirty changes in the erasure area.\nthanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T16:24:06.597", "Id": "15252", "Score": "2", "body": "@MichaelG - The classic race condition is thus: Checking for the existence of a file at time `t` says nothing about the existence of a file with that path (or even if it's the same file) at time `t + 1`. The file can be renamed, another one with the same name put in its place, etc. Checking the existence of a file is also not always a quick operation, so in addition to gaining nothing it takes time. The \"right\" way is to just open the file and handle the \"not found\" case if you need to do something different there. As for how to make the code less complex: remove it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T14:47:09.370", "Id": "15345", "Score": "0", "body": "So the race condition is like this: 1. `if (! Directory.Exists(dir)) return true;` 2. `dirInfo.Delete();` 3. what is the worst case? The checked dir has disappeared; but hey, it is not a problem. We anyway wanted it to be deleted!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T16:20:05.253", "Id": "47867", "Score": "0", "body": "@MichaelG - Execuse me, but what the heck is the point of this post?! I see no questions in your post (other than a code example subsection marked as a question, which is not relevant to the post itself). Please ask something specific! Eg: Have I accounted for all possibilites? Have I missed some important folders? (which have been pointed out in previous comments by the way) Is there a better way to go about protecting from wrongful deletion? (again already pointed out, UAC, ACL and others. I would also say only allow deletion in c:\\Users\\<User>\\.... anything else is bad!) etc..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-25T08:33:21.823", "Id": "375629", "Score": "0", "body": "@Marko, this is Code Review - the question is *always* \"How can I improve my code\", and doesn't need to be stated." } ]
[ { "body": "<h2>When all you have is a hammer, every problem looks like a nail.</h2>\n<blockquote>\n<p>You're trying to do something with code, that's not the code's job. <strong>Delete all this code</strong> and tackle the problem at the root: <strong>make sure your code runs with the appropriate permissions</strong>.</p>\n<p>It's that simple.</p>\n<p>-- My humble opinion</p>\n</blockquote>\n<hr />\n<blockquote>\n<p><strong>Deleting folders is a risky business</strong></p>\n</blockquote>\n<p>Indeed! If your running code doesn't have permission to wipe out your hard drive, you have some exceptions to deal with, i.e. you should wrap I/O calls in a <code>try...catch</code> block.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T04:54:01.973", "Id": "57568", "Score": "2", "body": "[I knew that phrase sounded familiar!](http://synoptek.com/Dev-Blog/beware-the-golden-hammer-of-software-development/)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T02:45:09.500", "Id": "35503", "ParentId": "8332", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T15:29:51.777", "Id": "8332", "Score": "6", "Tags": [ "c#", ".net" ], "Title": "Deleting folders is a risky business" }
8332
<p>The following method is designed to return <code>true</code> if it passes all of the rules for a password. Does anyone see a way to improve it? Performance improvements are welcome for sake of education.</p> <p>I already know password rules beside length are counter-productive. It's not my choice. Also, I know that performance is absolutely trivial here. I only care about performance by way of educating myself. The stuff I learn on non-critical optimization often helps me when I do have a bottleneck. I will not be implementing something just because it is faster.</p> <pre><code>/** * Returns true if and only if a password passes the rules: * - Must be at least 8 characters. * - Must contain two of the following types: * - Letters * - Numbers * - Symbols (includes whitespace) * * @param string $password The raw, unencrypted password. * @return bool */ public function isValidPassword($password) { $length = strlen($password); if ($length &lt; 8) { return false; } $foundLetter = false; $foundNumber = false; $foundSymbol = false; for ($i = 0; $i &lt; $length; $i++) { $char = $length[$i]; if (ctype_alpha($char)) { $foundLetter = true; } else if (ctype_digit($char)) { $foundNumber = true; } else if (ctype_punct($char) || ctype_space($char)) { $foundSymbol = true; } } return ($foundLetter &amp;&amp; $foundNumber) || ($foundLetter &amp;&amp; $foundSymbol) || ($foundNumber &amp;&amp; $foundSymbol); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:09:58.567", "Id": "13005", "Score": "0", "body": "a1111111 will pass, is this the intention?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:55:28.353", "Id": "13019", "Score": "1", "body": "Password rules like this (apart from min length) are stupid and counter productive: http://xkcd.com/936/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T21:04:07.930", "Id": "13021", "Score": "0", "body": "@LokiAstari I knew I should have mentioned that I didn't create the rules. In fact I was able to get rid of two of them." } ]
[ { "body": "<p>Should this:</p>\n\n<pre><code> else if (ctype_digit($char)) {\n $foundLetter = true;\n</code></pre>\n\n<p>Not be:</p>\n\n<pre><code> else if (ctype_digit($char)) {\n $foundNumber = true;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:01:18.190", "Id": "13003", "Score": "1", "body": "I believe that's merely a copy-paste error, which is why I tried to edit it; this isn't relevant to his question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:24:20.523", "Id": "13011", "Score": "0", "body": "@seand What do you base that believe on? I can't think of a likely scenario where such an error would be introduced by copy and pasting (though that might just be my lack of imagination, of course). I see no reason to believe that this mistake isn't present in the original code and the OP just didn't test the function extensively." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:40:16.397", "Id": "13014", "Score": "0", "body": "@sepp2k: If I were writing the same code, I would have copied those statements over because they follow a pattern of `$foundX = true;` and just replaced `X`. It probably is an error in the original code but that doesn't change the fact that it's not what he's asking, so it shouldn't be an answer, but rather an edit + comment on the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:42:51.787", "Id": "13015", "Score": "0", "body": "@seand He asked for ways to improve his code. Making the code actually correct is a perfectly valid improvement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:49:26.177", "Id": "13017", "Score": "1", "body": "@seand No, it's not. \"Code correctness\" is actually the first item on the list of on-topic items in the FAQ. What's off topic is posting code you know is wrong and ask people to find your bug. If someone posts code that he believes to be correct and an answerer points out a mistake the OP overlooked, that's perfectly on topic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T21:04:51.580", "Id": "13022", "Score": "1", "body": "It was merely a copy error. I do appreciate your time, though." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T19:58:41.750", "Id": "8342", "ParentId": "8340", "Score": "2" } }, { "body": "<p>Does performance really matter? It seems <a href=\"https://softwareengineering.stackexchange.com/a/80092/36726\">premature optimization</a>.</p>\n\n<p>Actually, I'd rewrite the last part to a more readable form:</p>\n\n<pre><code>$classCount = 0;\nif ($foundLetter) {\n $classCount++;\n}\nif ($foundNumber) {\n $classCount++;\n}\nif ($foundSymbol) {\n $classCount++;\n}\n\nif ($classCount &gt;= 2) {\n return true;\n}\nreturn false;\n</code></pre>\n\n<p>It would be more important and less error-prone if you have more than three character classes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T21:03:44.500", "Id": "13020", "Score": "0", "body": "No, performance does not matter. For the love of everything good and sane, I said, \"Performance improvements are welcome for sake of education.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T21:10:54.020", "Id": "13024", "Score": "0", "body": "I am not an idiot. This is in NO way a bottleneck. That doesn't mean its performance cannot be improved. I ask for performance improvements for my education only. That doesn't mean I'm going to implement a faster performing code just because its faster." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:28:38.957", "Id": "8345", "ParentId": "8340", "Score": "2" } }, { "body": "<p>Your solution does not honor multibyte characters, i.e. it will probably break for non-English languages.</p>\n\n<p>Instead you could utilize PCRE (regular expressions) and Unicode character grounps:</p>\n\n<pre><code>$foundLetter = preg_match('(\\pL)u', $password);\n$foundNumber = preg_match('(\\pN)u', $password);\n$foundSymbol = preg_match('(???)u', $password);\n</code></pre>\n\n<p>Not sure what you define as a symbol, <code>[\\pP\\p{Xps}]</code> (Punctuation + Whitespace) would reflect your current version (I think). Maybe a better alternative would be <code>[^\\pL\\pN]</code> though, which just ensures one non alphanumeric letter.</p>\n\n<p>In theory you could change your script into a one liner now:</p>\n\n<pre><code>return strlen($password) &gt;= 8 &amp;&amp; (\n preg_match('(\\pL)u', $password)\n + preg_match('(\\pN)u', $password)\n + preg_match('([^\\pL\\pN])u', $password)\n) &gt;= 2;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T21:20:57.920", "Id": "13026", "Score": "2", "body": "*This* is the kind of feedback I'd like to see. Thanks, NikiC." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-13T05:47:43.757", "Id": "357677", "Score": "0", "body": "Or an even shorter single-call 1-liner: `return preg_match('^(?.*(\\pL)u)(?=.*(\\pN)u)(?=.*([^\\pL\\pN])u).{8,}', $password)`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T21:20:03.833", "Id": "8347", "ParentId": "8340", "Score": "4" } } ]
{ "AcceptedAnswerId": "8347", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T19:32:29.530", "Id": "8340", "Score": "5", "Tags": [ "php", "performance", "validation" ], "Title": "Validating password rules" }
8340
<p>I just finished chasing a <a href="http://en.wikipedia.org/wiki/Heisenbug" rel="nofollow">Heisenbug</a> that was entirely my fault. I'd like to avoid it happening again.</p> <p>I have a function which formats a date to a certain preset format. Turns out I was not allocating enough space:</p> <pre><code>char* FormatDate(DT dateTime) { char* formattedDate; formattedDate = (char*)malloc( 6 //That was my bug, I had 5. For the record, I forgot a comma, not the terminal null... + numlen(dateTime.Year) + numlen(dateTime.Month) + numlen(dateTime.Day) + numlen(dateTime.Hour) + numlen(dateTime.Minute) + numlen(dateTime.Second) ); sprintf(formattedDate,"%d,%d,%d,%d,%d,%d", dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second); return formattedDate; } </code></pre> <p><code>numlen</code> calculates the number of characters the number would take if printed in "%d" format.</p> <p>And yes, the calling function has the duty to free the response.</p> <p>What I'd like to know is how to avoid having the hardcoded <code>6</code>, which arguably could change. <code>sprintf</code> does return the numbers of characters written, but that's a lot like the chicken and the egg... Is there another approach with pre-allocating that's safe? And not, say allocate a space of 250 just to make sure anything fits.</p>
[]
[ { "body": "<p>It appears that if have access to the standard library version of snprintf you can do this:</p>\n\n<pre><code>char* FormatDate(DT dateTime)\n{\n size_t needed = snprintf(NULL, 0,\"%d,%d,%d,%d,%d,%d\", dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second);\n char* formattedDate = (char*)malloc(needed);\n snprintf(formattedDate, needed,\"%d,%d,%d,%d,%d,%d\", dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second);\n return formattedDate;\n}\n</code></pre>\n\n<p>Original source obtained from StackOverflow</p>\n\n<pre><code>char* get_error_message(char const *msg) {\n size_t needed = snprintf(NULL, 0, \"%s: %s (%d)\", msg, strerror(errno), errno);\n char *buffer = malloc(needed);\n snprintf(buffer, needed, \"%s: %s (%d)\", msg, strerror(errno), errno);\n return buffer;\n}\n</code></pre>\n\n<p>Copied from <a href=\"https://stackoverflow.com/questions/1775403/using-snprintf-to-avoid-buffer-overruns\">https://stackoverflow.com/questions/1775403/using-snprintf-to-avoid-buffer-overruns</a> but duplicated to make finding answers quicker.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:09:12.977", "Id": "13004", "Score": "0", "body": "Shouldn't you allocate `needed+1`? I'm using Visual Studio 2005, it doesn't think it has `snprintf`. It does have sprintf, though. I like the approach of sending it to null. I think I'll go with that (if `sprintf` supports it)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:13:00.637", "Id": "13006", "Score": "0", "body": "If I remember that version of MSVC has _snprintf and it works differently than the standard library version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:19:37.267", "Id": "13008", "Score": "0", "body": "Yup, found `_snprintf`. Works, but I don't know what's different." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:21:49.670", "Id": "13009", "Score": "0", "body": "I cannot say for sure it is, but I remember reading it would sometimes not null terminate. If your tests pass then no worries." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:24:06.300", "Id": "13010", "Score": "1", "body": "That's not reassuring." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:01:22.043", "Id": "8343", "ParentId": "8341", "Score": "3" } } ]
{ "AcceptedAnswerId": "8343", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T19:44:59.647", "Id": "8341", "Score": "3", "Tags": [ "c", "memory-management" ], "Title": "Space to allocate before sprintf" }
8341
<p>This is my first attempt at a jQuery plugin. If someone could help me make sure that the code is clean, efficient, and formated correctly I would really appreciate it.</p> <p><strong>Background</strong></p> <p>So the reason I wrote this plugin is because I cannot find an easy to use code that has already been written. Plus, many people who work with a Learning Management System could utilize this without any effort on their part. All the communication with the LMS happens within the plugin, so they don't have to really learn the process of AICC communication. The only requirement to use this plugin is, the developer will have to know what AICC variables the LMS uses. These variables are set in stone by LMS and will not change per user ... everyone will have to use the same variables.</p> <p><strong>LMS Process</strong></p> <p><strong>Step 1</strong>. User starts the course (a <code>$.get()</code> method is used to see if any information was previously stored. If so, load the information.)</p> <p><strong>Step 2</strong>. As the user traverses the course you post information to the LMS and store the pages already viewed so you can have them start where they left off if they leave.(AKA Bookmarking)</p> <p><strong>Step 3</strong>. After the user finishes the course you <code>$.post()</code> the information to the LMS and mark the course as passed.</p> <p>So the process is pretty straight forward, the only thing is the callback from the server is in straight text and that cannot be changed, so you are stuck using the format the LMS returns.</p> <p><strong>What I am looking for</strong></p> <p>What I would like is for everyone to look at the plug and see if its the best it could be and if not offer some type off feedback. This plugin works very good, but is it efficient?</p> <p>Here is my code, I will show the plugin code first then the HTML</p> <p><strong>jquery.aicc.js</strong></p> <pre><code>(function($) { $.extend( { aicc:function(p) { var _sid = getUrlVar('AICC_SID'); var _url = getUrlVar('AICC_URL'); var _action =(p['action']=='set')?setAICC(p['score'],p['time'],p['credit'],p['location'],p['status']):(p['action']=='get')?getAICC():false; function getUrlVar(urlVar) { var match = RegExp('[?&amp;]' + urlVar + '=([^&amp;]*)').exec(window.location.search); return unescape(match &amp;&amp; decodeURIComponent(match[1].replace(/\+/g, ' '))); } function setAICC(s,t,c,l,ls,c) { $.post(_url,{command:"PutParam",version:"2.2",session_id:_sid, aicc_data:"[CORE]\nlesson_location="+l+"\ncredit="+c+"\nscore="+s+"\ntime="+t+"\nlesson_status="+ls},function(r) { p['response'].call(this,json(r)); }) .error(function(a,b,c){p['response'].call(this,c);}); } function getAICC() { $.get(_url,{command:"GetParam",version:"2.2",session_id:_sid},function(r) { p['response'].call(this,json(r)); }) .error(function(a,b,c){p['response'].call(this,c);}); } function json(str) { var obj = {}; str.replace(/([^=]+)=(.*)\n/g,function(_,name,value){obj[name]=value;}); return obj; } } }); })(jQuery); </code></pre> <p><strong>index.html</strong></p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/transitional.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"&gt; &lt;title&gt;jQuery Plugin Testing Portal&lt;/title&gt; &lt;script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script language="javascript" src="library/jquery.aicc.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(function() { /* sets aicc information */ $('#setBtn').click(function() { $.aicc( { action:'set', score:'83', time:'00:00:00', credit:'C', location:'page_1', status:'Incomplete', response:function(r) { alert(r['ERROR']); alert(r['ERROR_TEXT']); alert(r['VERSION']); } }); }); /* gets ALL aicc information (returns in JSON format */ $('#getBtn').click(function() { $.aicc( { action:'get', response:function(r) { alert(r['ERROR']); alert(r['ERROR_TEXT']); alert(r['VERSION']); alert(r['AICC_DATA']); alert(r['STUDENT_ID']); alert(r['STUDENT_NAME']); alert(r['SCORE']); alert(r['TIME']); alert(r['CREDIT']); alert(r['LESSON_LOCATION']); alert(r['LESSON_STATUS']); } }); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;button id="setBtn"&gt;Set AICC&lt;/button&gt; &lt;button id="getBtn"&gt;Get AICC&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Note: When the user is logged into the LMS and is taking the course, there are variables in the URL that the plugin grabs:</p> <p><a href="http://www.lms.com/?AICC_SID=C0000000M00000S&amp;AICC_URL=https%3a%2f%2fwww%2elms%2ecom%2fplateau%2fPwsAicc" rel="nofollow">http://www.lms.com/?AICC_SID=C0000000M00000S&amp;AICC_URL=https%3a%2f%2fwww%2elms%2ecom%2fplateau%2fPwsAicc</a></p> <p>Here is the callback from the LMS on the <code>$.post()</code> and <code>$.get()</code>. (This is all text with each line ending with <code>\n</code>.)</p> <pre><code>ERROR=0 ERROR_TEXT=Successful VERSION=2.2 AICC_DATA=[CORE] STUDENT_ID=0123456 STUDENT_NAME=Doe, John R SCORE=83 TIME=02:35:37 CREDIT=C LESSON_LOCATION=page_1 LESSON_STATUS=INCOMPLETE [Core_Lesson] [Objectives_Status] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-19T14:54:16.707", "Id": "20686", "Score": "0", "body": "first thing : Thank you trying to help Aicc users :) Do you have follow the Lars-Erik's advices ? I'm working on a scorm project and i could give you help to get a \"jquery-Friendly\" version. Anyway : thanks again !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T16:44:18.693", "Id": "20952", "Score": "0", "body": "Hello Niorgen, I did follow his advice and totally reconstructed the plugin. If you are interested in seeing what it does just follow this link ->http://forum.aicc.org/cgi-bin/yabb2/YaBB.pl?num=1330364068/0" } ]
[ { "body": "<p>I don't immediately see any efficiency issues with your code. It's simple and concise.\nBut I do notice that you don't follow all the best practices for plugin authoring described here:</p>\n\n<p><a href=\"http://docs.jquery.com/Plugins/Authoring\" rel=\"nofollow\">http://docs.jquery.com/Plugins/Authoring</a></p>\n\n<p>I guess you'll do something else than alerting ten times in production? ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T17:11:01.567", "Id": "13063", "Score": "0", "body": "Thanks for taking a look, yeah I see what you are saying. I actually have been following a jQuery Plugin tutorial I found via Google. After reading your link, I see what I need to do. That is exactly what I wanted someone to confirm, so I am going to mark this as answered because your link provides me with what changes I need. Thanks again :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T09:56:24.900", "Id": "8356", "ParentId": "8352", "Score": "2" } } ]
{ "AcceptedAnswerId": "8356", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T00:36:48.163", "Id": "8352", "Score": "4", "Tags": [ "javascript", "jquery", "html" ], "Title": "Learning Management System/AICC project" }
8352
<p>I was finding myself frequently calling <code>getApplication()</code> and casting it as <code>MyApplication</code> so that I could call a method in <code>MyApplication</code>. I decided to declare the static variable <code>Current</code> in <code>MyApplication</code> and set it in the constructor. Now I don't have to do the casting.</p> <p>Are there any pitfalls to taking this approach?</p> <pre><code>public class MyApplication extends Application { public static MyApplication Current; public MyApplication(){ super(); Current = this; } public void doSomething(){ } } public class MyActivity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyApplication.Current.doSomething(); } } </code></pre> <p>Below is, I think, the normal approach for getting the application and calling the method.</p> <pre><code>public class MyApplication extends Application { public void doSomething(){ } } public class MyActivity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((MyApplication)getApplication()).doSomething(); } } </code></pre>
[]
[ { "body": "<p>With this solution there is a danger that somebody accidentally change <code>MyApplication.current</code> to <code>null</code> or an invalid reference.</p>\n\n<p>I'd override the <code>getApplication</code> method in the <code>MyActivity</code> class with a <a href=\"http://en.wikipedia.org/wiki/Covariant_return_type\" rel=\"nofollow\">covariant return type</a>:</p>\n\n<pre><code>@Override\npublic MyApplication getApplication() {\n return (MyApplication) super.getApplication();\n}\n</code></pre>\n\n<hr>\n\n<p>According to the <a href=\"http://www.oracle.com/technetwork/java/codeconv-138413.html\" rel=\"nofollow\">Code Conventions for the Java Programming Language</a>, <code>Current</code> should be <code>current</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T12:10:36.927", "Id": "13047", "Score": "0", "body": "Couldn't he also just put that getApplication() method on MyApplication, like MyApplication.getCurrent()?\nPoint, as you say, is to provide read only access to the instance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T12:29:10.977", "Id": "13048", "Score": "0", "body": "I'm not too familiar with Android and I could imagine some situation when `super.getApplication()` returns a proxy or wrapper class instead of the direct reference to the `MyApplication` instance. I don't know it is possible or not. On the other hand, static fields usually makes testing harder, so I try to avoid them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T12:44:52.080", "Id": "13049", "Score": "0", "body": "Well, in this case MyApplication is obviously intended to be a single instance, so changing the \"Current\" member to private and exposing a static getter shouldn't be an issue imho. But I don't know Android either, so add a pinch of salt. (aren't more or less all mobile apps single instanced?)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T08:40:50.353", "Id": "8355", "ParentId": "8353", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T01:47:50.887", "Id": "8353", "Score": "3", "Tags": [ "java", "android", "static" ], "Title": "Static variable Current in Application" }
8353
<p>I'm fairly new to Python and currently building a small application to record loans of access cards to people in a company. I'm using wxPython for the GUI and SQLAlchemy for the CRUD. I'm loosely following <a href="http://www.blog.pythonlibrary.org/2011/11/10/wxpython-and-sqlalchemy-an-intro-to-mvc-and-crud/" rel="nofollow">Mike Driscoll's tutorial for a similar application</a> but I want to add some extra things that he hasn't implemented (he has most controls in the same window, but I'm passing things a lot between dialogues and windows and it's starting to look messy).</p> <p>Particularly concerned about the following method in <code>dialogs.py</code>:</p> <pre><code>def OnCardReturn(self, event): """ Call the controller and get back a list of objects. If only one object return then set that loan as returned. If none returned then error, no loans currently on that card. If more than one returned something has gone wrong somewhere, but present a list of the loans against that card for the user to pick the correct one to return. """ value = self.txtInputGenericNum.GetValue() loans = controller.getQueriedRecords(self.session, "card", value) #returns a list of objects numLoans = len(loans) if numLoans == 1: controller.returnLoan(self.session, value) #returns nothing successMsg = "Card " + str(value) + " has been marked as returned" showMessageDlg(successMsg, "Success!") elif numLoans == 0: failureMsg = "Card " + str(value) + " is not currently on loan" showMessageDlg(failureMsg, "Failed", flag="error") elif numLoans &gt; 1: failureMsg = """ More than one loan for " + str(value) + " exists. Please select the correct loan to return from the next screen. """ showMessageDlg(failureMsg, "Failed", flag="error") selectReturnLoan = DisplayList(parent=self, loanResults=loans, returnCard=True) selectReturnLoan.ShowModal() selectReturnLoan.Destroy() </code></pre> <p>The controller is still under construction, so no complete code yet, but I've commented in what is returned by the calls to it so it's still possible to see what the functionality is.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-17T20:59:32.670", "Id": "134446", "Score": "2", "body": "Hi, I removed the external links are broken as of today. If you still have those scripts somewhere online, please re-add the working links. Btw, any code you want reviewed should be included in the post itself (and now you see the reason for that)." } ]
[ { "body": "<p>Inline comments should only be used sparingly, and definitely not on already long lines. Your <code>#returns a list of objects</code> is pretty unnecessary both because it's overly long, but also because it's inferrable and doesn't seem to matter. You only pass the <code>loans</code> on unchanged so the user doesn't care that they're a list of objects. You can infer that it's a collection of something because of the name <code>loans</code> and the <code>len</code> usage. And that's all you need to know in this function, so forget that comment.</p>\n\n<p>You should also format your docstring so it contains just one line summarising the function, a blank line and then the further details. You just have one long block but it's hard to read from it what the function should do. Instead you detail the possible results.</p>\n\n<p>Instead of using <code>str</code> and concatenation, just use <code>str.format</code>. It's a convenient way of formatting strings and coverting their type at the same time:</p>\n\n<pre><code> successMsg = \"Card {} has been marked as returned\".format(value)\n</code></pre>\n\n<p>Also note that you haven't correctly inserted this value in the <code>failureMsg</code> of <code>numLoans &gt; 1</code>. You just have the string literal <code>\" + str(value) + \"</code>. You'd need the extra quotation marks to do it your way:</p>\n\n<pre><code> failureMsg = \"\"\"\n More than one loan for \"\"\" + str(value) + \"\"\" exists. Please select\n the correct loan to return from the next screen.\n \"\"\"\n</code></pre>\n\n<p>But instead I'd suggest using <code>str.format</code> again.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-28T09:52:13.120", "Id": "108984", "ParentId": "8358", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T13:33:22.380", "Id": "8358", "Score": "6", "Tags": [ "python", "beginner", "mvc" ], "Title": "Recording loans of access cards to people in a company" }
8358
<p>I am relatively inexperienced with MySQL and have a query, which to my eyes appears relatively complex: </p> <pre><code>SELECT SQL_CALC_FOUND_ROWS songsID, song_name, artist_band_name, author, song_artwork, song_file, genre, song_description, uploaded_time, emotion, tempo, user, happiness, instruments, similar_artists, play_count, projects_count, rating, ratings_count, waveform, datasize, display_name, user_url, genre_id, IF(user_ratings_count, 'User Voted', 'Not Voted') as voted FROM ( SELECT sp.songsID, projects_count, AVG(rating) as rating, COUNT(rating) AS ratings_count, COUNT(IF(userid=$userid, 1, NULL)) as user_ratings_count FROM ( SELECT songsID, COUNT(*) as projects_count FROM $sTable s LEFT JOIN $sTable2 p ON s.songsID = p.songs_id GROUP BY songsID) as sp LEFT JOIN $sTable3 r ON sp.songsID = r.songid GROUP BY sp.songsID) as spr JOIN $sTable s USING (songsID) LEFT JOIN $sTable5 q ON s.user = q.ID LEFT JOIN ( SELECT g.song_id, GROUP_CONCAT(g.genre_id SEPARATOR ',') as genre_id FROM $sTable6 g JOIN $sTable h ON h.songsID = g.song_id GROUP by h.songsID) as gs ON s.songsID = gs.song_id </code></pre> <p>Essentially, this query collects data from several different tables about a list of songs:</p> <ul> <li>The song table itself is <code>$sTable</code> with the other tables containing various related information such as ratings, projects, uploaded user information etc.</li> <li>The final part of the query collects a comma-separated list of <code>genre_id</code>s from <code>$sTable6</code>.</li> <li>The <code>WHERE</code> clause is dynamically generated depending on what the user is filtering upon.</li> </ul> <p>I am specifically concerned about the fact that I am currently dynamically generating the <code>WHERE</code> clause when a user wants to search by <code>genre_id</code>, by looping through a string of comma-separated <code>genre_id</code>s and building the <code>WHERE</code> clause like so:</p> <pre><code>WHERE genre_id LIKE '%6%' OR genre_id LIKE '%3%' OR genre_id LIKE '%8%' </code></pre> <p>This strikes me as inefficient but given the dynamic nature of this specific app I have been unable to come up with a different solution that compares directly using '<code>=</code>'.</p> <p>Therefore, this is actually two questions in one:</p> <ol> <li><p>Is there any way to improve the performance of this query overall (any comments on on index schemes or a way of simplifying the query itself are most welcome)?</p></li> <li><p>Is there a better way of performing the dynamic <code>WHERE</code> clause so the database doesn't have to use <code>LIKE</code> searching through comma separated strings?</p></li> </ol> <p>The table in question, <code>$sTable6</code>, is simply a link table for a many-to-many relationship:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>$stable (songs) $stable6 (genres_link) $sTable7 (genres) songsID* genre_id** genre_id** column song_id* genre_name column icon_url etc.... column column </code></pre> </blockquote> <p><code>$sTable 7</code> is not used in the above query at all and does not need to be.</p> <p>I get the following returned via MySQL <code>EXPLAIN</code> when using a simple 2 genre_id <code>WHERE</code> clause (with only 9 rows of songs in total, I will be testing large datasets soon).</p> <blockquote> <pre class="lang-none prettyprint-override"><code>id select_type table type possible_keys key key_len ref rows Extra 1 PRIMARY &lt;derived4&gt; ALL NULL NULL NULL NULL 2 Using where 1 PRIMARY &lt;derived2&gt; ALL NULL NULL NULL NULL 9 Using where; Using join buffer 1 PRIMARY s eq_ref PRIMARY PRIMARY 4 gs.song_id 1 1 PRIMARY q eq_ref PRIMARY PRIMARY 8 songbanc_cms.s.user 1 4 DERIVED g index PRIMARY PRIMARY 8 NULL 6 Using index; Using temporary; Using filesort 4 DERIVED h eq_ref PRIMARY PRIMARY 4 songbanc_cms.g.song_id 1 Using index 2 DERIVED &lt;derived3&gt; ALL NULL NULL NULL NULL 9 Using temporary; Using filesort 2 DERIVED r ref PRIMARY PRIMARY 4 sp.songsID 2 Using index 3 DERIVED s index NULL PRIMARY 4 NULL 2 Using index 3 DERIVED p ref songs_id songs_id 4 songbanc_cms.s.songsID 4 Using index </code></pre> </blockquote>
[]
[ { "body": "<p>I don't know is it help or not (since it's a really complicated query) but it's usually worth caching computed values such as <code>rating</code> and <code>ratings_count</code> and updating them once a day or an hour for example. In the majority of the cases it's enough to provide non-real-time data to the users.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T15:39:37.277", "Id": "13054", "Score": "0", "body": "Good point palacsint, thanks, that will definitely help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-24T15:27:50.763", "Id": "103787", "Score": "1", "body": "In addition to @palacsint, I usually fire a DDBB trigger to do this kind of taks, as adding number of votes, add/substract pictures in a gallery, etc." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T15:36:29.790", "Id": "8364", "ParentId": "8359", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T14:07:40.610", "Id": "8359", "Score": "3", "Tags": [ "performance", "sql", "mysql" ], "Title": "Song database query" }
8359
<p>I been working on getting the <code>SocketAsyncEventArgs</code> to work the way I want it to work. Now I was wondering: is this going to work how it should work?</p> <pre><code>/// &lt;summary&gt; /// The settings to use with this ServerSocket. /// &lt;/summary&gt; ServerSocketSettings Settings; /// &lt;summary&gt; /// The buffer manager for allocation a buffer block to a SocketAsyncEventArgs. /// &lt;/summary&gt; BufferManager BufferManager; /// &lt;summary&gt; /// The semaphore used for controlling the max connections to the server. /// &lt;/summary&gt; SemaphoreSlim MaxConnectionsEnforcer; /// &lt;summary&gt; /// The socket used for listening for incoming connections. /// &lt;/summary&gt; Socket ListenSocket; /// &lt;summary&gt; /// The pool of re-usable SocketAsyncEventArgs for accept operations. /// &lt;/summary&gt; SocketAsyncEventArgsPool PoolOfAcceptEventArgs; /// &lt;summary&gt; /// The pool of re-usable SocketAsyncEventArgs for receiving data. /// &lt;/summary&gt; SocketAsyncEventArgsPool PoolOfRecEventArgs; /// &lt;summary&gt; /// The pool of re-usable SocketAsyncEventArgs for sending data. /// &lt;/summary&gt; SocketAsyncEventArgsPool PoolOfSendEventArgs; /// &lt;summary&gt; /// Initializes a new instance of the Non-blocking I/O ServerSocket. /// &lt;/summary&gt; /// &lt;param name="settings"&gt;The settings to use with this ServerSocket.&lt;/param&gt; public ServerSocket(ServerSocketSettings settings) { this.Settings = settings; this.BufferManager = new BufferManager((this.Settings.BufferSize * this.Settings.NumOfSaeaForRec) + (this.Settings.BufferSize * this.Settings.NumOfSaeaForSend) * this.Settings.OpsToPreAllocate, this.Settings.BufferSize * this.Settings.OpsToPreAllocate); this.PoolOfAcceptEventArgs = new SocketAsyncEventArgsPool(this.Settings.MaxSimultaneousAcceptOps); this.PoolOfRecEventArgs = new SocketAsyncEventArgsPool(this.Settings.NumOfSaeaForRec); this.PoolOfSendEventArgs = new SocketAsyncEventArgsPool(this.Settings.NumOfSaeaForSend); this.MaxConnectionsEnforcer = new SemaphoreSlim(this.Settings.MaxConnections, this.Settings.MaxConnections); } internal void Init() { this.BufferManager.InitBuffer(); for (int i = 0; i &lt; this.Settings.MaxSimultaneousAcceptOps; i++) { SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs(); acceptEventArg.Completed += new EventHandler&lt;SocketAsyncEventArgs&gt;(AcceptEventArg_Completed); this.PoolOfAcceptEventArgs.Push(acceptEventArg); } // receive objs for (int i = 0; i &lt; this.Settings.NumOfSaeaForRec; i++) { SocketAsyncEventArgs eventArgObjectForPool = new SocketAsyncEventArgs(); this.BufferManager.SetBuffer(eventArgObjectForPool); eventArgObjectForPool.Completed += new EventHandler&lt;SocketAsyncEventArgs&gt;(IO_ReceiveCompleted); eventArgObjectForPool.UserToken = new Connection(null, this); this.PoolOfRecEventArgs.Push(eventArgObjectForPool); } // send objs for (int i = 0; i &lt; this.Settings.NumOfSaeaForSend; i++) { SocketAsyncEventArgs eventArgObjectForPool = new SocketAsyncEventArgs(); this.BufferManager.SetBuffer(eventArgObjectForPool); eventArgObjectForPool.Completed += new EventHandler&lt;SocketAsyncEventArgs&gt;(IO_SendCompleted); eventArgObjectForPool.UserToken = new SendDataToken(); this.PoolOfSendEventArgs.Push(eventArgObjectForPool); } } public void StartListen() { this.ListenSocket = new Socket(this.Settings.Endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); this.ListenSocket.Bind(this.Settings.Endpoint); this.ListenSocket.Listen(this.Settings.Backlog); } internal void StartAccept() { SocketAsyncEventArgs acceptEventArgs; if (this.PoolOfAcceptEventArgs.TryPop(out acceptEventArgs)) { this.MaxConnectionsEnforcer.Wait(); bool willRaiseEvent = this.ListenSocket.AcceptAsync(acceptEventArgs); if (!willRaiseEvent) { ProcessAccept(acceptEventArgs); } } } private void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e) { ProcessAccept(e); } private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs) { if (acceptEventArgs.SocketError != SocketError.Success) { HandleBadAccept(acceptEventArgs); return; } StartAccept(); SocketAsyncEventArgs recEventArgs; if (this.PoolOfRecEventArgs.TryPop(out recEventArgs)) { ((Connection)recEventArgs.UserToken).Socket = acceptEventArgs.AcceptSocket; acceptEventArgs.AcceptSocket = null; this.PoolOfAcceptEventArgs.Push(acceptEventArgs); StartReceive(recEventArgs); } else { HandleBadAccept(acceptEventArgs); throw new InvalidOperationException("We starved the receive pool for objects, make sure it matches the max connections."); } } private void IO_SendCompleted(object sender, SocketAsyncEventArgs e) { ProcessSend(e); } private void IO_ReceiveCompleted(object sender, SocketAsyncEventArgs e) { ProcessReceive(e); } private void StartReceive(SocketAsyncEventArgs receiveEventArgs) { Connection token = (Connection)receiveEventArgs.UserToken; bool willRaiseEvent = token.Socket.ReceiveAsync(receiveEventArgs); if (!willRaiseEvent) { ProcessReceive(receiveEventArgs); } } private void ProcessReceive(SocketAsyncEventArgs receiveEventArgs) { Connection con = (Connection)receiveEventArgs.UserToken; if (receiveEventArgs.BytesTransferred &gt; 0 &amp;&amp; receiveEventArgs.SocketError == SocketError.Success) { // NEED TO ADD RECEIVE DATA HERE ETC StartReceive(receiveEventArgs); } else { CloseClientSocket(receiveEventArgs); ReturnReceiveSaea(receiveEventArgs); } } public void SendData(Socket socket, byte[] data) { SocketAsyncEventArgs sendEventArgs; this.PoolOfSendEventArgs.TryPop(out sendEventArgs); SendDataToken token = (SendDataToken)sendEventArgs.UserToken; token.DataToSend = data; sendEventArgs.AcceptSocket = socket; StartSend(sendEventArgs); } private void StartSend(SocketAsyncEventArgs sendEventArgs) { SendDataToken token = (SendDataToken)sendEventArgs.UserToken; if (token.SendBytesRemainingCount &lt;= this.Settings.BufferSize) { sendEventArgs.SetBuffer(sendEventArgs.Offset, token.SendBytesRemainingCount); Buffer.BlockCopy(token.DataToSend, token.BytesSentAlreadyCount, sendEventArgs.Buffer, sendEventArgs.Offset, token.SendBytesRemainingCount); } else { sendEventArgs.SetBuffer(sendEventArgs.Offset, this.Settings.BufferSize); Buffer.BlockCopy(token.DataToSend, token.BytesSentAlreadyCount, sendEventArgs.Buffer, sendEventArgs.Offset, this.Settings.BufferSize); } bool willRaiseEvent = sendEventArgs.AcceptSocket.SendAsync(sendEventArgs); if (!willRaiseEvent) { ProcessSend(sendEventArgs); } } private void ProcessSend(SocketAsyncEventArgs sendEventArgs) { SendDataToken token = (SendDataToken)sendEventArgs.UserToken; if (sendEventArgs.SocketError == SocketError.Success) { token.SendBytesRemainingCount = token.SendBytesRemainingCount - sendEventArgs.BytesTransferred; if (token.SendBytesRemainingCount == 0) { token.Reset(); this.PoolOfSendEventArgs.Push(sendEventArgs); } else { token.BytesSentAlreadyCount += sendEventArgs.BytesTransferred; StartSend(sendEventArgs); } } else { token.Reset(); CloseClientSocket(sendEventArgs); ReturnSendSaea(sendEventArgs); } } private void CloseClientSocket(SocketAsyncEventArgs args) { Connection con = (Connection)args.UserToken; try { con.Socket.Shutdown(SocketShutdown.Both); } catch (Exception) { } con.Socket.Close(); con.OnConnectionClose(); } private void ReturnReceiveSaea(SocketAsyncEventArgs args) { this.PoolOfRecEventArgs.Push(args); this.MaxConnectionsEnforcer.Release(); } private void ReturnSendSaea(SocketAsyncEventArgs args) { this.PoolOfSendEventArgs.Push(args); } private void HandleBadAccept(SocketAsyncEventArgs acceptEventArgs) { acceptEventArgs.AcceptSocket.Close(); this.PoolOfAcceptEventArgs.Push(acceptEventArgs); } internal void Shutdown() { this.ListenSocket.Shutdown(SocketShutdown.Receive); this.ListenSocket.Close(); DisposeAllSaeaObjects(); } private void DisposeAllSaeaObjects() { this.PoolOfAcceptEventArgs.Dispose(); this.PoolOfSendEventArgs.Dispose(); this.PoolOfRecEventArgs.Dispose(); } </code></pre> <p>Is it OK to have 1 receive operation looping and receiving data, but having a pool of multiple send operations? The reason behind this is because I don't want to send data straight after a receive. I want to send data when I wish to, but for receive operations its different, I want it to loop constantly accepting data for a client. Is this going to be FAST and effective?</p> <p>The only thing I need to handle now is receiving data properly with this code and decoding the data.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T13:09:10.097", "Id": "74282", "Score": "2", "body": "I have found that reuse of the SAEA at extreme rates can actually cause the CLR to fail because of the underlying buffer. I would recommend using a queue of SAEA and process them one after the other. It could have been my approach, or system, but thought i'd flag it for you anyway! If you want to see how I implemented shout back and I will drop a link to you :)" } ]
[ { "body": "<p>Just a couple observations, unfortunately not directly related to your primary concerns but still [hopefully] valuable input from a code review perspective:</p>\n\n<ul>\n<li>The class is <em>tightly coupled</em> with several other classes. This may or may not be problematic, just thought I'd point it out - I consider instantiating objects as a concern on its own, I don't like having <code>new</code> instructions all over my code, so I'd try to move these instructions outside the class if possible.</li>\n<li><code>Init()</code> has too many responsibilities, I would extract 3 methods from that code (one for each loop).</li>\n<li><code>SocketAsyncEventArgs.UserToken</code> is an <code>object</code>, for convenience. It seems you're <em>sometimes</em> putting a <code>Connection</code> in there, and other times a <code>SendDataToken</code>. This is likely to get confusing and result in <code>InvalidCastException</code> occurrences as the code gets maintained and evolves.</li>\n</ul>\n\n<p>You could create a class that cleanly exposes what you need, and only cast <code>UserToken</code> to that type:</p>\n\n<pre><code>public class CustomUserToken\n{\n public class CustomUserToken(Connection connection, SendDataToken token)\n {\n _connection = connection;\n _token = token;\n }\n\n private readonly Connection _connection;\n public Connection Connection { get { return _connection; } }\n\n private readonly SendDataToken _token;\n public SendDataToken Token { get { return _token; } }\n}\n</code></pre>\n\n<p>And now you can consistently cast <code>SockedAsyncEventArgs.UserToken</code> to <code>CustomUserToken</code>, and get the <code>Connection</code> and <code>Token</code> from there.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:03:41.187", "Id": "45510", "ParentId": "8361", "Score": "5" } }, { "body": "<p>I've noticed that the socket you use for <code>SendAsync</code> is the SAEA's <code>AcceptSocket</code>.\nHowever for <code>ReceiveAsync</code>, you use your UserToken's Socket.\nCould you use the same instance for both purposes?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-08T20:58:32.527", "Id": "196139", "ParentId": "8361", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T15:01:40.813", "Id": "8361", "Score": "8", "Tags": [ "c#", ".net", "networking" ], "Title": "SocketAsyncEventArgs send and receive" }
8361
<p>This is my first forray into Java Swing and it's not exactly pretty. I have quite a few methods, and a lot of stuff going on (XML parsing, data conversion, etc) and I'm just wondering what kind of general improvements / redundancies I can eliminate from my code.</p> <p><strong>test.xml:</strong></p> <pre class="lang-xml prettyprint-override"><code>&lt;weeks&gt; &lt;week&gt; &lt;date&gt;2012/01/23 00:00:00&lt;/date&gt; &lt;riddle&gt;Why Did the chicken Cross the road&lt;/riddle&gt; &lt;lastWeekSolution&gt;Because I said So&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/01/30 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 1&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/02/06 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 2&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/02/13 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 3&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/02/20 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 4 &lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/02/27 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 5&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/03/05 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 6&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/03/12 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 7&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/03/19 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 8&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/03/26 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 9&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/04/02 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 10&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/04/09 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 11&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/04/16 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 12&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/04/23 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 13&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;week&gt; &lt;date&gt;2012/04/30 00:00:00&lt;/date&gt; &lt;riddle&gt;ipso lorem 14&lt;/riddle&gt; &lt;lastWeekSolution&gt;I'm Going to get this&lt;/lastWeekSolution&gt; &lt;/week&gt; &lt;/weeks&gt; </code></pre> <p><strong>MoreSwing.java:</strong></p> <pre class="lang-java prettyprint-override"><code>package moreswing; // @author Damien Bell import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.io.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JTextArea; import javax.swing.JLabel; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.util.Scanner; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class MoreSwing extends JFrame { public MoreSwing(){ initUI(); } private int j; private String[] strArray = new String[4]; JTextArea area = new JTextArea(strArray[1]); JButton nextButton = new JButton("Next"); JButton prevButton = new JButton("Previous"); JButton toggleAnswerButton = new JButton("Previous"); boolean isToggledNext = false; boolean isToggledPrev = false; boolean dateLockBool=false; public final Date getDateTime(){ Date date = new Date(); return date; } //Loads everything from the selected week in the xml file into an array of strings via xml parsing. public final String[] xmlLoader(int s, String[] strArray_m){ try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse (new File("test.xml")); // normalize text representation doc.getDocumentElement ().normalize (); NodeList listOfWeek = doc.getElementsByTagName("week"); Node firstWeekNode = listOfWeek.item(s-1); int totalWeeks = listOfWeek.getLength(); strArray_m[3] = Integer.toString(totalWeeks); if(firstWeekNode.getNodeType() == Node.ELEMENT_NODE){ Element firstWeekElement = (Element)firstWeekNode; //------- NodeList dateList = firstWeekElement.getElementsByTagName("date"); Element dateElement = (Element)dateList.item(0); NodeList textDateList = dateElement.getChildNodes(); strArray_m[0]= (((Node)textDateList.item(0)).getNodeValue().trim()).toString(); //------- NodeList riddleList = firstWeekElement.getElementsByTagName("riddle"); Element riddleElement = (Element)riddleList.item(0); NodeList textRiddleList = riddleElement.getChildNodes(); strArray_m[1]= (((Node)textRiddleList.item(0)).getNodeValue().trim()).toString(); //---- NodeList lWSList = firstWeekElement.getElementsByTagName("lastWeekSolution"); Element ageElement = (Element)lWSList.item(0); NodeList textLWSList = ageElement.getChildNodes(); strArray_m[2]= (((Node)textLWSList.item(0)).getNodeValue().trim()).toString(); //------ }//end of if clause } catch (SAXParseException err) { System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ()); System.out.println(" " + err.getMessage ()); }catch (SAXException e) { Exception x = e.getException (); ((x == null) ? e : x).printStackTrace (); }catch (Throwable t) { t.printStackTrace (); } return strArray_m; } //Handles all the data from the next button public final void doUpdate(int j, String[] strArray_m, JTextArea area){ xmlLoader(j, strArray_m); //Load stuff from the xml file area.setText(strArray_m[1]); // update the text area } public final boolean toggleButton(JButton buttonDisable, boolean disableButtonBool){ buttonDisable.setEnabled(!buttonDisable.isEnabled()); // Swap button state if(disableButtonBool){ disableButtonBool = false; } // Swap bool else { disableButtonBool = true; }//Swap bool return disableButtonBool;//return Bool }////End ToggleButton method public final void dateLock(JButton nextButton){ nextButton.setEnabled(!nextButton.isEnabled()); }//End Datelock Method public final void toggleContent(JTextArea area, JButton toggleContent, String[] strArray_m){ String toggle = toggleContent.getText(); if(toggle.equalsIgnoreCase("Show Last Week's Answer")){ toggleContent.setText("This Week's Brain Teaser"); area.setText(strArray_m[2]); }//end if else{ toggleContent.setText("Show Last Week's Answer"); area.setText(strArray_m[1]); }//End else }//End ToggleContent method public final void initUI() { //add panel JPanel panel = new JPanel(); getContentPane().add(panel); panel.setLayout(null); //Declare Scanner, input the week you want, load that week from XML file Scanner input = new Scanner(System.in); j = 1; xmlLoader(j, strArray); isToggledPrev = toggleButton(prevButton, isToggledPrev); //Create text area with returned XML data as default text area text area.setBounds(50, 100, 350, 400); panel.add(area); // add text area to panel area.setText(strArray[1]); JLabel labelAuthor = new JLabel("Author: Damien Bell"); labelAuthor.setBounds(620, 600, 150, 50); panel.add(labelAuthor); toggleAnswerButton.setBounds(95, 520, 250, 30); toggleAnswerButton.setText("Show Last Week's Answer"); toggleAnswerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ toggleContent(area, toggleAnswerButton, strArray); } }); panel.add(toggleAnswerButton); nextButton.setBounds(550, 250, 80, 30); nextButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ Date date1 = getDateTime(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); try{ Date date2 = dateFormat.parse(strArray[0]); if (date1.compareTo(date2) &lt; 0 ){ dateLock(nextButton); dateLockBool=true; } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } if((j+2)&gt; Integer.parseInt(strArray[3])){ isToggledNext = toggleButton(nextButton, isToggledNext); } if(isToggledPrev){ isToggledPrev = toggleButton(prevButton, isToggledPrev); } j++; doUpdate(j, strArray, area); } }); panel.add(nextButton); prevButton.setBounds(550, 350, 80, 30); prevButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ if((j-2) == 0 ){ isToggledPrev = toggleButton(prevButton, isToggledPrev); } if(isToggledNext){ isToggledNext = toggleButton(nextButton, isToggledNext); } if(dateLockBool){ dateLockBool = false; dateLock(nextButton); } j--; doUpdate(j, strArray, area); } }); panel.add(prevButton); //Add quit button JButton quitButton = new JButton("Quit"); quitButton.setBounds(10,610,80,30); quitButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent event){ System.exit(0); } }); panel.add(quitButton); // Add quit button to panel //Set overall window options for swing window setTitle("Quit Button Test"); setSize(800,700); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } // Main, lol public static void main(String args[]){ SwingUtilities.invokeLater(new Runnable() { public void run(){ MoreSwing ms = new MoreSwing(); ms.setVisible(true); } }); } } </code></pre>
[]
[ { "body": "<p>Given that you <em>already</em> appear to have an error in your XML file (because the solution presented in the first week appears to be the answer to itself, not <code>lastWeekSolution</code> as claimed), I'd recommend revising your structure. It's also going to cause problems with your edge cases. The first one logically can't have a solution element <em>at all</em> (because a blank solution is still a solution), and the last element can <em>only</em> have a solution element. It's also going to cause problems if you read it into something that ignores the order in the XML file - that is, treats it as set data.</p>\n\n<p>I'd revise it to:</p>\n\n\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;riddle&gt;\n &lt;postingTimestamp&gt;2012/01/23 00:00:00&lt;/postingTimestamp&gt;\n &lt;query&gt;Why Did the chicken Cross the road?&lt;/query&gt;\n &lt;solution&gt;Because I told him to!&lt;/solution&gt;\n&lt;/riddle&gt;\n</code></pre>\n\n<p>I'd recommend making your XSD (you did define one, right?) allow between 0 and some multiple number of solutions (some riddles have no answer, some may have multiple).\n(Of course, I'd also probably store this in a database, not an XML file, but whatever).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T18:41:22.603", "Id": "13074", "Score": "0", "body": "In this case the XML file was really just a filler, I should've mentioned that. The first week's solution should've been more like\n\n<week>\n <riddle>Why did the chicken cross the road</riddle>\n <LWS>There was no solution since this is the first week</LWS>\n <date>whatever</date>" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T18:43:20.087", "Id": "13075", "Score": "0", "body": "Although you do make a good point about the edge cases being a pain, I haven't really conceptualized a solution to the final week solution quite yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T18:55:36.120", "Id": "13077", "Score": "0", "body": "@HunderingThooves - There's also the problem that you're explicitly connecting this riddle to the previous one. You can't simply insert a new riddle between existing ones, you have to update multiple entries; I'd rather grab two entries as necessary, than one that I hope contains the correct answer. Also, I'd drop the `week` element, and just key things by date - you should change your program to aggregate them by weeks as necessary (what happens if you put an entry in the wrong week?)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T20:28:19.007", "Id": "13083", "Score": "0", "body": "How would you do that X-Zero, aggregate them by weeks that is? The best I could think of is the date comparison that I used above, but if there's a better way to go about this I would love to learn it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T20:55:31.563", "Id": "13084", "Score": "0", "body": "Once you have a `Date` object (or, because I really like the [Joda Time](http://joda-time.sourceforge.net/index.html) library, `DateTime`) you should be able to query it for week number. I haven't really looked through your Java code, I was focusing more on the problems generated by your data-model; however, I can already tell you're violating seperation of concerns - your display code **ABSOLUTELY SHOULD NOT** be loading your backend data. Design patterns will help you here - [MVC](http://en.wikipedia.org/wiki/Model-view-controller) will be a good place to start." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T17:51:45.050", "Id": "8367", "ParentId": "8366", "Score": "2" } }, { "body": "<ol>\n<li><p>Instead of printing stacktraces to the console show the error message to the user. (See later.)</p></li>\n<li><p>The following code with the ternary operator is really hard to read. Try to avoid it.</p>\n\n<pre><code>final Exception x = e.getException();\n((x == null) ? e : x).printStackTrace();\n</code></pre></li>\n<li><p>What is <code>j</code>?</p>\n\n<pre><code>private int j;\n</code></pre>\n\n<p>Try to find a more meaningful name.</p></li>\n<li><p>The widget fields should be <code>private</code> and they could be <code>final</code>. I don't think that other classes should access these objects.</p>\n\n<pre><code>private final JButton nextButton = new JButton(\"Next\");\n...\n</code></pre>\n\n<p>It would improve <a href=\"http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29\" rel=\"nofollow noreferrer\">cohesion</a>.</p></li>\n<li><p>Fields should be at the beginning of the class, then comes the constructor, then the other methods. (According to the <a href=\"http://www.oracle.com/technetwork/java/codeconv-138413.html\" rel=\"nofollow noreferrer\">Code Conventions for the Java Programming Language</a>, 3.1.3 Class and Interface Declarations.)</p></li>\n<li><p>Variable names such as <code>strArray_m</code> does not fit to the <a href=\"http://www.oracle.com/technetwork/java/codeconv-138413.html\" rel=\"nofollow noreferrer\">Code Conventions for the Java Programming Language</a>, Chapter 9: Naming Conventions)</p></li>\n<li><p>Comments on the closing curly braces are unnecessary and disturbing. Modern IDEs could show blocks.</p>\n\n<pre><code>}// //End ToggleButton method\n</code></pre>\n\n<p><a href=\"https://softwareengineering.stackexchange.com/questions/53274/comments-at-end-of-code-block-after-good-or-bad\">“// …” comments at end of code block after } - good or bad?</a></p></li>\n<li><p>The <code>disableButtonBool</code> parameter of the <code>toggleButton</code> does nothing with the state of the button. I'd remove this parameter.</p>\n\n<pre><code>public final boolean toggleButton(final JButton buttonDisable, boolean disableButtonBool) {\n buttonDisable.setEnabled(!buttonDisable.isEnabled()); // Swap button\n // state\n if (disableButtonBool) {\n disableButtonBool = false;\n } else {\n disableButtonBool = true;\n }\n return disableButtonBool;// return Bool\n}// //End ToggleButton method\n</code></pre></li>\n<li><p>I'd move the <code>toggle</code> method a <code>ToggleButton</code> class (which would be a subclass of <code>JButton</code>):</p>\n\n<pre><code>public class ToggleButton extends JButton {\n private static final long serialVersionUID = 1L;\n\n public ToggleButton(String text) {\n super(text);\n }\n\n public boolean toggle() {\n final boolean newState = !isEnabled();\n setEnabled(newState);\n return newState;\n }\n}\n</code></pre>\n\n<p>Then I'd use this class in the <code>MoreSwing</code> class:</p>\n\n<pre><code>private final ToggleButton nextButton = new ToggleButton(\"Next\");\nprivate final ToggleButton prevButton = new ToggleButton(\"Previous\");\n</code></pre>\n\n<p>The <code>toggle</code> method belongs here, it manipulates the state of the button. (It increases cohesion.)</p></li>\n<li><p>The <code>xmlLoader</code> method should have a separate class: <code>XmlLoader</code>. Currently it violates the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>.</p>\n\n<p>Then the <code>XmlLoader.loadXml()</code> method should throw a custom exception in the <code>catch</code> block:</p>\n\n<pre><code>} catch (final SAXParseException saxpe) {\n final String errorMsg = \"** Parsing error\" + ...\n throw new WeekException(errorMsg, saxpe);\n}\n</code></pre>\n\n<p>Your UI have to handle these <code>WeekException</code>-s. For example, show a Swing error box to the user with the message of the exception. (Find a better name for the exception, please.)</p></li>\n<li><p>The <code>Scanner</code> instance is unnecessary:</p>\n\n<pre><code>Scanner input = new Scanner(System.in);\n</code></pre>\n\n<p>(Unused variable.)</p></li>\n<li><p>I'm not too familiar with Swing, but I think there should be a better way to stop the application than calling <code>System.exit()</code>:</p>\n\n<pre><code>quitButton.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(final ActionEvent event) {\n System.exit(0);\n }\n});\n</code></pre>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/258099/how-to-close-a-java-swing-application-from-the-code\">How to close a Java Swing application from the code</a></li>\n<li><a href=\"https://stackoverflow.com/a/3281943/843804\">This answer also helpful</a></li>\n</ul></li>\n<li><p>I'd use JAXB for the XML processing.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T23:14:40.303", "Id": "13096", "Score": "0", "body": "This is amazing, thank you so much.\n\nFor the record I do have a few clarifications I'd like to ask / post:\n\n1. That's a good idea, I will definitely change that. -- 2. I didn't even write that exception code. I grabbed a lot of the xml code from a website then tweaked it a LOT to suit my needs. -- 3. I meant to change that a while back, too bad you can't just refactor for a single letter, eh? -- 4. Another good idea, they should definitely be private, and I suppose that quit could be final, all the others have things acting on them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T23:15:28.057", "Id": "13098", "Score": "0", "body": "5. Can you explain a bit more why this convention exists and why it's the norm in java? I got yelled at for not creating things at the time of initialization / usage in C++ and now it seems like the opposite in Java--- 6. I really struggle to find a good variable name convention that works for me. --- 7. I suppose you have a point, however I am showing this to a teacher (she knows that I check my code on here) so having the distinction of lots of comments will (hopefully) help her to read it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T23:22:07.183", "Id": "13100", "Score": "0", "body": "8. Yeah, I meant to do something else with that, but then I ended up making datelock which worked the other way around. -- 9. I'm not exactly sure what this code does / what you mean, can you explain this a little more? 10. How would you suggest that I fix the multiple responsibility side of this? I'd never heard of that before, although it does make sense. -- 11. Ahhh, I forgot to remove that, it was part of my debug code from earlier, good catch. -- 12. I never really understood why system.exit(0) was good / bad, can you explain that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T23:22:37.497", "Id": "13101", "Score": "0", "body": "And finally, thanks again for all your help, it really means a lot to see what's wrong with my code. I plan to go back and fix what I understood of what you listed here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T23:58:05.083", "Id": "13200", "Score": "0", "body": "If you copy code from the web and it will be part of the application you will be responsible for that. If it's even just a homework it could lead to awkward situations when the teacher ask how this line works and why you chose that :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T23:58:33.197", "Id": "13201", "Score": "0", "body": "5. I don't know. Maybe a lot of people find it convenient, and if lots of people use that it reduces the effort is needed to read and understand source code. You should read this question and its answers: [Variable declaration closer to usage Vs Declaring at the top of Method](http://codereview.stackexchange.com/questions/6283/variable-declaration-closer-to-usage-vs-declaring-at-the-top-of-method) (Check the book in my answer there too.); 6. The linked document contain the rules for naming conventions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T23:58:41.777", "Id": "13202", "Score": "0", "body": "10: I'm not too familiar with Swing, but I'd search for \"Spring MVC\" (MVC as Model-view-controller architecture).; Check the update too." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T22:58:51.513", "Id": "8380", "ParentId": "8366", "Score": "3" } } ]
{ "AcceptedAnswerId": "8380", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T15:47:25.713", "Id": "8366", "Score": "4", "Tags": [ "java", "xml", "swing" ], "Title": "XML parsing and data conversion with Swing" }
8366
<p>Here is my solution for Project Euler 35. (Find the number of circular primes below 1,000,000. Circular meaning all rotations of the digits are prime, i.e. <code>197</code>, <code>719</code>, <code>971</code>.) The code takes about 30 minutes to run. Can you help me identify which parts of the algorithm are hogging up computation time?</p> <p>I know there are many solutions out there, I just want to know why this one is soooo slow. I suspect it has something to do with the <code>p.count</code> function call.</p> <ul> <li><code>p</code> is initialized to a list of all primes below 1 million using the Sieve of Eratosthenes. </li> <li><code>total</code> is initialized to 0.</li> </ul> <pre><code>for i in p: primer = str(i) circ = 1 for j in range(len(primer)-1): primer = primer[1:]+primer[:1] if (p.count(int(primer)) == 1): circ += 1 if circ == len(primer): total += 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T18:29:41.053", "Id": "19987", "Score": "0", "body": "See http://codereview.stackexchange.com/a/12389/13523" } ]
[ { "body": "<p>Your <code>p</code> is a list. Then you do <code>p.count(x)</code> to see if x is a prime. This does a linear search of the list, and in fact, has to examine every element of <code>p</code>, not just those up to the occurrence of <code>x</code>. Instead, change <code>p</code> to a set. It will run much faster. Also, once you see that a rotation is not prime, you can stop checking all the rotations.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T20:27:00.767", "Id": "8372", "ParentId": "8371", "Score": "7" } }, { "body": "<p><em>All</em> primes below a million? You only need the ones that consist of the digits 1, 3, 7, or 9.</p>\n\n<p>Edit: And the single-digit circular primes 2 and 5.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T20:33:23.323", "Id": "13085", "Score": "1", "body": "Your total would be off by 1: you would miss 2! But good point!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T20:34:48.317", "Id": "13086", "Score": "1", "body": "While accurate if he were only concerned with primes > 10, this optimization would actually produce the wrong answer because 5 counts as a circular prime according to the problem description. It's a good idea if you special case 5 though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T20:30:08.677", "Id": "8373", "ParentId": "8371", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T20:24:01.400", "Id": "8371", "Score": "6", "Tags": [ "python", "optimization", "algorithm", "project-euler", "primes" ], "Title": "Euler 35 - python solution taking too long" }
8371
<p>It's simple. <code>Person</code> is a superclass. <code>Student</code> and <code>Instructor</code> are its subclasses. The program suppose to allow user create a student or an instructor.</p> <p><strong>Run</strong></p> <pre><code>package com.exercise.inheritance1; import java.util.Scanner; import org.joda.time.LocalDate; public class Run { public static void main(String args[]) { Boolean done = false; do { System.out.println("Select one of the following:"); System.out.println("\t1 -- Create Student"); System.out.println("\t2 -- Create Instructor"); System.out.println("Enter your selection (0 to exit): "); Scanner scan = new Scanner(System.in); String userInput = scan.nextLine(); int selection; String name; LocalDate dateOfBirth; String major; Double salary; try { selection = Integer.parseInt(userInput); } catch(Exception ex) { System.out.println("What?"); System.out.println(ex.getMessage()); continue; } System.out.println("You selected " + selection); switch(selection) { case 0: done = true; break; case 1: //Create Student System.out.println("Name:"); name = scan.nextLine(); System.out.println("Birthdate(YYYY-MM-DD):"); try { dateOfBirth = LocalDate.parse(scan.nextLine()); } catch(IllegalArgumentException ex) { System.out.println(String.format("Ooops! Message: \n%s", ex.getMessage())); continue; } System.out.println("Major:"); major = scan.nextLine(); Student stu = new Student(name, dateOfBirth, major); System.out.println(stu.toString()); break; case 2: //Create Instructor System.out.println("Name:"); name = scan.nextLine(); System.out.println("Birthdate(YYYY-MM-DD):"); try { dateOfBirth = LocalDate.parse(scan.nextLine()); } catch(IllegalArgumentException ex) { System.out.println(String.format("Ooops! Message: \n%s", ex.getMessage())); continue; } System.out.println("Salary:"); try { salary = Double.parseDouble(scan.nextLine()); } catch(IllegalArgumentException ex) { System.out.println(String.format("Ooops! Message: \n%s", ex.getMessage())); continue; } Instructor ins = new Instructor(name, dateOfBirth, salary); System.out.println(ins.toString()); break; default: System.out.println(String.format("You have selected an invalid number %s", selection)); continue; } }while(!done); System.out.println("See ya!"); } } </code></pre> <p><strong>Person</strong></p> <pre><code>package com.exercise.inheritance1; import org.joda.time.LocalDate; public class Person { protected String name; protected LocalDate dateOfBirth; public Person(String name, LocalDate dateOfBirth) { setName(name); setDateOfBirth(dateOfBirth); } private void setName(String name) { this.name = name; } public String getName() { return this.name; } private void setDateOfBirth(LocalDate dateOfBirth) { this.dateOfBirth = dateOfBirth; } public LocalDate getDateOfBirth() { return this.dateOfBirth; } @Override public String toString() { return String.format("%s: %s\n%s: %s", "Name", this.getName(), "Date of Birth", this.getDateOfBirth()); } } </code></pre> <p><strong>Student</strong></p> <pre><code>package com.exercise.inheritance1; import org.joda.time.LocalDate; public class Student extends Person { private String major; public Student(String name, LocalDate dateOfBirth, String major) { super(name, dateOfBirth); setMajor(major); } private void setMajor(String major) { this.major = major; } public String getMajor() { return this.major; } @Override public String toString() { return String.format("%s\n%s: %s", super.toString(), "Major", this.getMajor()); } } </code></pre> <p><strong>Instructor</strong></p> <pre><code>package com.exercise.inheritance1; import org.joda.time.LocalDate; public class Instructor extends Person { private double salary; public Instructor(String name, LocalDate dateOfBirth, double salary) { super(name, dateOfBirth); setSalary(salary); } private void setSalary(double salary) { this.salary = salary; } public double getSalary() { return this.salary; } @Override public String toString() { return String.format("%s\n%s: %s", super.toString(), "Salary", this.getSalary()); } } </code></pre>
[]
[ { "body": "<p>It seems to be good enough but you can</p>\n\n<ol>\n<li>Add more comments</li>\n<li><p>Add more methods to your main. Examples: </p>\n\n<ul>\n<li><code>public Student createStudent()</code></li>\n<li><code>public Instructor createInstructor()</code></li>\n</ul>\n\n<p>This will help you have a clearer Case Section</p></li>\n</ol>\n\n<p>There are many ways to code your project because of the simple task. Just try to make it clearer so you can read it like you were reading a book or a story :)</p>\n\n<p>I didn't get what you meant by <code>Major</code>? If it's a <code>Person</code> then you can use a <code>Major</code> object to handle this instead of a string. Thus you'll pass an object to the constructor which is another <code>Person</code> (the <code>Major</code>) assuming you extended this <code>Major</code> object by the <code>Person</code> object (since a <code>Major</code> should be a <code>Person</code>: <code>class Major extends Person</code>).</p>\n\n<p>Don't forget to put a space in <code>\"Major\"</code> (change it to <code>\"Major: \"</code>):</p>\n\n<pre><code>super.toString(), \"Major: \", this.getMajor();\n</code></pre>\n\n<p>PS: same for the other classes: <code>Person</code>, <code>Instructor</code>, ...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T04:24:21.250", "Id": "13111", "Score": "0", "body": "A major is not a person, but a primary area of study for a university student." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T12:54:16.613", "Id": "13118", "Score": "0", "body": "Ok sorry for this :). Btw you can create and object for that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T03:26:14.480", "Id": "8384", "ParentId": "8375", "Score": "1" } }, { "body": "<p>Two things: if you enter the date wrong, you reset the input. Not a big deal since there are only two fields, but if it was 15 fields, it would be really annoying. Secondly, when entering dates, it's often better to ask the user to enter as three separate fields (YYYY, MM, DD) rather than having them format the string (it's ok to ask them in something that they can edit, but here it's \"write once\".</p>\n\n<p>. . .</p>\n\n<p>Generally it's good practice to declare variables as late as possible. When you expose things like</p>\n\n<pre><code>String name;\nLocalDate dateOfBirth;\nString major;\nDouble salary;\n</code></pre>\n\n<p>there is no guarantee of state. Sometimes some of the variables are unset, sometimes they are all set, etc. Move them into the case statement.</p>\n\n<p>. . .</p>\n\n<p>Another point is not to give exception messages to the user. Format it nicely, log it, but don't show the raw exception message.</p>\n\n<p>. . .</p>\n\n<p>Good call on using Joda, Java Dates are terrible.</p>\n\n<p>. . .</p>\n\n<p>Generally it is not a good idea to switch on integer flags. It's fine for input, but as the code grows, it becomes less maintainable. You have two states right now, imagine how difficult it would be to maintain that if statement with 15 different modes.</p>\n\n<pre><code>try\n {\n selection = Integer.parseInt(userInput);\n }\n catch(Exception ex)\n {\n System.out.println(\"What?\");\n System.out.println(ex.getMessage());\n continue;\n }\n</code></pre>\n\n<p>Instead, it might be better expressed as:</p>\n\n<pre><code>enum EditMode { UNKNOWN, EXIT, CREATE_STUDENT, CREATE_INSTRUCTOR }\n...\nEditMode editMode = EditMode.UNKNOWN;\ntry {\n String userInput = scan.nextLine();\n selection = Integer.parseInt(userInput);\n\n if(selection == 0) { editMode = EditMode.EXIT; }\n else if(selection == 1) { editMode = EditMode.CREATE_STUDENT; }\n else if(selection == 2) { editMode = EditMode.CREATE_INSTRUCTOR; }\n\n } catch (Exception e) {\n //... do nothing. log an error.\n }\n ...\n //Now you switch on EditMode, and it's much more clear what is going on.\n</code></pre>\n\n<p>This also protects you from accidentally looking at invalid modes.</p>\n\n<p>Getting more advanced, in Java enums are static final children of Enum, so you can have methods and constructors on them. In particular, you can move the logic from your switch statement to within the enum types. This is generally referred to as the \"strategy pattern\".</p>\n\n<pre><code>enum EditMode { UNKNOWN, EXIT, CREATE_STUDENT, CREATE_INSTRUCTOR }\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>enum EditMode {\n UNKNOWN {\n //Note: we aren't passing in the actual input here.\n void handleEdit() { System.out.println(\"You have selected an invalid option\"); }\n },\n\n EXIT {\n void handleEdit() { /* Do nothing. Handle this specially */ }\n },\n\n CREATE_STUDENT {\n void handleEdit() { /* Code from \"case 1:\" goes here */ }\n }, \n CREATE_INSTRUCTOR {\n void handleEdit() { /* Code from \"case 2:\" goes here */ }\n };\n\n abstract void handleEdit();\n}\n</code></pre>\n\n<p>with this, your main loop becomes much simpler.</p>\n\n<pre><code>while(true) {\n EditMode editMode = EditMode.UNKNOWN;\n try {\n String userInput = scan.nextLine();\n selection = Integer.parseInt(userInput);\n\n if(selection == 0) { editMode = EditMode.EXIT; }\n else if(selection == 1) { editMode = EditMode.CREATE_STUDENT; }\n else if(selection == 2) { editMode = EditMode.CREATE_INSTRUCTOR; }\n } catch (Exception e) {\n //... do nothing / log an error. editMode will be UNKNOWN, so you can\n // pretty much just ignore the exception.\n }\n\n if(editMode == EditMode.EXIT) { break; }\n editMode.handleEdit();\n}\n</code></pre>\n\n<p>which is much cleaner, I think.</p>\n\n<p>Notice however that UNKNOWN no longer displays the user input. Using an enum, the only option to fix this is to have an argument to handleEdit - which would be ignored by most others. The other choice is to create actual objects for your strategies, subclassing each one, and then creating them while inspecting the input.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T06:04:00.420", "Id": "8386", "ParentId": "8375", "Score": "3" } }, { "body": "<p>You could use the Apache Commons CLI library.</p>\n\n<p><a href=\"http://commons.apache.org/cli/\" rel=\"nofollow\">http://commons.apache.org/cli/</a></p>\n\n<p>It abstracts out the option parsing and usage printing. All you have to do is to define the Options your console app provides and bind them to keywords.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T06:41:36.203", "Id": "8443", "ParentId": "8375", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T22:03:59.233", "Id": "8375", "Score": "3", "Tags": [ "java", "jodatime", "inheritance", "console" ], "Title": "Creating students and instructors" }
8375
<p>I have the following code that gets the difference in time between now and when an alarm is supposed to go off (i.e. "alarm goes off in 23 minutes, 56 seconds").</p> <pre><code>def time_to_alarm_in_words #AN EMPTY STRING WE WILL BE ADDING TO time_in_words = '' #THE TIME TO THE ALARM IN SECONDS total_seconds = (time - Time.now).to_i #SOME BASIC TIME UNIT VARIABLES days = total_seconds / 86400 hours = (total_seconds / 3600) - (days * 24) minutes = (total_seconds / 60) - (hours * 60) - (days * 1440) seconds = total_seconds % 60 #ONLY PROCEED IF THE TIME TO THE ALARM IS POSITIVE(I.E. IN THE FUTURE) unless total_seconds &lt;= 0 #BUILD A HASH WITH THE TIME UNTIL THE ALARM time_hash = {"days" =&gt; (total_seconds / 86400), "hours" =&gt; ((total_seconds / 3600) - (days * 24)), "minutes" =&gt; ((total_seconds / 60) - (hours * 60) - (days * 1440)), "seconds" =&gt; (total_seconds % 60)} #IF THE TIME SEGMENT IS POSITIVE, ADD IT TO THE STRING time_hash.each_pair do |time_segment,length| if value &gt; 0 #i.e. add "22 hours," to the empty string time_in_words &lt;&lt; "#{length} #{time_segment}," end end #CHOP OFF THE TRAILING ',' time_in_words.chop! #RETURN THE RESULT return time_in_words + " ago" end </code></pre> <p>I have a feeling I could cut this down by half. Any suggestions?!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-27T18:34:28.187", "Id": "62830", "Score": "0", "body": "Use [distance_of_time_in_words](http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words)(Time.now, Time.now.end_of_day)" } ]
[ { "body": "<p>Courtesy of the clever helper method from this link:\n<a href=\"https://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails\">https://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails</a></p>\n\n<pre><code>def humanize secs\n [[60, :seconds], [60, :minutes], [24, :hours], [1000, :days]].map{ |count, name|\n if secs &gt; 0\n secs, n = secs.divmod(count)\n \"#{n.to_i} #{name}\"\n end\n }.compact.reverse.join(' ')\nend\n\ndef time_to_alarm_in_words time\n #AN EMPTY STRING WE WILL BE ADDING TO\n time_in_words = ''\n\n #THE TIME TO THE ALARM IN SECONDS\n total_seconds = (time - Time.now).to_i\n\n time_in_words = humanize total_seconds\n\n #RETURN THE RESULT\n return time_in_words + \" in the future\"\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T22:44:53.263", "Id": "8379", "ParentId": "8376", "Score": "1" } } ]
{ "AcceptedAnswerId": "8379", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T22:28:24.750", "Id": "8376", "Score": "1", "Tags": [ "ruby" ], "Title": "Suggested refactorings of this Ruby time-to-string method?" }
8376
<p>I've implemented <a href="http://wiki.commonjs.org/wiki/Modules/1.1.1" rel="nofollow">CommonJS Modules 1.1.1</a> as a simple bash script with a bit of help from <a href="http://www.gnu.org/software/m4/" rel="nofollow">M4</a>.</p> <p>I'm interested in comments on the shell scripting and the javascript output. </p> <p>Some specific questions on bash scripting:</p> <ul> <li>How are backquotes different from $( ... ) as far as evaluating stuff in strings?</li> <li>Are there places where I have improperly quoted variables, where things could break if path names have spaces or weird characters? <code>normalize_path</code> looks wrong to me, but I'm not sure how to correct it.</li> <li>Is there a better way to increment/decrement variables?</li> <li>Is anything done in a bad style?</li> </ul> <p>I'm also interested in comments on the javascript output (the anonymous bootstrap object, and its <code>init</code> function).</p> <p>Also, is this a good implementation of CommonJS Modules? It passes all of the unit tests, but it may still have flaws. One thing on my to-do list is adding a command line argument / environment variable for a list of include paths.</p> <hr> <p><strong>com4</strong> - the main program. </p> <pre><code>#!/bin/bash export program="CoM4" export usage="Usage: $0 -i &lt;in_file.js&gt; -o &lt;out_file.js&gt;"; export com4_path="$( dirname $( readlink -f "$0" ))" export included_files="included_files.tmp" export tmp_path="_tmp" export abs_path="" export rel_path="" export include="" export in_file="" export out_file="" export fail=0; export test_mode=0; export html=0; export var_global="window" export var_main="" . "$com4_path/include.sh" get_options "$@" mkdir "$tmp_path" echo -n &gt; "$out_file" echo -n &gt; "$included_files" abs_path="`normalize_path $( dirname "$in_file" )`"; rel_path="$abs_path"; id="`basename "$in_file"`"; if [ $html = 1 ]; then echo "&lt;html&gt;&lt;head&gt;&lt;script&gt;" &gt;&gt; "$out_file"; fi if [ $test_mode = 1 ]; then echo "function print(text){ console.log(text); }" &gt;&gt; "$out_file"; fi if [ "$var_main" != "" ]; then echo -n "$var_main = " &gt;&gt; "$out_file"; fi echo "({modules:[ "&gt;&gt; "$out_file"; write_module "$id" 1 &gt;&gt; "$out_file"; for file in $( ls $tmp_path ); do cat "$tmp_path/$file" &gt;&gt; "$out_file"; done echo " // // $program bootstrap // 0],init:function(){ var boot=this, exports=[], require=function(id){ return exports[id] || void boot.modules[id](require, id ? {id:id} : require.main, exports[id]={}) || exports[id]; }; require.main={id:0}; return require(0); }}).init();" &gt;&gt; "$out_file"; if [ $html = 1 ]; then echo "&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;" &gt;&gt; "$out_file"; fi rm "$included_files" rm -r "$tmp_path" </code></pre> <hr> <p><strong>include.sh</strong> - helper functions. </p> <pre><code>get_options () { while getopts "i:o:g:m:I:th" opt; do case "$opt" in i) in_file="$OPTARG";; o) out_file="$OPTARG";; g) var_global="$OPTARG";; I) include="$OPTARG";; # TODO: -I / include dirs t) test_mode=1;; h) html=1;; m) var_main="$OPTARG";; [?]) fail=1;; esac done if [ "$in_file" = "" ]; then echo &gt;&amp;2 "$0: No input file specified." fail=1 fi if [ "$out_file" = "" ]; then echo &gt;&amp;2 "$0: No output file specified." fail=1 fi if [ $fail != 0 ]; then echo &gt;&amp;2 "$usage" exit $fail fi } normalize_path () { echo "$(cd $(dirname "$1"); echo $PWD/$(basename "$1"))" } write_module () { if [ "`echo $1 | egrep '^\.\.?/'`" = "" ]; then path=$(normalize_path "$abs_path/$1.js") else path=$(normalize_path "$rel_path/$1.js") fi module_name=`abs_to_rel "$abs_path" "$path"` loaded=0 old_path="$rel_path" rel_path=$( dirname "$path" ) count=0 if [ $2 ]; then require="require"; else require="[_require_]"; fi for included in `cat $included_files`; do count=$(( $count + 1 )) if [ "$included" = "$path" ]; then count=$(( $count - 1 )) echo -n "$require($count)" return fi done tmp_file="$tmp_path/$count" if [ "$2" = "" ]; then echo -n "$require($count)" fi echo -n &gt; "$tmp_file"; echo "$path" &gt;&gt; "$included_files" echo " // // $module_name //" &gt;&gt; "$tmp_file" if [ -e "$path" ]; then echo "function(require, module, exports){ " &gt;&gt; "$tmp_file" m4 -P "$com4_path/macros.m4" "$path" &gt;&gt; "$tmp_file" echo "}," &gt;&gt; "$tmp_file" else echo ",// Module \"$module_name\" not found." &gt;&gt; "$tmp_file" echo "Warning: Module \"$module_name\" not found." &gt;&amp;2 fi rel_path="$old_path" } # both $1 and $2 are absolute paths # returns $2 relative to $1 abs_to_rel () { source=$1 target=$2 common_part=$source back= while [ "${target#$common_part}" = "${target}" ]; do common_part=$(dirname $common_part) back="../${back}" done echo ${back}${target#$common_part/} } </code></pre> <hr> <p><strong>macros.m4</strong> - <code>require</code> macro.</p> <pre><code>m4_changequote([_,_])m4_dnl m4_define(require, [_m4_esyscmd( if [ $1 ]; then . "$com4_path/include.sh" write_module $1 else echo -n "[_[_require_]_]" fi )_])m4_dnl m4_define(GLOBAL, [_m4_esyscmd( echo -n "$var_global" )_])m4_dnl </code></pre> <hr> <p>Here is an example of the output from one of the unit tests. The <code>print</code> function is a debug-mode feature to make CommonJS unit tests work properly. </p> <pre><code>function print(text){ console.log(text); } ({modules:[ // // ../program.js // function(require, module, exports){ var test = require(1); var a = require(3); var b = require(4); test.assert(a.a, 'a exists'); test.assert(b.b, 'b exists') test.assert(a.a().b === b.b, 'a gets b'); test.assert(b.b().a === a.a, 'b gets a'); test.print('DONE', 'info'); }, // // ../test.js // function(require, module, exports){ exports.print = typeof print !== "undefined" ? print : function () { var system = require(2); var stdio = system.stdio; stdio.print.apply(stdio, arguments); }; exports.assert = function (guard, message) { if (guard) { exports.print('PASS ' + message, 'pass'); } else { exports.print('FAIL ' + message, 'fail'); } }; }, // // ../system.js // ,// Module "../system.js" not found. // // ../a.js // function(require, module, exports){ exports.a = function () { return b; }; var b = require(4); }, // // ../b.js // function(require, module, exports){ var a = require(3); exports.b = function () { return a; }; }, // // CoM4 bootstrap // 0],init:function(){ var boot=this, exports=[], require=function(id){ return exports[id] || void boot.modules[id](require, id ? {id:id} : require.main, exports[id]={}) || exports[id]; }; require.main={id:0}; return require(0); }}).init(); </code></pre>
[]
[ { "body": "<p>Looks good with a quick scan-over. Except I think you should learn to use the bash regular expressions operator instead of using egrep... Didn't really look at your code well enough but you've used it in a test operator so... Yeah, might be better as a bash solution: <code>[[ $ARG =~ EXPR ]]</code></p>\n\n<p><code>shopt -s extglob</code> also activates extended reg-exes in bash but the using can be a bit frustrating because it isn't \"regex standard\" or full featured, but with some patience you can learn to do things with bash other's have never dreamed of.</p>\n\n<p>Script inputs</p>\n\n<p>Try this instead:</p>\n\n<pre><code>&lt;&lt;ends M4\n\nYOUR SCRIPT HERE\n\nYou can put variables and substitutions here too.\n\nIf you like you can pipe the output from m4 into cat, bash, seed, js, rhino\n\nwhatever. I love this little trick :)\n\nends\n</code></pre>\n\n<p>Substitutions: no difference. Only syntax and nesting.</p>\n\n<p>Increment/Decrement (arithmetic):</p>\n\n<pre><code>declare -i i\ni+=X; # -= requires the use of let for some reason or another..\nlet i++; # standard arithmetic command\n(( i++ )) # just like let/expr..\n$[ i++ ] # another way to let expr\n</code></pre>\n\n<p>You can also use a integer variables without the $ sign as an index to arrays or strings even with incremental/decremental operators. This helps with writing short &amp; concise loop codes.</p>\n\n<p>I love javascript. I imagine someday I will write my own command shell using javascript as the controller back end. But I'm partial to using SpiderMonkey. You cannot beat having access to the C API with a stick (from a shell script)</p>\n\n<p>Happy hacking. Hope this helps. Your code looks good. But it will get better with many trials and errors. Hopefully someone with more insight into your JS tool can provide you a better answer. Just thought it was worth my two cents.</p>\n\n<p>you can join my web and ask me anything about bash, or join my admin group. I have confidence in your skills.</p>\n\n<p><a href=\"https://www.facebook.com/alt.bash\" rel=\"nofollow\">https://www.facebook.com/alt.bash</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T05:55:07.630", "Id": "18810", "Score": "0", "body": "m4 --- ugh... the ugly beast. I hate being forced into that syntax. Would have been much better with more syntax customization on the back end. I'm writing my own macro processor using awk ATM, I love being able to define the language to suit the language I'm working with. The only problem is most interpreters don't think someone might want to have a preprocessor run along side them, so they don't put the proper error handling interface into the code :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T19:07:44.217", "Id": "18814", "Score": "0", "body": "Thanks for the review! The heredoc idea looks cool, but I'm not sure where I'd use it exactly... are you suggesting to put the contents of the m4 script in a heredoc string in the bash script? I think I like it better as a separate script. Your comment about typed variables is very interesting, I had no idea this existed. I'm playing with it now. It seems that if you don't declare with -i, `+=` does string concatenation! As for m4, I agree the syntax is pretty bad, but it's powerful and gets the job done. I considered writing a simple text replacement script instead, but decided against..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T01:47:58.627", "Id": "18824", "Score": "0", "body": "If you need to do any preprocessing on your m4, awk, or sed scripts the here doc solution is quite viable. I usally set an alias like: `alias 'script:'='<<ends'` which looks way cooler! `script: m4 | awk` catch my drift? Sure ya do! `shopt -s expand_aliases` turns aliasing on for scripts." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T01:50:25.363", "Id": "18825", "Score": "0", "body": "Sometimes i use the here-doc scripts to 'compile' some script in bash where the loop operates on a variable that won't change inside the loop. `source <(script: cat ... ends ... )`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T05:52:09.910", "Id": "11728", "ParentId": "8378", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T22:40:04.473", "Id": "8378", "Score": "1", "Tags": [ "javascript", "bash", "shell" ], "Title": "CommonJS modules/require at build-time with bash and M4" }
8378
<p>I know there is probably a better way to have coded this. Can anyone be of help? I am not an expert JavaScript coder.</p> <pre><code>$(function() { $('#clientLoginText').hover(function() { $('#clientLoginBox').stop().animate({ "height" : '80px'}, 700); }, function() { //$('#clientLoginBox').stop().delay(500).animate({ "height" : '0px'}, 700); }); }); $(function() { $('#clientLoginBox').hover(function() { }, function() { $('#clientLoginBox').stop().delay(500).animate({ "height" : '0px'}, 700); }); }); </code></pre>
[]
[ { "body": "<p>Well here is a tidied up version that shouldn't change the functionality at all:</p>\n\n<pre><code>$(function() {\n $('#clientLoginText').mouseenter(function() {\n $('#clientLoginBox').stop().animate({ \"height\" : '80px'}, 700);\n });\n\n $('#clientLoginBox').mouseleave(function() {\n $(this).stop().delay(500).animate({ \"height\" : '0px'}, 700);\n });\n});\n</code></pre>\n\n<p>About the changes:</p>\n\n<ul>\n<li><p>You only need a single document.ready function: the only good reason I can think of for having two is if you need to put them in separate JS files.</p></li>\n<li><p>You had used the <code>.hover()</code> function, which is shorthand for <code>.mouseenter()</code> and <code>.mouseleave()</code>, but in the first use you passed an empty function for the <code>mouseleave</code> part and in the second use you passed an empty function for the <code>mouseenter</code> part, so why not just code the first directly as <code>.mouseenter()</code> and the second as <code>.mouseleave()</code>?</p></li>\n<li><p>Within an event handler you can refer to the element that triggered the event as <code>this</code>, or <code>$(this)</code> if you need it as a jQuery object. More efficient than getting jQuery to find it again from its id.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T01:42:26.553", "Id": "8382", "ParentId": "8381", "Score": "7" } }, { "body": "<p>There's no reason to separate the mouseenter and mouseleave jQuery events into different calls. Since it's the same element, just use:</p>\n\n<pre><code>$(function() {\n $('#clientLoginBox').mouseenter(function() {\n $(this).stop().animate({\"height\": '80px'}, 700);\n }).mouseleave(function() {\n $(this).stop().delay(500).animate({\"height\": '0px'}, 700);\n });\n});\n</code></pre>\n\n<p>It's not that big of a deal to have them separate, but it is an extra call to select the element. Combining them the way directly above makes use of chaining supported in jQuery.</p>\n\n<p>If you wanted to keep them physically separate but not need two calls, you could use:</p>\n\n<pre><code>$(function() {\n var the_box = $('#clientLoginBox').mouseenter(function() {\n $(this).stop().animate({\"height\": '80px'}, 700);\n });\n\n the_box.mouseleave(function() {\n $(this).stop().delay(500).animate({\"height\": '0px'}, 700);\n });\n});\n</code></pre>\n\n<p>Since you want to handle both events, I think using .hover makes more sense, just combine them better:</p>\n\n<pre><code>$(function() {\n $('#clientLoginBox').hover(function() {\n $(this).stop().animate({\"height\": '80px'}, 700);\n }, function() {\n $(this).stop().delay(500).animate({\"height\": '0px'}, 700);\n });\n});\n</code></pre>\n\n<p>.hover() is just a shortcut for binding mouseenter and mouseleave in that order. If you wanted to only bind mouseenter, you could pass a single function to .hover().</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T14:31:41.240", "Id": "33831", "Score": "0", "body": "In the original question there are two separate elements for enter and leave so this doesn't work." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T17:40:17.260", "Id": "10662", "ParentId": "8381", "Score": "1" } } ]
{ "AcceptedAnswerId": "8382", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T00:58:57.940", "Id": "8381", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Animating login screens" }
8381
<p>I want to do binary search and if the target is not there get the index of where it should have been. </p> <p>This is the code I came up with. It seems correct. Is there any problem? Can it be improved? </p> <pre><code>private int binarySearch(String[] sortedArray, String target, int start, int end) { if(start &lt;= end){ int mid = (start + end)/2; if(sortedArray[mid].equals(target)){ return mid; } else if (target.compareTo(sortedArray[mid]) &lt; 0){ return binarySearch(sortedArray, target, start, mid - 1); } else{ return binarySearch(sortedArray, target, mid + 1, end); } } return start; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T19:12:31.823", "Id": "13137", "Score": "5", "body": "Is there a reason you don't use `Arrays.binarySearch` ?" } ]
[ { "body": "<p>2 minor things:</p>\n\n<ol>\n<li><p>Remove the unnecessary comparison. If</p>\n\n<pre><code>sortedArray[mid].equals(target)\n</code></pre>\n\n<p>fails, it will again compare the two strings in the next <code>if</code> condition. Instead, you can just do:</p>\n\n<pre><code>int c = target.compareTo(sortedArray[mid]);\nif(c == 0)\n return mid;\nelse if(c &lt; 0)\n ...\n</code></pre></li>\n<li><p>To keep the method signature simple, you can overload it and delegate to the one that does the work:</p>\n\n<pre><code>public int binarySearch(String[] sortedArray, String target) {\n binarySearch(sortedArray, target, 0, sortedArray.length - 1);\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T15:04:39.660", "Id": "8397", "ParentId": "8388", "Score": "5" } }, { "body": "<p>Return start is incorrect. That will only happen if the target is not in the array, so you'll just end up with effectively a random index. Instead, I would use the Iterator pattern to return an Iterator to the target within the array instead of its index. That way you can handle the \"not found\" case as well.</p>\n\n<p>Another simpler approach to this would be to just return -1, but then the client has to check against a \"magic number\", which is generally not a good thing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T17:04:49.137", "Id": "13133", "Score": "0", "body": "Thanks for the reply.Not sure I follow why return of start is incorrect.If the target is missing, I think that start would return the position it would have occupied.Do you think it does not achieve this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T17:31:44.173", "Id": "13134", "Score": "0", "body": "user384706: That is perhaps true, but it's confusing from a usability point of view, since you have to check twice to see if you actually found the result. That is, you'd have to say \"int pos = binarySearch(array, word); if(array[pos] == word) { ... }\". Additionally, that position would only be true if the array was not modified after the search, so it will quickly become meaningless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-15T20:45:01.037", "Id": "94758", "Score": "0", "body": "@user384706 The standard solution for the absent element is to return the bitwise complement of the insertion position like [here](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(byte[],%20byte)). The bitwise complement is always negative and usually written as `-pos-1` instead of `~pos`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T16:48:04.493", "Id": "8399", "ParentId": "8388", "Score": "2" } }, { "body": "<p>One minor thing in addition to the other answers, there's a bug in your mid point calculation:</p>\n\n<pre><code>int mid = (start + end)/2;\n</code></pre>\n\n<blockquote>\n <p>it fails if the sum of low and high is greater than the maximum positive int value (2^31 - 1). The sum overflows to a negative value, and the value stays negative when divided by two. In C this causes an array index out of bounds with unpredictable results. In Java, it throws ArrayIndexOutOfBoundsException.</p>\n</blockquote>\n\n<p>from <a href=\"http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html\">Nearly All Binary Searches and Mergesorts are Broken</a></p>\n\n<p>To prevent it from flowing over maximum int range replace it with:</p>\n\n<pre><code>int mid = low + ((high - low) / 2);\n</code></pre>\n\n<p>A very minor thing, that will only occur on arrays with a very high number of items. But since you asked for improvements of your code ...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T08:20:15.980", "Id": "8536", "ParentId": "8388", "Score": "5" } }, { "body": "<p>minor improvement, to seand's answer</p>\n\n<pre><code>private int binarySearch(String[] sortedArray, String target) {\n binarySearch(sortedArray, target, 0, sortedArray.length - 1);\n}\n\nprivate int binarySearch(String[] sortedArray, String target, int start, int end) {\n if (start &gt; end)\n return start;\n int mid = (start + end) / 2;\n int c = target.compareTo(sortedArray[mid]);\n return (c == 0) ? mid : (c &lt; 0) ?\n binarySearch(sortedArray, target, start, mid - 1) :\n binarySearch(sortedArray, target, mid + 1, end);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-29T10:21:32.910", "Id": "29114", "ParentId": "8388", "Score": "1" } }, { "body": "<p>You have a recursive implementation, and Java isn't a functional language. If the input is too long, you might simply hit a <code>java.lang.StackOverflowError</code>.</p>\n\n<p>Binary search can simply be written with imperative style, see <code>Arrays.binarySearch</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T10:04:30.847", "Id": "394631", "Score": "0", "body": "This is correct in common. However, in the case of binary search the stack grows with ˋlog(array-size)ˋ. That should not be a problem even when the array has the maximum possible size." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-15T10:40:45.557", "Id": "54298", "ParentId": "8388", "Score": "1" } } ]
{ "AcceptedAnswerId": "8397", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T08:17:56.353", "Id": "8388", "Score": "7", "Tags": [ "java", "algorithm", "binary-search" ], "Title": "Java binary search (and get index if not there) review" }
8388
<p>I have the following routine that I would like to simplify:</p> <pre><code>public void SetUniform(RenderContext ctx, string uName, object value) { if (ctx == null) throw new ArgumentNullException("ctx"); if (value == null) throw new ArgumentNullException("value"); if (value is int) SetUniform(ctx, uName, (int)value); else if (value is Vertex2f) SetUniform(ctx, uName, (Vertex2f)value); else if (value is Vertex3f) SetUniform(ctx, uName, (Vertex3f)value); else if (value is Vertex4f) SetUniform(ctx, uName, (Vertex4f)value); else if (value is Matrix4x4) SetUniform(ctx, uName, (Matrix4x4)value); else throw new NotSupportedException(value.GetType() + " is not supporteds"); } </code></pre> <p>As you can read, the above routine is essentially the generic version of all <code>SetUniform</code>. I need this routine becuase I don't know the <code>value</code> type at compile time, but in this way I need to check its type at runtime each time I need it.</p> <p>How can I reduce this routine is a more simple and performant-wise way?</p> <hr> <p>Due the comments, I need to clarify some question that seems not enought clear.</p> <ul> <li>The "Uniform" state belongs to a specific class <code>ShaderProgram</code>, not to a wide set of classes (the ones listed on the snippet above are only a subset). Each <code>SetUniform</code> implementation access to the internal state of <code>ShaderProgram</code>, which I would not like expose, even using an internal modifier.</li> <li>The <em>SetUniform</em> overload with <em>object</em> parameter is required because I get the value using reflection, indeed I have no idea at compile time what is the value type. Indeed I have defined an additional overload which recall specific implementation.</li> <li>Each <code>SetUniform</code> overload have a different implementation. Specifically, they call the one of the routines specified <a href="http://www.opengl.org/sdk/docs/man/xhtml/glUniform.xml" rel="nofollow">here</a>.</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T12:21:59.307", "Id": "13115", "Score": "0", "body": "Could you not have some class hierarchy where you can have Vertex2f, Vertex3f implementing SomeInterface. Put the SetUniform method on the interface, then have the implementations on the classes. Standard OO programming - Why ask an object what type it is in order to decide which version of a method to call?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T19:51:33.017", "Id": "13139", "Score": "0", "body": "There's something I don't understand about this. Judging by the code, this is the generic version of `SetUniform` and you have five more overloads in the same class. In this case, if for example `(value is int)`, then why would the generic `SetUniform` get called instead of the specialized `SetUniform(.., .., int value)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T19:55:07.030", "Id": "13140", "Score": "0", "body": "Each SetUniform calls one of the glUniform* OpenGL routine. Standard OOP doesn't help here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T20:00:11.813", "Id": "13141", "Score": "0", "body": "@w0lf The values are retrieved using reflection, indeed I have an object value, and not a typed one." } ]
[ { "body": "<p>You can overload your SetUniform method with the different types of value:</p>\n\n<pre><code>public void SetUniform(int value)\n{\n\n}\npublic void SetUniform(Vertex2f value)\n{\n\n}\npublic void SetUniform(Vertex3f value)\n{\n\n}\n...\n</code></pre>\n\n<p>You could also try using the <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern#C.23\" rel=\"nofollow\">Null Object Pattern</a> to avoid the null checks or define some default behaviour.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T20:07:42.913", "Id": "13142", "Score": "0", "body": "I already have these overrides, the ones called by the generic one. Re-read question with more attention." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T20:56:03.257", "Id": "13143", "Score": "0", "body": "Then why do you need the generic one?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T20:58:17.020", "Id": "13144", "Score": "0", "body": "Because the value is retrieved using reflection." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T11:51:53.523", "Id": "8392", "ParentId": "8389", "Score": "1" } }, { "body": "<p>You could define a mapping between value type and a lambda that performs the required call:</p>\n\n<pre><code>class ShaderProgram\n{\n // The dictionary is static, so that it does not get recreated for every instance\n // of the class. In this case, however, the lambdas need to know the instance that\n // SetUniform should be called on\n private static readonly Dictionary&lt;Type, Action&lt;ShaderProgram, RenderContext, string, object&gt;&gt; _setterMapping = new Dictionary&lt;Type, Action&lt;ShaderProgram, RenderContext, string, object&gt;&gt;\n {\n {typeof(int), (instance, ctx, uName, value) =&gt; instance.SetUniform(ctx, uName, (int)value)},\n {typeof(Vertex2f), (instance, ctx, uName, value) =&gt; instance.SetUniform(ctx, uName, (Vertex2f)value)},\n {typeof(Vertex3f), (instance, ctx, uName, value) =&gt; instance.SetUniform(ctx, uName, (Vertex3f)value)},\n {typeof(Vertex4f), (instance, ctx, uName, value) =&gt; instance.SetUniform(ctx, uName, (Vertex4f)value)},\n {typeof(Matrix4x4), (instance, ctx, uName, value) =&gt; instance.SetUniform(ctx, uName, (Matrix4x4)value)},\n };\n\n public void SetUniform(RenderContext ctx, string uName, object value)\n {\n if (ctx == null)\n throw new ArgumentNullException(\"ctx\");\n\n if (value == null)\n throw new ArgumentNullException(\"value\");\n\n Action&lt;ShaderProgram, RenderContext, string, object&gt; setter;\n if (!_setterMapping.TryGetValue(value.GetType(), out setter))\n throw new NotSupportedException(value.GetType() + \" is not supported\");\n\n setter(this, ctx, uName, value);\n } \n}\n</code></pre>\n\n<p>Whether this is actually more performant would need to be profiled. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T09:36:14.953", "Id": "13962", "Score": "0", "body": "Good idea, but since I'm stick with .NET 2.0 I bind a delegate pointing to the method queries with reflection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T05:34:01.277", "Id": "13997", "Score": "0", "body": "In .NET 2.0, you don't have lambdas, but you do have [anonymous methods](http://msdn.microsoft.com/en-us/library/0yw3tz5k(v=vs.80).aspx). In both cases, however, you can use named static methods to achieve the same thing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T01:44:04.367", "Id": "8408", "ParentId": "8389", "Score": "1" } } ]
{ "AcceptedAnswerId": "8408", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T09:44:48.787", "Id": "8389", "Score": "4", "Tags": [ "c#", "reflection" ], "Title": "C# overload method simplification" }
8389
<p>I'm studying C on <em>K&amp;R</em> and I solved exercise 2.08:</p> <blockquote> <p>Write a function <code>rightrot(x,n)</code> that returns the value of the integer <code>x</code> rotated to the right by <code>n</code> positions</p> </blockquote> <p>I've tested my code with some bit patterns and it seems to work, but I'm not sure that this solution covers all possible cases.</p> <p>What do you think about this code?</p> <pre><code>unsigned rightrot(unsigned x, int n) { int size; unsigned y; size = 0; y = x; while (y != 0) { y = y &lt;&lt; BYTESIZE; size++; } size = size * BYTESIZE; return (x &lt;&lt; (size-n)) | (x &gt;&gt; n); } </code></pre> <p>Here is the main</p> <pre><code>#include &lt;stdio.h&gt; #define BYTESIZE 8 unsigned rightrot(unsigned x, int n); int main(void) { unsigned x; int n; x = 0x23acb; n = 2; printf("%x\n", rightrot(x, n)); return 0; } </code></pre>
[]
[ { "body": "<p>Isn't it something like this?</p>\n\n<pre><code>#include &lt;limits.h&gt; /* for CHAR_BIT */\n\nunsigned\nrotate_right(unsigned x, int n)\n{\n int left_shift = ((sizeof x) * CHAR_BIT) - n;\n return x&lt;&lt;left_shift | x&gt;&gt;n;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T22:27:43.520", "Id": "13146", "Score": "0", "body": "I'm aware of the existence of built in `sizeof` function but I can not use it because formally in the book it has not yet been explained. :-) Is it correct to calculate the size of `x` as I did or am I missing something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T13:13:02.143", "Id": "13216", "Score": "1", "body": "No. In your solution, if x==0, size is 0. Try for(size=0, y=~0; y; y<<=1, size++); (note the ; at the end of that)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-14T14:05:30.497", "Id": "87512", "Score": "0", "body": "+1. GCC 4.9 can optimize it to a simple `ror`. \nCheck [here](http://goo.gl/Yp2MQU). Lower versions can't though, even with higher optimization levels." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:17:04.663", "Id": "8396", "ParentId": "8390", "Score": "6" } }, { "body": "<p>@William has the optimum solution.</p>\n\n<p>But some comments on your code:</p>\n\n<pre><code>// There is already a macro that defines the number of bits\n// in a byte it is called CHAR_BIT\n#define BYTESIZE 8\n\n // Initialize variables as you declare them \n int size;\n unsigned y;\n\n // You can find the number of bytes in an object using\n // sizeof(&lt;expression&gt;) \n while (y != 0) {\n y = y &lt;&lt; BYTESIZE;\n size++;\n }\n\n // Thus the number of bits is:\n // sizeof(y) * CHAR_BIT\n size = size * BYTESIZE;\n\n // The result is the same.\n return (x &lt;&lt; (size-n)) | (x &gt;&gt; n);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T03:55:50.093", "Id": "8413", "ParentId": "8390", "Score": "3" } } ]
{ "AcceptedAnswerId": "8413", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T10:52:33.020", "Id": "8390", "Score": "5", "Tags": [ "c", "bitwise" ], "Title": "Bit rotations exercise" }
8390
<p>For quite a long, I have been using a pattern to make my life a bit easier. please help me evaluate how good or bad my approach is and how can I improve it.</p> <p>I have a static class for just returning values:</p> <pre><code> class ReturnValue { const STATUS_SUCCESS = "SUCCESS"; const STATUS_FAIL = "FAILED"; public static function doReturn($funtionName, $status = NULL, $value = NULL, $message = NULL) { if ($status == NULL) { $status = self::STATUS_FAIL; } $return = array( action =&gt; $funtionName, status =&gt; $status, message =&gt; $message, returnValue =&gt; $value ); return (object) $return; } } </code></pre> <p>usage example:</p> <pre><code> function add($val, $val2) { if (empty($val)) { return ReturnValue::doReturn(__FUNCTION__, ReturnValue::STATUS_FAIL, '', 'Val must be a number'); } if (empty($val2)) { return ReturnValue::doReturn(__FUNCTION__, ReturnValue::STATUS_FAIL, '', 'Val2 must be a number'); } $sum = $val + $val2; return ReturnValue::doReturn(__FUNCTION__, ReturnValue::STATUS_SUCCESS, $sum, "$val + $val2 = $sum"); } </code></pre> <p>To get the returned value:</p> <pre><code> $add = add(1, 2); print $add-&gt;returnValue; // Gives 1 + 2 = 3 print $add-&gt;message; // Gives "Val2 must be a number" print $add-&gt;status; // FAILED //OR to make an error $add = add(1, ''); // an empty param is passed print $add-&gt;returnValue;//Gives 3 print $add-&gt;message; // Gives "1 + 2 = 3" print $add-&gt;status; // SUCCESS </code></pre>
[]
[ { "body": "<p>I would prefer:</p>\n\n<pre><code>function add($left, $right) {\n if (!(isset($left, $right) &amp;&amp; is_numeric($left) &amp;&amp; is_numeric($right)))\n {\n throw new InvalidArgumentException(\n __METHOD__ . ' Left and Right arguments must be numeric.');\n }\n\n return $left + $right;\n}\n</code></pre>\n\n<p>The exception can then be caught at a level where you know how to deal with it.</p>\n\n<p>Usage:</p>\n\n<pre><code>try\n{\n print add(1, 2) . \"\\n\";\n print add(1, '') . \"\\n\";\n}\ncatch (Exception $e)\n{\n echo $e-&gt;getMessage();\n}\n</code></pre>\n\n<p>The calls to <code>add</code> are not mixed in with custom error handling, making it easier for other people to understand your code. It also removes the dependency on your ReturnValue class which makes your code more reusable. The exception allows you to let the code get back to an appropriate level where you can deal with your problem, rather than passing this information back up stack levels.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T20:30:02.717", "Id": "13196", "Score": "0", "body": "Actually I have become accustomed to the three return values for every function I call, i.e the \"status\" (SUCCESS | FAILED), \"returnValue\" and \"message\".\n\nThis is also helpful when calling some function via JAXAX, doing a json_ecode on the returned value makes this bit streamlined" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T12:51:13.823", "Id": "8394", "ParentId": "8391", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T11:21:35.463", "Id": "8391", "Score": "3", "Tags": [ "php", "design-patterns" ], "Title": "Is the way I use my pattern good enough?" }
8391
<p>I'd want an advise about the following idea that I have for organizing JavaScript when it comes to creating an HTML page. My group will be starting a new project and the approach that I'm trying to come up with will be large scale because every HTML page will be using it. Below I'll show a sample code and I'd like it to be reviewed and advised if you think that's a good approach. I did not find anywhere anything better it seems.</p> <p>There are 4 files:</p> <ul> <li><code>${root}/billing.html</code>: contains an input box for the name on credit card</li> <li><code>${root}/js/com/mycompany/common/common.js</code>: initializes logging and error handling</li> <li><code>${root}/js/com/mycompany/common/Url.js</code>: class that is used to perform an AJAX call</li> <li><code>${root}/js/com/mycompany/aproject/billing.js</code>: initializes things on the billing page</li> </ul> <p><code>common.js</code>:</p> <pre><code>var com_mycompany_common_common = function() { function log(message) { console.log((new Date()) + ': ' + message); } function init() { window.onerror = function(message) { log('Unhandled error: ' + message); } } return { log: log, init: init } } (); $(document).ready(function() { try { com_mycompany_common_common.init(); } catch (e) { console.log('Error during initialization: ' + e); } }); </code></pre> <p><code>Url.js</code>:</p> <pre><code>function com_mycompany_common_Url(url) { this.url = url; } com_mycompany_common_Url.prototype.addParameter(name, value) { this.url += '?' + name + '=' + value; } com_mycompany_common_Url.prototype.ajax() { com_mycompany_common_common.log('Send ajax to: ' + this.url); } </code></pre> <p><code>billing.js</code>:</p> <pre><code>var com_mycompany_aproject_billing = function() { function init() { $('#submitButton').click(function() { Url url = new com_mycompany_common_Url('http://bla.com/process/billing'); var creditCardName = $('#ccName').val(); url.addParameter('name', creditCardName); url.ajax(); } } return {init: init}; } (); $(document).ready(function() { try { com_mycompany_aproject_billing.init(); } catch (e) { com_mycompany_common_common.log('Error during initialization: ' + e); } }); </code></pre> <p><code>billing.html</code>:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Billing&lt;/title&gt; &lt;/head&gt; &lt;body&gt; Enter name on credit card: &lt;input type="text" id="ccName" /&gt;&lt;br&gt;&lt;br&gt; &lt;button id="submitButton"&gt;Submit Payment&lt;/button&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/com/mycompany/common/common.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/com/mycompany/common/Url.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/com/mycompany/aproject/billing.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T12:46:36.777", "Id": "13117", "Score": "0", "body": "@Raynos This is the stupidest comment I've ever seen. Can you please explain why your eyes are bleeding?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T13:31:03.820", "Id": "13120", "Score": "0", "body": "@Raynos I did not test it but my question is beyond running this code, I want to talk to people if this is a good strategy to apply to a large application. Things like code reuse and easy unit testing, with many people involved. You may be right in that maybe this forum is not meant for architectural questions but I don't know any other appropriate one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T13:40:55.633", "Id": "13124", "Score": "0", "body": "@Raynos I'll try not to from now on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T13:42:46.833", "Id": "13125", "Score": "0", "body": "I'll try not be such as ass from now on ;)" } ]
[ { "body": "<p>You have globals everywhere. Your cross module communication strategy is \"uniquely named globals everywhere\". I assume you know globals are bad but <a href=\"http://clux.github.com/modul8/docs/modularity.html\" rel=\"nofollow\">modul8 has a good article about it</a></p>\n\n<p>Use a <a href=\"https://gist.github.com/1694295\" rel=\"nofollow\">module bundling strategy</a> using tools like <a href=\"https://github.com/substack/node-browserify\" rel=\"nofollow\">browserify</a> or <a href=\"https://github.com/clux/modul8\" rel=\"nofollow\">modul8</a></p>\n\n<pre><code>// common.js\nfunction log(message) {\n console.log((new Date()) + ': ' + message);\n}\n\nwindow.onerror = function(message) {\n log('Unhandled error: ' + message);\n}\n\nmodule.exports = { log: log };\n</code></pre>\n\n<p>You just got rid of those ugly company names as your namespacing strategy. And you also removed that ugly boilerplate code. Here your common.js file exports an object with the log method</p>\n\n<pre><code>// Url.js\nvar log = require(\"common.js\").log;\n\nfunction Url(url) { \n this.url = url;\n}\n\nUrl.prototype.addParameter = function(name, value) {\n this.url += '?' + name + '=' + value;\n};\n\nUrl.prototype.ajax = function() {\n log('Send ajax to: ' + this.url);\n};\n\nmodule.exports = { Url: Url };\n</code></pre>\n\n<p>You Url module explicitly requires your common file. It now has the log method.</p>\n\n<pre><code>//billing.js\nvar Url = require(\"Url.js\").Url,\n $ = require(\"jQuery\");\n\n$('#submitButton').click(function() {\n var url = new Url('http://bla.com/process/billing');\n var creditCardName = $('#ccName').val();\n url.addParameter('name', creditCardName);\n url.ajax();\n}\n</code></pre>\n\n<p>And billing explicitly requires Url and jQuery.</p>\n\n<pre><code>// billing.html\n&lt;!DOCTYPE html&gt;\n\n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;Billing&lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n Enter name on credit card: &lt;input type=\"text\" id=\"ccName\" /&gt;&lt;br&gt;&lt;br&gt;\n &lt;button id=\"submitButton\"&gt;Submit Payment&lt;/button&gt;\n\n &lt;script type=\"text/javascript\" src=\"js/billing-bundle.js\"&gt;&lt;/script&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>And your billing html file loads a single precompiled billing bundle.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T13:39:25.730", "Id": "13123", "Score": "0", "body": "This looks awesome. Let me read up on it and get back." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T13:57:40.480", "Id": "13126", "Score": "0", "body": "I'm trying to grasp how browserify works behind the scenes. I want to ask you if I understand it correctly. There is a back-end service running. You make a single request and it returns JavaScript that is probably minified and all that stuff?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:11:00.790", "Id": "13127", "Score": "0", "body": "@SBel the idea is that these tools are build tools / compilers. You run them on your entry point file (billing.js) and they recursively find all dependencies and builds up a file with all the files in the right order so that `require` just works. [This gist shows how require works and all your files are wrapped in define(function () { });](https://gist.github.com/1615755). Of course you can do this on the fly but that's just slow, build it statically (just like you can gzip html/css on the fly but that's slow)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:15:10.880", "Id": "13128", "Score": "0", "body": "Aahhh, so you need to compile them yourself. If there doesn't exist some Eclipse plugin that auto compiles for you when you change a file then that will suck. But thanks for the general, I really appreciate it. And yeah, regarding your comment about on the fly would be slow I would expect a smart back-end service that would only \"compile\" if something changed, otherwise would cache." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:35:38.847", "Id": "13129", "Score": "0", "body": "@SBel the on the fly compilation is useful for dev builds. Personally [I use a makefile](https://github.com/Raynos/feature/blob/master/Makefile), so `make` runs the build step and opens the unit tests. Not ideal but pretty smooth." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:57:38.260", "Id": "13130", "Score": "0", "body": "I guess I could probably live with clicking on a button periodically to build and run tests. I'm now trying to get started with creating a script for that, it will be an ant script I think." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T15:17:35.713", "Id": "13131", "Score": "0", "body": "@SBel totally use node :P [example build file](https://github.com/Raynos/DOM-shim/blob/master/build.js)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T15:31:37.847", "Id": "13132", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/2320/discussion-between-sbel-and-raynos)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T13:27:00.813", "Id": "8395", "ParentId": "8393", "Score": "2" } }, { "body": "<p>How I normally do namespacing:</p>\n\n<pre><code>// File: MyNamespace.Log.js\n\nif (typeof(MyNamespace) === \"undefined\") {\n MyNamespace = {};\n}\n\nMyNamespace.Logger = (function () {\n return {\n log: function (message) {\n console.log(message);\n },\n\n warn: function (message) {\n console.warn(message);\n },\n\n error: function (message) {\n console.error(message);\n }\n };\n})();\n</code></pre>\n\n<hr>\n\n<pre><code>// File: MyNamespace.Url.js\nif (typeof(MyNamespace) === \"undefined\") {\n MyNamespace = {};\n}\n\nMyNamespace.Url = function (url) { \n this.url = url;\n};\n\nMyNamespace.Url.prototype.addParameter(name, value) {\n this.url += \"?\" + name + \"=\" + value;\n};\n\nMyNamespace.Url.prototype.ajax() {\n MyNamespace.Logger.log(\"Send ajax to: \" + this.url);\n};\n</code></pre>\n\n<hr>\n\n<pre><code>// File: MyNamespace.Billing.js\nif (typeof(MyNamespace) === \"undefined\") {\n MyNamespace = {};\n}\n\nvar MyNamespace.Billing = (function () {\n return {\n init: function () {\n $(\"#submitButton\").click(function () {\n var url = new MyNamespace.Url(\"http://bla.com/process/billing\");\n var creditCardName = $(\"#ccName\").val();\n url.addParameter(\"name\", creditCardName);\n url.ajax();\n });\n }\n };\n})();\n\n$(document).ready(function() {\n try {\n MyNamespace.Billing.init();\n } catch (e) {\n MyNamespace.Logger.log(\"Error during initialization: \" + e);\n }\n});\n</code></pre>\n\n<p>Note that it doesn't matter what order these files are included in, because there's only runtime dependencies. If you have definition-time dependencies, then they must be defined in the correct order. At this point, you could include them individually, or use something like YUI Compressor to bundle them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T02:34:01.790", "Id": "8484", "ParentId": "8393", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T12:33:07.480", "Id": "8393", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "JavaScript architecture example on an HTML page" }
8393
<p>I'm trying to solve the Spotify bestbefore programming challenge found here <a href="http://www.spotify.com/us/jobs/tech/best-before/" rel="nofollow">http://www.spotify.com/us/jobs/tech/best-before/</a></p> <p>I have written the code in Python but when I send it in, it says "Wrong Answer". I have checked my code for bugs many times but unable to find out what is wrong. I know the answers to other's people's code is on the web but I do not want to look at theirs. I'm a firm believer in self-integrity and I really want to solve this myself. I'm just trying to found out some test cases where my code below does not work. Thanks</p> <pre><code>import sys def values(year,month,day): valid = True #print "Debug: " + str(a) + " " + str(b) + " " + str(c) #Year fullYear = year if year &lt; 2000: fullYear = year + 2000 #Month if month &gt; 12: valid = False #Day if month in (4,6,9,11): if day &gt; 30: valid = False elif month == 2: is_leapyear = detectLeapyear(int(fullYear)) if (is_leapyear): if day &gt; 29: valid = False else: if day &gt; 28: valid = False else: if day &gt; 31: valid = False if not valid: return 0 else: return 1 def detectLeapyear(in_year): rem4 = in_year % 4 if not rem4: rem100 = in_year % 100 if not rem100: rem400 = in_year % 400 if not rem400: return 1 else: return 0 else: return 1 else: return 0 if __name__ == '__main__': for line in sys.stdin: #date = sys.argv[1] date = line.strip() sArray = date.split('/') validArray = [] x = int(sArray[0]) y = int(sArray[1]) z = int(sArray[2]) #year-month-day if values(x,y,z): validArray.append([x,y,z]) if values(x,z,y): validArray.append([x,z,y]) if values(y,x,z): validArray.append([y,x,z]) if values(y,z,x): validArray.append([y,z,x]) if values(z,x,y): validArray.append([z,x,y]) if values(z,y,x): validArray.append([z,y,x]) if validArray: validArray = sorted(validArray, reverse=False) #Zero Padding of Numbers if validArray[0][0] &lt; 2000: fyear = str(validArray[0][0] + 2000) if validArray[0][1] &lt; 10: fmonth = "0" + str(validArray[0][1]) else: fmonth = str(validArray[0][1]) if validArray[0][2] &lt; 10: fday = "0" + str(validArray[0][2]) else: fday = str(validArray[0][2]) #print "=&gt;" + str(validArray[0][0]) + "-" + str(validArray[0][1]) + "-" + str(validArray[0][2]) print fyear + "-" + fmonth + "-" + fday #print validArray else: print date + " is illegal" </code></pre> <p>These are the Test cases I have and they all seem to work:</p> <pre><code>12/11/10 02/4/67 31/9/73 31/12/2999 2000/6/12 2000/06/12 2000/12/6 2000/12/06 13/12/67 02/4/67 31/9/73 99/99/99 </code></pre> <p>Program output:</p> <pre><code>2010-11-12 2067-02-04 31/9/73 is illegal 2067-12-31 2067-06-12 2067-06-12 2067-06-12 2067-06-12 2067-12-13 2067-02-04 31/9/73 is illegal 99/99/99 is illegal </code></pre>
[]
[ { "body": "<p>I'm not sure if you can use the <code>sys.stdin</code>. I know it works with <code>data = raw_input()</code>, so you should probably use that.</p>\n\n<p>Also, in you programs inputs and outputs, there's some wrong dates. For some reason the output is 2067 even though you inputed 2000. I cannot see why this should be like that out from your code.</p>\n\n<p>Also, are you sure</p>\n\n<pre><code>validArray = sorted(validArray, reverse=False)\n</code></pre>\n\n<p>sorts the code properly? you know you should have the date on form [x &lt; y &lt; z]</p>\n\n<p>Other than that, I can't see why your code isn't working.</p>\n\n<p>Just a couple of things:</p>\n\n<ol>\n<li><p>Why do you use </p>\n\n<pre><code>if not valid:\n return 0\nelse:\n return 1\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>if valid:\n return 1\nelse:\n return 0\n</code></pre>\n\n<p>?</p></li>\n<li><p>I don't like this too much either:</p>\n\n<pre><code>def detectLeapyear(in_year):\n\n rem4 = in_year % 4\n if not rem4:\n rem100 = in_year % 100\n if not rem100:\n rem400 = in_year % 400\n if not rem400:\n return 1\n else:\n return 0\n else:\n return 1\n else:\n return 0\n</code></pre>\n\n<p>You should try this instead:</p>\n\n<pre><code>if in_year % 4 == 0:\n if in_year % 100 == 0:\n if in_year % 400 == 0:\n return 1\n else:\n return 0\n else:\n return 1\nelse:\n return 0:\n</code></pre></li>\n<li><p>In the <code>__main__</code> function, you shoud probable use a <code>for</code> function:</p>\n\n<pre><code>for year, month, date in ...\n</code></pre>\n\n<p>To do this, you probably have to rewrite your code a little bit. </p></li>\n</ol>\n\n<p>If you want to, you can look at my solution and the answers, that were really good. I see you can use some of the same tips as i got. <strong><a href=\"https://codereview.stackexchange.com/questions/8263/spotify-puzzle-problem-in-python\">Spotify Best Before Puzzle</a></strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T19:41:24.350", "Id": "8400", "ParentId": "8398", "Score": "0" } }, { "body": "<p>I just went over the <a href=\"http://dpaste.com/694498\" rel=\"nofollow\">last version of your code</a> you posted on freenode's #python, and there are two major errors in it:</p>\n\n<p>You never check if month or day are 0, and your month > 12 check gets overwritten by the later if clauses. With those fixed, it passes.</p>\n\n<p>Same issues are already in the code above, but I did not check if it has others as well.</p>\n\n<p>the flag variable approach is very error prone and hard that way - it would be better to return False right away if you determine that, not tag it along with the chance that it might get flipped back erroneously.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T06:34:14.977", "Id": "13211", "Score": "0", "body": "Thanks a lot this has fixed my problem and it was accepted as an answer. This has helped me learn python better, thanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T01:18:27.560", "Id": "8407", "ParentId": "8398", "Score": "1" } } ]
{ "AcceptedAnswerId": "8407", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T15:56:08.583", "Id": "8398", "Score": "2", "Tags": [ "python" ], "Title": "Spotify Bestbefore Coding Challenge in Python" }
8398
<p>I'm creating a factory design for math problems. The purpose of the factory is:</p> <ul> <li>The problems must be generated with a certain difficulty (or <code>level</code>). To do this, I've got an abstract method called ConfigureLevels.</li> <li>I set an abstract method called <code>Generate</code>, this one must be implemented in a concrete class.</li> </ul> <p>This is the factory design which I'm talking to.</p> <p><img src="https://i.stack.imgur.com/fynTw.png" alt="enter image description here"></p> <p>Here is the abstract <code>ProblemFactory</code>. </p> <ul> <li>The abstract factory provide a <code>Random</code> variable. </li> <li>Also contains a <code>CanConfigureXLevel()</code> which by default returns false, but if you want that will be available, just override it to true. <code>ConfigureXLevel()</code> is an abstract method which knows how to configure the level (returns <code>IConfigure</code>).</li> <li>Contains a dictionary which contains the available levels (<code>key:=Levels</code>, <code>value:=IConfiguration</code> which works like a container of objects usefull to generate the problem (for example binary and times tables both needs two bound objects)).</li> </ul> <p>_</p> <pre><code>public abstract class ProblemFactory { private IDictionary&lt;Levels, IConfiguration&gt; Configurations = new Dictionary&lt;Levels, IConfiguration&gt;(); protected Random Random = new Random(); public ProblemFactory() { LoadLevels(); } protected abstract Problem Generate(); public virtual bool CanConfigureEasyLevel() { return false; } public virtual bool CanConfigureMediumLevel() {return false; } public virtual bool CanConfigureHardLevel() {return false; } protected abstract IConfiguration ConfigureEasyLevel(); protected abstract IConfiguration ConfigureMediumLevel(); protected abstract IConfiguration ConfigureHardLevel(); private void LoadLevels() { if (CanConfigureEasyLevel()) { Configurations.Add(Levels.Easy, ConfigureEasyLevel()); } if (CanConfigureMediumLevel()) { Configurations.Add(Levels.Medium, ConfigureMediumLevel()); } if (CanConfigureHardLevel()) { Configurations.Add(Levels.Hard, ConfigureHardLevel()); } } private void Configure(Levels level) { if (!Configurations.ContainsKey(level)) throw new InvalidOperationException("Level not available"); // .. } } </code></pre> <p>And here is a concrete class, check how I'm overriding some <code>ConfigureXLevel</code> from the abstract <code>ProblemFactory</code>. The factory create additions problems, and it should know how to calculates.</p> <pre><code>public class AdditionProblemFactory : ProblemFactory { public AdditionProblemFactory(Levels level) : base(level) { //.. } public override Problem Generate(IConfiguration configuration) { int x = //.. x must receive a random number according to the configuration int y = //.. Operators op = //.. return ProblemA.CreateProblemA(x, y, op); } public override bool CanConfigureMediumLevel() { return true; } protected override IConfiguration ConfigureEasyLevel() { throw new NotImplementedException(); } protected override IConfiguration ConfigureMediumLevel() { BinaryProblemConfiguration configuration = new BinaryProblemConfiguration(); configuration.Bound1 = new Bound&lt;int&gt;(2, 10); configuration.Bound2 = new Bound&lt;int&gt;(2, 10); configuration.Operators = new List&lt;Operators&gt;() { Operators.Addition, Operators.Subtraction, Operators.Multiplication, Operators.Division }; return configuration; } protected override IConfiguration ConfigureHardLevel() { throw new NotImplementedException(); } } </code></pre> <p>And this is a <code>BinaryProblemConfiguration</code></p> <pre><code>public class BinaryProblemConfiguration : IConfiguration { public Bound&lt;int&gt; Bound1 { get; set; } public Bound&lt;int&gt; Bound2 { get; set; } public List&lt;Operators&gt; Operators { get; set; } public BinaryProblemConfiguration() { } public BinaryProblemConfiguration(Bound&lt;int&gt; bound1, Bound&lt;int&gt; bound2, List&lt;Operators&gt; operators) { this.Bound1 = bound1; this.Bound2 = bound2; this.Operators = operators; } } </code></pre> <p>The matter is in the <code>Generate method</code> from <code>AdditionProblemFactory</code> and <code>TimesTablesProblemFactory</code>, <code>x, y and operator variables</code> should receive random numbers according to the Level IConfiguration.</p> <p>Here is the part I don't know what I should modify of the design. Maybe is better move the random variable to IConfiguration and generate numbers there.</p> <p><strong>Here is the current project, don't worry it's so compact</strong> <em>(Factories => Infrastructure.FactoryCore | Configurations => Infrastructure.ConfigurationCore | BinaryProblem => ExerciseA):</em></p> <p><a href="http://www.mediafire.com/?rf3m1x9b1vdha1k" rel="nofollow noreferrer">http://www.mediafire.com/?rf3m1x9b1vdha1k</a></p>
[]
[ { "body": "<p>If I keep giving feedback on this project, I'll have to start charging consulting fees. :P</p>\n\n<pre><code>protected Random Random = new Random();\n</code></pre>\n\n<p>You should be sharing your Random object between all your ProblemFactories. Basically, you should only have one new Random in your entire program, and you should pass it around. </p>\n\n<blockquote>\n <p>Here is the part I don't know what I should modify of the design.\n Maybe is better move the random variable to IConfiguration and\n generate numbers there.</p>\n</blockquote>\n\n<p>The problem you are facing is that you've split BinaryProblemConfiguration and AdditionProblemFactory in an awkward way. The AdditionProblemFactory manages a collection of configuration as well as generating problems. That's two different things, and a class is best when it only does one thing. Move <code>Generate</code> into BinaryProblemConfiguration. </p>\n\n<p>As for Random, pass the reference to Generate() function on IConfiguration. </p>\n\n<pre><code>protected override IConfiguration ConfigureMediumLevel()\n{\n BinaryProblemConfiguration configuration = new BinaryProblemConfiguration();\n configuration.Bound1 = new Bound&lt;int&gt;(2, 10);\n configuration.Bound2 = new Bound&lt;int&gt;(2, 10);\n configuration.Operators = new List&lt;Operators&gt;() { Operators.Addition, Operators.Subtraction, Operators.Multiplication, Operators.Division };\n\n return configuration;\n}\n</code></pre>\n\n<p>Since BinaryProblemConfiguration is mostly concerned with holding configurations, this piece of code now seems out of place. Move it outside of the class like so:</p>\n\n<pre><code> BinaryProblemConfiguration configuration = new BinaryProblemConfiguration();\n configuration.Bound1 = new Bound&lt;int&gt;(2, 10);\n configuration.Bound2 = new Bound&lt;int&gt;(2, 10);\n configuration.Operators = new List&lt;Operators&gt;() { Operators.Addition, Operators.Subtraction, Operators.Multiplication, Operators.Division };\n problemFactory.AddConfiguration(Levels.Medium, configuration);\n</code></pre>\n\n<p>Now there is no addition specific logic in AdditionProblemFactory and you should be able to get rid of any subclasses and just have a ProblemFactory class. </p>\n\n<p>I'd then extend the problem factory so that it handles multiple types of problems. I.E. it would take a ProblemType and a Level rather then just a Level.</p>\n\n<pre><code>interface IConfiguration\n{\n IProblem Generate(Random random);\n}\n\nclass ProblemFactory\n{\n void AddConfiguration(ProblemType,Level,IConfiguration);\n IProblem Generate(ProblemType, Level);\n bool ProblemAvailable(ProblemType, Level);\n}\n\nclass AdditionProblemConfiguration : IConfiguration\n{\n...\n}\n\nclass SubtractionProblemConfiguration : IConfiguration\n{\n...\n}\n\nclass ProblemConfiguration\n{\n ProblemFactory StandardConfiguration()\n {\n ProblemFactory problemFactory = new ProblemFactory();\n // add configuration to problem factory\n // consider reading file to determine ranges of numbers for problems\n return problemFactory;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T05:00:00.413", "Id": "13166", "Score": "0", "body": "thanks for take a look Winston, but I have my doubth about the design, maybe because is midnight, but I can't understand how would I use the last three classes? And this one is off topic, I'm still learning about how create good designs, I really have difficulty creating these designs.. what books would you recomend me?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T23:47:55.540", "Id": "13269", "Score": "0", "body": "I agree with Winston about having just one Random instance. Without looking very closely, I don't see why you can't just have it as static protected in the most relevant (abstract?) base class. (As I proposed in my example the other day)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T00:15:23.543", "Id": "13270", "Score": "0", "body": "With the design that you propose. Supposing we need in addition problems the three levels (Easy, Medium and Hard), should I have three AdditionXProblemConfiguration?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T00:52:04.893", "Id": "13271", "Score": "0", "body": "@DarfZon, no. Like your BinaryProblemConfiguration the range of the values should be set by manipulating the properties of the object. No need for extra classes. You should set those properties in the ProblemConfiguration class. There you should create three versions of each and add them all to the problemFactory" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T04:43:33.747", "Id": "8415", "ParentId": "8401", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T20:27:03.907", "Id": "8401", "Score": "1", "Tags": [ "c#", "design-patterns" ], "Title": "How to add a random feature for a factory design" }
8401
<p>I have written a simple python program which takes a number from the user and checks whether that number is divisible by 2:</p> <pre><code># Asks the user for a number that is divisible by 2 # Keep asking until the user provides a number that is divisible by 2. print 'Question 4. \n' num = float(raw_input('Enter a number that is divisible by 2: ')) while (num%2) != 0: num = float(raw_input('Please try again: ')) print 'Congratulations!' </code></pre> <p>I would appreciate any feedback on this code, areas for improvement and/or things that I could have done differently.</p>
[]
[ { "body": "<p>Well, first of all, you should put code in an <code>if __name__ == '__main__':</code> block to make sure it doesn't run whenever the file is imported. Thus, just copy pasting:</p>\n\n<pre><code>if __name__ == '__main__':\n print 'Question 4. \\n'\n\n num = float(raw_input('Enter a number that is divisible by 2: '))\n while (num%2) != 0:\n num = float(raw_input('Please try again: '))\n\n print 'Congratulations!'\n</code></pre>\n\n<p>The next thing to notice is that a number being even is actually a fairly common check to make. Such things should be turned into functions. Mostly copy-pasting again:</p>\n\n<pre><code>def is_even(num):\n \"\"\"Return whether the number num is even.\"\"\"\n return num % 2 == 0\n\nif __name__ == '__main__':\n print 'Question 4. \\n'\n\n num = float(raw_input('Enter a number that is divisible by 2: '))\n while not is_even(num):\n num = float(raw_input('Please try again: '))\n\n print 'Congratulations!'\n</code></pre>\n\n<p>Notice the docstring: it's important to document your code, and while the purpose of <code>is_even</code> is obvious, getting into the habit of adding documentation is good. You could also put the following docstring at the top of the file:</p>\n\n<pre><code>\"\"\"Provide the is_even function.\n\nWhen imported, print prompts for numbers to standard output and read numbers\nfrom standard input separated by newlines until an even number is entered. Not\nentering an even number raises EOFError.\n\n\"\"\"\n</code></pre>\n\n<p>In my opinion, you should get into the habit of programs working on files, not on user input; you'll find that programs are much easier to chain that way.</p>\n\n<p>Possible further improvements are handling the <code>EOFError</code> (catching it and printing something like \"No even numbers entered.\"), splitting the repeating functionality into a <code>main</code> function (questionable use), and maybe adding a <code>read_float</code> function that would be something along the lines of</p>\n\n<pre><code>def read_float(prompt):\n \"\"\"Read a line from the standard input and return it as a float.\n\n Display the given prompt prior to reading the line. No error checking is done.\n\n \"\"\"\n return float(raw_input(prompt))\n</code></pre>\n\n<p>Here too, there is plenty of room for error checking.</p>\n\n<p>I removed the parentheses around <code>(num%2)</code> as I went along; <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> discourages these, if I remember correctly. Either way, it is a very valuable read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T10:50:28.050", "Id": "13171", "Score": "0", "body": "Thanks for the great feedback, I found it very helpful. You suggested that I put `if __name__ == '__main__':` into my code. Any I correct in thinking that the code will then only be run when the file is called directly? If so, how would you call the code indirectly through another file?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T11:16:04.523", "Id": "13173", "Score": "0", "body": "@TomKadwill - That is correct; if you feel the need to call it from another file, put it into a function (which is often called `main`), as far as I've seen." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T23:32:12.237", "Id": "8404", "ParentId": "8403", "Score": "3" } }, { "body": "<pre><code>print 'Question 4. \\n'\n\nnum = float(raw_input('Enter a number that is divisible by 2: '))\n</code></pre>\n\n<p>Some error-handling would be good here, because <code>float</code> will raise a <code>ValueError</code> if the input can't be converted.</p>\n\n<pre><code>while (num%2) != 0:\n</code></pre>\n\n<p>This is correct, but over-fussy. The parentheses are unnecessary, because <a href=\"http://docs.python.org/reference/expressions.html#index-80\" rel=\"nofollow\">python's precedence rules</a> mean that modulo will be evaluated before any comparison operators.</p>\n\n<pre><code> num = float(raw_input('Please try again: '))\n</code></pre>\n\n<p>The script should allow the user to exit gracefully if they don't want to continue.</p>\n\n<p>Here's one possible way to re-write your script based on the suggestions above:</p>\n\n<pre><code>print 'Question 4. \\n'\n\nprompt = 'Enter a number that is divisible by 2: '\n\nwhile True:\n data = raw_input(prompt)\n if data:\n try:\n number = float(data)\n except ValueError:\n print 'Invalid input...'\n else:\n if number % 2 == 0:\n print 'Congratulations!'\n break\n prompt = 'Please try again: '\n else:\n # allow the user to exit by entering nothing\n print 'Goodbye!'\n break\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T10:56:10.663", "Id": "13172", "Score": "0", "body": "Thanks for the feedback, particularly on error-handling. I can see how your script contains more error checking and is more elegant. I'll take this into account when writing my next script." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T00:51:02.487", "Id": "8405", "ParentId": "8403", "Score": "2" } } ]
{ "AcceptedAnswerId": "8404", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T22:25:57.030", "Id": "8403", "Score": "5", "Tags": [ "python" ], "Title": "Python 'check if number is divisible by 2' program" }
8403
<p>I wrote a little utility to check stdin for correct UTF-8, reporting any errors encountered, but I am concerned about its simplicity and performance. Could anyone take a look and suggest some improvements please?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdint.h&gt; int in, msz_byte, state = 0, cpbytes = 0; uint8_t byte; uint32_t cp; unsigned long long offset = 0; /* Find the position of the most significant zero bit in a byte. Return 0 to 7, or -1 if there is no zero bit. */ int msz(uint8_t value) { int r = 0; if (value == 0xff) return -1; value = ~value; while (value &gt;&gt;= 1) r++; return r; } /* Check if a codepoint is valid, returning 1 if so and 0 otherwise. Invalid codepoints include those higher than U+10ffff, any codepoint from U+fdd0 to U+fdef inclusive, as well as the last two codepoints in every plane, and all surrogate pair values (U+d800 to U+dfff inclusive). */ int valid(uint32_t cp) { return ( (cp &lt; 0x110000) &amp;&amp; ((cp &lt; 0xfdd0) || (cp &gt; 0xfdef)) &amp;&amp; ((cp &amp; 0xfffe) != 0xfffe) &amp;&amp; ((cp &amp; 0xfffff800) != 0xd800) ); } /* Print an error, then reset the parser state. */ char *errors[] = { "invalid byte (0xc0, 0xc1, 0xfe or 0xff)", "unexpected continuation byte; ASCII or start byte expected", "unexpected ASCII byte; continuation byte expected", "unexpected start byte; continuation byte expected", "invalid codepoint", "overlong sequence", "unexpected EOF while waiting for a continuation byte", }; void error(int i) { printf("%lld: %s\n", offset, errors[i]); state = 0; cpbytes = 0; } int main(void) { while ((in = getchar()) != EOF) { byte = in; msz_byte = msz(byte); if ( byte == 0xc0 || byte == 0xc1 || byte == 0xfe || byte == 0xff ) { error(0); goto next_byte; } switch (state) { case 0: if (msz_byte == 6) { error(1); goto next_byte; } if (msz_byte &gt;= 1 &amp;&amp; msz_byte &lt;= 5) { state = 6 - msz_byte; cp = (byte &amp; ((1 &lt;&lt; msz_byte) - 1)) &lt;&lt; (state * 6); cpbytes = 1; } break; case 1: case 2: case 3: case 4: case 5: if (msz_byte == 7) { error(2); goto next_byte; } else if (msz_byte &gt;= 1 &amp;&amp; msz_byte &lt;= 5) { error(3); goto next_byte; } else if (msz_byte == 6) { cp |= (byte &amp; 0x3f) &lt;&lt; (--state * 6); cpbytes++; if (!state) { if (!valid(cp)) { error(4); goto next_byte; } if ( (cp &lt;= 0x80) || (cp &lt;= 0x800 &amp;&amp; cpbytes &gt; 2) || (cp &lt;= 0x10000 &amp;&amp; cpbytes &gt; 3) || (cpbytes &gt; 4) ) { error(5); goto next_byte; } } } break; } next_byte: offset++; } if (state) error(6); return 0; } </code></pre> <p>Paul Martel's answer helped greatly, reducing runtime by 50% on a 10 MB all-zeros file, and reducing runtime by 80% on a 10 MB file of random bytes.</p> <pre><code>#include &lt;stdio.h&gt; #define ERROR(error) do {\ printf("%llu: %s\n", offset, errors[error]);\ needed = 0;\ continue;\ } while (0) char *errors[] = { "invalid byte (0xfe or 0xff)", "unexpected continuation byte; ASCII or start byte expected", "unexpected ASCII byte; continuation byte expected", "unexpected start byte; continuation byte expected", "invalid codepoint", "overlong sequence", "unexpected EOF while waiting for a continuation byte", }; int byte_type[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 7 }; unsigned long initial_cp[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x40, 0x80, 0xc0, 0x100, 0x140, 0x180, 0x1c0, 0x200, 0x240, 0x280, 0x2c0, 0x300, 0x340, 0x380, 0x3c0, 0x400, 0x440, 0x480, 0x4c0, 0x500, 0x540, 0x580, 0x5c0, 0x600, 0x640, 0x680, 0x6c0, 0x700, 0x740, 0x780, 0x7c0, 0, 0x1000, 0x2000, 0x3000, 0x4000, 0x5000, 0x6000, 0x7000, 0x8000, 0x9000, 0xa000, 0xb000, 0xc000, 0xd000, 0xe000, 0xf000, 0, 0x40000, 0x80000, 0xc0000, 0x100000, 0x140000, 0x180000, 0x1c0000, 0, 0x1000000, 0x2000000, 0x3000000, 0, 0x40000000, 0, 0 }; unsigned long min_cp[6] = { 0, 0x80, 0x800, 0x10000, 0x200000, 0x4000000 }; int main(void) { int in, needed = 0, needed_start; unsigned long cp; long long offset = -1; while ((in = getchar()) != EOF) { offset++; if (byte_type[in] == 7) ERROR(0); switch (needed) { case 0: if (byte_type[in] == 1) ERROR(1); else if (byte_type[in] != 0) { needed = byte_type[in] - 1; needed_start = needed; cp = initial_cp[in]; } break; case 1: if (byte_type[in] == 0) ERROR(2); else if (byte_type[in] &gt; 1) ERROR(3); else { cp |= in &amp; 0x3f; needed = 0; if ( (cp &gt; 0x110000) || ((cp &gt;= 0xfdd0) &amp;&amp; (cp &lt;= 0xfdef)) || ((cp &amp; 0xfffe) == 0xfffe) || ((cp &amp; 0xfffff800) == 0xd800) ) ERROR(4); if (cp &lt; min_cp[needed_start]) ERROR(5); } break; case 2: case 3: case 4: case 5: if (byte_type[in] == 0) ERROR(2); else if (byte_type[in] &gt; 1) ERROR(3); else cp |= (in &amp; 0x3f) &lt;&lt; (--needed * 6); break; } } if (needed) ERROR(6); return 0; } </code></pre> <p>One optimisation I made afterwards was to eliminate the getchar() function call overhead by reading and parsing 4096 bytes at a time. This cut down runtimes by at least another 50%.</p> <p>(fixed bugs where not enough state was retained)</p> <pre><code>#include &lt;stdio.h&gt; #define ERROR(error) do {\ printf("%llu: %s\n", state-&gt;offset, errors[error]);\ state-&gt;needed = 0;\ continue;\ } while (0) struct parser_state { long long offset; int needed; int needed_start; unsigned long cp; }; char *errors[] = { "invalid byte (0xfe or 0xff)", "unexpected continuation byte; ASCII or start byte expected", "unexpected ASCII byte; continuation byte expected", "unexpected start byte; continuation byte expected", "invalid codepoint", "overlong sequence", "unexpected EOF while waiting for a continuation byte", }; int byte_type[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 7 }; unsigned long initial_cp[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x40, 0x80, 0xc0, 0x100, 0x140, 0x180, 0x1c0, 0x200, 0x240, 0x280, 0x2c0, 0x300, 0x340, 0x380, 0x3c0, 0x400, 0x440, 0x480, 0x4c0, 0x500, 0x540, 0x580, 0x5c0, 0x600, 0x640, 0x680, 0x6c0, 0x700, 0x740, 0x780, 0x7c0, 0, 0x1000, 0x2000, 0x3000, 0x4000, 0x5000, 0x6000, 0x7000, 0x8000, 0x9000, 0xa000, 0xb000, 0xc000, 0xd000, 0xe000, 0xf000, 0, 0x40000, 0x80000, 0xc0000, 0x100000, 0x140000, 0x180000, 0x1c0000, 0, 0x1000000, 0x2000000, 0x3000000, 0, 0x40000000, 0, 0 }; unsigned long min_cp[6] = { 0, 0x80, 0x800, 0x10000, 0x200000, 0x4000000 }; void parse_block(struct parser_state *state, unsigned char *buf, long long len) { long i; for (i = 0; i &lt; len; i++) { state-&gt;offset++; if (byte_type[buf[i]] == 7) ERROR(0); switch (state-&gt;needed) { case 0: if (byte_type[buf[i]] == 1) ERROR(1); else if (byte_type[buf[i]] != 0) { state-&gt;needed = byte_type[buf[i]] - 1; state-&gt;needed_start = state-&gt;needed; state-&gt;cp = initial_cp[buf[i]]; } break; case 1: if (byte_type[buf[i]] == 0) ERROR(2); else if (byte_type[buf[i]] &gt; 1) ERROR(3); else { state-&gt;cp |= buf[i] &amp; 0x3f; state-&gt;needed = 0; if ( (state-&gt;cp &gt; 0x110000) || ((state-&gt;cp &gt;= 0xfdd0) &amp;&amp; (state-&gt;cp &lt;= 0xfdef)) || ((state-&gt;cp &amp; 0xfffe) == 0xfffe) || ((state-&gt;cp &amp; 0xfffff800) == 0xd800) ) ERROR(4); if (state-&gt;cp &lt; min_cp[state-&gt;needed_start]) ERROR(5); } break; case 2: case 3: case 4: case 5: if (byte_type[buf[i]] == 0) ERROR(2); else if (byte_type[buf[i]] &gt; 1) ERROR(3); else state-&gt;cp |= (buf[i] &amp; 0x3f) &lt;&lt; (--(state-&gt;needed) * 6); break; } } } int main(void) { size_t bufread; unsigned char buf[4096]; struct parser_state state = { -1, 0, 0, 0 }; while ((bufread = fread(buf, 1, 4096, stdin))) parse_block(&amp;state, buf, bufread); if (state.needed) puts(errors[6]); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T14:25:17.753", "Id": "13292", "Score": "0", "body": "The buffered version would fail to handle a multi-byte char crossing a 4k boundary unless needed_start and cp are part of parse_state, so that parse_block is essentially stateless as it exits. For performance, you might want to consider keeping them as locals and only reading/writing them on parse_state at parse_block entry/exit. Other candidates for caching in local vars for performance (and readability?) are `buf[i]` and/or `byte_type[buf[i]]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T14:45:48.297", "Id": "13293", "Score": "0", "body": "I prefer the more explicit original handling for `0xc0` and `0xc1` as `error(0)` and in fact (as I've already commented elsewhere) think you should build on it -- the first two 2s in byte_type should be 7s, (as well as the last two 4s and the 5s and 6s)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T04:31:34.037", "Id": "13319", "Score": "0", "body": "Thanks for catching that bug. I implemented state very quickly and forgot that needed_start and cp would need to be retained between blocks. With regards to the handling of start bytes that would generate overlongs or codepoints higher than U+10FFFF, the reason why I no longer catch any of them as explicitly invalid is because I think it is cleaner to catch them through the normal routes, and because explicit catching will cause several \"unexpected continuation byte; ASCII or start byte expected\" errors to follow once the parser state has been reset." } ]
[ { "body": "<p>Move all of these declarations into main where they are used (mostly) and pass them as arguments as needed elsewhere (like error).</p>\n\n<pre><code>int in, msz_byte, state = 0, cpbytes = 0;\nuint8_t byte;\nuint32_t cp;\nunsigned long long offset = 0;\n</code></pre>\n\n<p>Replace computations with vector lookups: replace <code>msz(value)</code> with <code>msz[value]</code> and eliminate the function.</p>\n\n<p>For performance, <code>valid(uint32_t)</code> is simple enough to expand inline in the one place it is called, reversing the sense to account for the <code>!</code>.</p>\n\n<p>Pass <code>offset</code> as an argument into <code>error</code>. Keep <code>state</code> within <code>main</code>; possibly reset it in an <code>ERROR</code> macro that calls <code>error</code>: </p>\n\n<pre><code>void error(int i, unsigned long long offset) {\n printf(\"%lld: %s\\n\", offset, errors[i]);\n}\n\nint main(void) {\n while ((in = getchar()) != EOF) {\n byte = in;\n msz_byte = msz(byte);\n</code></pre>\n\n<p>An <code>offset++</code> HERE instead of at the bottom of the loop, would allow you to just <code>continue;</code> when finished processing each char (error or no error) eliminating the <code>goto</code> and <code>break</code> statements that all go the same place, anyway. You'd just need to remember to use <code>offset-1</code> when reporting errors -- you can remember that in the <code>ERROR</code> macro that also remembers to reset state.</p>\n\n<pre><code> if (\n byte == 0xc0 ||\n byte == 0xc1 ||\n byte == 0xfe ||\n byte == 0xff\n ) {\n</code></pre>\n\n<p>There's a fair amount of redundancy around these error cases. <code>msz(0xff)</code> is currently treated as a hard-coded special-case returning -1, but that's actually a <em>don't care</em> value to the caller. So is <code>msz(0xfe)</code> -- the only case returning 0, which is valid but <em>way too subtle</em> justification for there being no later handling for <code>msz_byte&lt;1</code>. Possibly more useful than msz(int) or even msz[] would be something more general like <code>char_class[]</code> that gives one integer code (maybe -1) for these 4 error cases, another code (maybe 0) for ASCII chars, another for each of the 5 patterns that initiates a multi-byte sequence, and another (possibly 6) for continuation byte patterns. The code would be more readable if the values, especially the special values like -1, 0, and 6 were given named constants, or just use an enum. </p>\n\n<pre><code> error(0);\n goto next_byte;\n }\n switch (state) {\n case 0:\n if (msz_byte == 6) {\n error(1);\n goto next_byte;\n }\n if (msz_byte &gt;= 1 &amp;&amp; msz_byte &lt;= 5) {\n state = 6 - msz_byte;\n</code></pre>\n\n<p>The transformation from initial byte to initial codepoint could also be determined by vector lookup rather than repeated calculations, as in <code>cp = initial_cp[byte];</code>. Run your formula once per byte value to generate the vector, ideally in a separate program (simple code generator):</p>\n\n<pre><code> cp = (byte &amp; ((1 &lt;&lt; msz_byte) - 1)) &lt;&lt; (state * 6);\n</code></pre>\n\n<p><code>cpbytes</code> is an odd duck. Since it gets incremented exactly when state gets decremented, it always ends up with a value one greater than the original <code>state</code> value. There's less maintenance involved in just setting an <code>original_state = state;</code> once, here, and testing that later instead of cpbytes. </p>\n\n<pre><code> cpbytes = 1;\n }\n break;\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n if (msz_byte == 7) {\n error(2);\n goto next_byte;\n } else if (msz_byte &gt;= 1 &amp;&amp; msz_byte &lt;= 5) {\n error(3);\n goto next_byte;\n } else if (msz_byte == 6) {\n cp |= (byte &amp; 0x3f) &lt;&lt; (--state * 6);\n cpbytes++;\n\n if (!state) {\n</code></pre>\n\n<p><code>case 1:</code> is actually the only one that (ever and always) transitions to <code>(!state)</code>. It's simpler to rewrite/simplify (no shifting!) the generic code above for <code>case 1:</code> as a special case and only (unconditionally) adding the following code in that special case.</p>\n\n<pre><code> if (!valid(cp)) {\n error(4);\n goto next_byte;\n }\n if (\n (cp &lt;= 0x80) ||\n (cp &lt;= 0x800 &amp;&amp; cpbytes &gt; 2) ||\n (cp &lt;= 0x10000 &amp;&amp; cpbytes &gt; 3) ||\n (cpbytes &gt; 4)\n ) {\n</code></pre>\n\n<p>This is another example where a vector could be used to simplify things.\nPut the boundary values in a vector and have something like <code>if (cp &lt; min_cp[original_state])</code>.</p>\n\n<p>Since <code>cpbytes &gt; 4</code> corresponds exactly to <code>original_state &gt; 3</code>, it's strange to be eventually ruling out <em>all</em> <code>state==4</code> and <code>state==5</code> cases as:</p>\n\n<pre><code> error(5);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T07:38:54.993", "Id": "13280", "Score": "0", "body": "Oh, I just wanted to also respond to your last sentence. The reason is because any non-overlong sequences in five or six bytes (state == 4 or state == 5) are above U+10FFFF (not valid Unicode codepoints), and are caught by the valid(cp) test. Any sequences of five or six bytes that make it to the next test are implicitly overlong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T13:52:55.497", "Id": "13290", "Score": "0", "body": "That being the case, the validator should simply reject bytes from 0xf5 through 0xfd as illegal `error(0)` (expanding the error message) vs. `error(5)`. From the user view, the problem is likely a corrupt byte at *that* offset. `error(0)` at THAT point seems more indicative than `error(5)` at the end, or the more likely `error(2)` or `error(3)` wherever it happens to run out of continuation bytes (one to four bytes later)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T04:38:04.577", "Id": "13320", "Score": "0", "body": "I'm not really sure I agree on this particular point. If a stream contained `fd bc 95 86 b0 bf` for example, I think it would be more meaningful to report that the codepoint is too high at the end, rather than report that the start byte is quasi-invalid, followed by an error reported for each continuation byte which is no longer expected." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T04:23:29.193", "Id": "8485", "ParentId": "8406", "Score": "2" } } ]
{ "AcceptedAnswerId": "8485", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T01:11:36.730", "Id": "8406", "Score": "3", "Tags": [ "c", "performance" ], "Title": "Improving a UTF-8 'validator'" }
8406
<p>I have a very big class <code>Foo</code> that should be divided into <code>FooBar</code>, <code>FooUtility</code>, <code>FooBench</code>, <code>FooBranch</code>. Each of this "subclasses" should have different methods. So that if <code>Foo</code> has:</p> <pre><code>public function methodA(); public function methodB(); public function methodC(); public function methodZ(); </code></pre> <p>Then I should be able to divide them as I want. For example:</p> <pre><code>FooBar: public function __construct($param); public function methodA(); FooUtility: public function __construct($param); public function methodB(); FooBench: public function __construct($param); public function methodZ(); FooBranch: public function __construct($param); public function methodC(); </code></pre> <p>But I should be able to call <code>methodB()</code> and <code>methodZ()</code> from the same class <code>Foo</code>.</p> <p>How should I manage this division? Interfaces? Abstract classes? Inheritance? How?</p>
[]
[ { "body": "<p>With <a href=\"https://en.wikipedia.org/wiki/Composition_over_inheritance\" rel=\"nofollow noreferrer\">Composition</a>/<a href=\"https://secure.wikimedia.org/wikipedia/en/wiki/Aggregation_%28object-oriented_programming%29#Aggregation\" rel=\"nofollow noreferrer\">Aggregation</a>.</p>\n\n<p>first define your interface for Foo collecting all the public methods it should expose from the components:</p>\n\n<pre><code>interface Foo\n{\n public function methodA();\n public function methodB();\n …\n}\n</code></pre>\n\n<p>You could also create interfaces for the components and extend the Foo interface from those, e.g.</p>\n\n<pre><code>interface Foo extends FooBar, FooUtility\n{}\n</code></pre>\n\n<p>Note: it's not strictly necessary to have an interface collecting the other interfaces or to have an interface for Foo at all. However, since you should <a href=\"https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface\">program against an interface and not a concrete implementation</a>, it's cleaner.</p>\n\n<p>Then implement that in your conrete Foo implementation: </p>\n\n<pre><code>class FooImplementation implements Foo\n{\n public function __construct(FooBar $fooBar, FooUtility $fooUtility)\n {\n $this-&gt;fooBar = $fooBar;\n $this-&gt;fooUtility = $fooUtility;\n }\n public function methodA() \n { \n return $this-&gt;fooBar-&gt;methodA();\n } \n public function methodB()\n {\n return $this-&gt;fooUtility-&gt;methodB();\n }\n …\n}\n</code></pre>\n\n<p>Inject the various components through the ctor and then just have the methods on Foo delegate to the appropriate components.</p>\n\n<p>You can use use a Factory or Builder to encapsulate creation of the complex Foo type. This will allow you to parametrize the subcomponents:</p>\n\n<pre><code>class FooFactory\n{\n public function create($param1, $param2)\n {\n return new FooImplementation(\n new FooBar($param1), \n new FooUtility($param2)\n );\n }\n}\n</code></pre>\n\n<p>Note that Factory and Builder are creational patterns. They may control when and how objects are created, so if you want to reuse one of the components in subsequent calls to create, you may add logic to manage the component lifecycles in the factory/builder.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:21:05.510", "Id": "13149", "Score": "0", "body": "Isn't there a more flexible and less-hardcoded way? Also my Foo bar cannot accept parameters in the constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:23:46.900", "Id": "13150", "Score": "1", "body": "@JeffPigarelli How is this hardcoded? Why can your `Foo` not accept parameters?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:28:08.510", "Id": "13151", "Score": "1", "body": "Jeff: not until PHP 5.4 introduces traits. What you seem to want to achieve is multiple inheritance, and PHP does not support that. The pattern presented here by Gordon is a well accepted solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:28:24.480", "Id": "13152", "Score": "0", "body": "@CharlesSprayberry, It cannot. Foo is a sort of singleton class with a single instance injected in the main application class. (sort of dependency injection)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:29:22.020", "Id": "13153", "Score": "0", "body": "@JeffPigarelli What does `Foo` being a singleton have anything to do with passing it parameters?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:31:17.163", "Id": "13154", "Score": "0", "body": "@CharlesSprayberry Foo is called through `$this->foo` which trough `__get($class)` magical method returns just a normal single instance of the class `Foo`. All of this is just mechanic and all classes called in this way are well-known no-parameters-singleton classes in my application." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:31:26.590", "Id": "13155", "Score": "2", "body": "Words `Singleton` and `Dependency Injection` don't go well together. Just sayin." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:35:34.293", "Id": "13156", "Score": "0", "body": "@Mchl, yeah. :P. With \"Singleton\" I was just referring to a class that should have just one instance, not to the design pattern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:36:45.727", "Id": "13157", "Score": "0", "body": "@Jeff Did you know, Singleton is also brand of whiskey? You can drink one shot of it and it wont hurt. But drink the whole bottle and you cannot maintain yourself anymore. The same is true in programming. Too many singletons will make your code unmaintainable. Get rid of the Singletons. And also get rid of the magic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:37:30.110", "Id": "13158", "Score": "0", "body": "@Gordon, could you please show me an example of use of the class Foo?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:37:34.140", "Id": "13159", "Score": "0", "body": "@JeffPigarelli Again, I don't understand why you can't pass these parameters to `Foo`. I don't agree with your approach using Singletons but this shouldn't prevent you from injecting parameters into it. When you create the single instance of `Foo` pass `FooUtility` and `FooBar` to it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:39:37.770", "Id": "13160", "Score": "0", "body": "@Gordon, we have already had this conversation, d'you remember? I'm not using Singletons anymore. This \"magic\" way is just a stupid thing about me wanting to see hot \"$this->class\" things in my application. Don't even bother. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:42:25.540", "Id": "13161", "Score": "0", "body": "@JeffPigarelli yeah I remember :) The more suprised I was to see you ask this question. It seems I have to improve my explaining skills ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:43:07.147", "Id": "13162", "Score": "0", "body": "@CharlesSprayberry, I can't. How would I pass parameters to `$this->foo`? This is a method. I should filter `$class` in `__get($class)` and check whatever `$class = \"Foo\"` or not then manage it differently. This is kinda crazy and so hardcoded..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:43:48.800", "Id": "13163", "Score": "0", "body": "@Gordon, at least I'm not using `Foo::getInstance()`..." } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:18:10.097", "Id": "8411", "ParentId": "8410", "Score": "5" } } ]
{ "AcceptedAnswerId": "8411", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T14:10:11.230", "Id": "8410", "Score": "4", "Tags": [ "php", "object-oriented" ], "Title": "Divide big class in subclasses" }
8410
<p>I just wanted to share this script I wrote in that hopes that someone might find it useful and can hopefully simplify it(?).</p> <p>I'm very new to writing anything with jQuery, so this script is probably bulkier than it needs to be, but it does work. </p> <p>Here's the full HTML page:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;title&gt;Simple Slide Panel&lt;/title&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"&gt;&lt;/script&gt; &lt;style type="text/css"&gt; html{ height:100%;} body { margin: 0 auto; padding: 0; font: 75%/120% Arial, Helvetica, sans-serif; height:100% } #menu1 { background: #754c24; height: 100%; width:0px; float:right; overflow:hidden; } #menu2 { background: #fff; height: 100%; width:0px; float:right; overflow:hidden; } #nav-bar { background: #333; height: 100%; width:30px; float:right; } ul.nav-menu{ padding:0px; margin:0; } ul.nav-menu li{ list-style-type:none; padding:0px; width:10px; height:400px; } ul.nav-menu li a{ display:block; width:100px; padding:5px; position:relative; right:42px; top:60px; color:#fff; text-decoration:none; } ul.nav-menu li a.btn-2{ top:160px; } ul.nav-menu li a:hover{ background-color:#fff; color:#000; } .rotate { -webkit-transform: rotate(-90deg); /* Safari */ -moz-transform: rotate(-90deg); /* Firefox */ -ms-transform: rotate(-90deg); /* IE */ -o-transform: rotate(-90deg); /* Opera */ filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); /* Internet Explorer */ } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="menu1"&gt;This panel expands Too.&lt;/div&gt; &lt;div id="menu2"&gt;This panel expands&lt;/div&gt; &lt;div id="nav-bar"&gt; &lt;ul class="nav-menu"&gt; &lt;li&gt; &lt;a name="nav" href="#" class="btn-1 rotate"&gt;Slide Panel 1&lt;/a&gt; &lt;a name="nav" href="#" class="btn-2 rotate"&gt;Slide Panel 2&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/nav-bar--&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { var $menu1 = $('#menu1'); var $menu2 = $('#menu2'); $('.btn-1').toggle( function() { if ($menu1.width() == 250) { $('#menu1').animate({width: "0"}, 500); } else { $('#menu2').animate({width:'0px'},500); $('#menu1').delay(500).animate({width:'250px'},500); } }, function() { if ($menu1.width() == 250) { $('#menu1').animate({width: "0"}, 500); } else { $('#menu2').animate({width:'0px'},500); $('#menu1').delay(500).animate({width:'250px'},500); } }); $('.btn-2').toggle( function() { if ($menu2.width() == 250) { $('#menu2').animate({width: "0"}, 500); } else { $('#menu1').animate({width:'0px'},500); $('#menu2').delay(500).animate({width:'250px'},500); } }, function() { if ($menu2.width() == 250) { $('#menu2').animate({width: "0"}, 500); } else { $('#menu1').animate({width:'0px'},500); $('#menu2').delay(500).animate({width:'250px'},500); } }); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T14:27:36.787", "Id": "13219", "Score": "2", "body": "Just one quick tip, I see you set the menu1 and menu2 divs to variables and you use those variables in the if statements. You may want to also use the variables in place of the animate/delate calls as well. For instance: \n`$('#menu1').animate({width: \"0\"}, 500);`\ncould be\n`$menu1.animate({width: \"0\"}, 500);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T21:44:00.710", "Id": "13252", "Score": "1", "body": "Thank you, that is a cleaner way to do it. I'm also wondering if there is some way to set it up so the buttons could be created dynamically and wouldn't have to be set as variables. Still pretty new to writing javascript/jquery but I'm guessing using the sibling function may be a place to start." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-05T01:19:04.457", "Id": "13557", "Score": "1", "body": "@Levi: I'd upvote that if you write it as an asnwer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-05T01:33:57.617", "Id": "13558", "Score": "0", "body": "@Levi: i would upvote it too, but that's not saying much because i upvote everything" } ]
[ { "body": "<p>2 comments:</p>\n\n<ul>\n<li>Why are you passing the same function twice to <code>$.toggle()</code>? From the <a href=\"http://api.jquery.com/toggle/\" rel=\"nofollow\">documentation</a> it looks like it only takes 1 function, the <code>callback</code>.</li>\n<li><p>You can abstract out the common functionality in those functions into one:</p>\n\n<pre><code>function toggleMenu(menu, alternateMenu) {\n if (menu.width() == 250) {\n menu.animate({width: \"0\"}, 500);\n }\n else {\n alternateMenu.animate({width:'0px'},500);\n menu.delay(500).animate({width:'250px'},500);\n } \n};\n\n$(document).ready(function() { \n $('.btn-1').toggle(function() {\n toggleMenu($('#menu1'), $('#menu2'));\n });\n\n $('.btn-2').toggle(function() {\n toggleMenu($('#menu2'), $('#menu1'));\n });\n});\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-05T03:51:23.740", "Id": "8678", "ParentId": "8412", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T23:51:29.550", "Id": "8412", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "jQuery horizontal slide out navigation" }
8412
<p>I have a collision detection for terrain setup (non-terrain is handled with a quadtree I implemented apart from this) and I was wondering how others have done it compared to mine and what I could learn from people's critiques here.</p> <p>My map is stored in a 2D array of "GameSquare"s</p> <pre><code>public class GameSquare extends GameObject { private char tileLetter = 'W'; private int row, col; } public boolean isPassable() { return tileLetter != 'W'; } </code></pre> <p><li>The row and col are the index in the 2D array.</li> <li>The char corresponds to the graphic, my render checks the char and draws a Wall(W), Floor(O), or Door(X)</li><br> <b>The Player</b><br> My player class gets track of the player in pixels. The speed and X,Y positions are all in exact pixels. I divide those measures by the width or height of the tile graphics I use and truncate it; in order to find the corresponding array cell that the player is in. In order to do collision detection I wrote a method that takes a <strong>cardinal direction</strong>, the players current <strong>collision box</strong>, and a <strong>distance</strong> which is usually their speed.<br> The <strong>cardinal direction</strong> is an enum that has methods for the adjX and adjY.<br> For example; <strong>East</strong> would return <em>adjX() = 1</em> and <em>adjY() = 0</em> whereas<br> <strong>SouthEast</strong> would return <em>adjX() = 1</em> and <em>adjY() = 1</em> &lt;-- Positive because this is the movement in a 2D array. <br><br> <b>The Collision Check</b><br></p> <pre><code>public int canMove(Direction dir, Rectangle collisionBox, int distance) { int goodToGo = 0; // Check each 'step' of our attempted movement from 1 - distance(ie speed) for(int i = 1; i &lt;= distance; i++) { // Assemble suggested new position bounds to check, ie corners of suggested movement HashSet&lt;Vector2f&gt; cornerPoints = new HashSet&lt;Vector2f&gt;(); cornerPoints.add( new Vector2f(collisionBox.getMinX()+dir.adjX()*i, collisionBox.getMinY()+dir.adjY()*i) ); cornerPoints.add( new Vector2f(collisionBox.getMaxX()+dir.adjX()*i, collisionBox.getMinY()+dir.adjY()*i) ); cornerPoints.add( new Vector2f(collisionBox.getMinX()+dir.adjX()*i, collisionBox.getMaxY()+dir.adjY()*i) ); cornerPoints.add( new Vector2f(collisionBox.getMaxX()+dir.adjX()*i, collisionBox.getMaxY()+dir.adjY()*i) ); // Check each corner of this step for( Vector2f point : cornerPoints ) { // Out of bounds check if( point.y &lt; 0 || point.y &gt; this.dungeonHeight*ratioRow || point.x &lt; 0 || point.x &gt; this.dungeonWidth*ratioCol ) { return goodToGo; } // Figure out what map square this point falls on int checkX = (int) (point.x / ratioCol); int checkY = (int) (point.y / ratioRow); // If that's a wall square... no go, we're done here, return the number of steps that // were OKed so far if( this.dungeon[checkY][checkX].getTileLetter('W') ) { return goodToGo; } } // If this step, i, didn't have any conflicts on any of the proposed new corners, then // increment our ongoing count of how many steps are OK to take goodToGo++; } return goodToGo; } </code></pre> <p>I know blocks of code are kind of a bitch but any feedback or just shared attempts at 2D collision detection in Slick/Java are very appreciated. </p>
[]
[ { "body": "<p>That really looks quite slow.</p>\n\n<p>First of, don't use HashSet in these situations. A HashSet is a HashMap with \"blind\" values - like using the key as a value, too. They guarantee uniqueness and fast access (as everyone knows!), but for a set of <strong>four objects</strong> in a tight and often called loop, you are really hurting performance - the creation overhead is far too high and lookup speed isn't that great.</p>\n\n<p>Next, you should probably change your usage pattern. Don't store distances in <code>int</code> if everything else is <code>float</code>. Same goes the other way around - the conversion between <code>int</code> and <code>float</code> is not free and you should avoid it in code that has to be really fast.</p>\n\n<p>It looks like you never use fractional values and always integers - even in your floats - so you probaly think you can get away with them. They are used as painting positions for the tiles anyway.</p>\n\n<p>Still, even for pixel-precise games, as soon as you change to float, everything starts to get smoother. Because you get sub-pixel movements, which wouldn't be possible for <code>int</code>. You can't display them, but they still affect percieved smoothness. I'd go for float, always keep positional data as floats and only convert to int when I need it to draw stuff.</p>\n\n<p>Next, you can use a vastly better collision check method.</p>\n\n<p>Vastly better in most cases as least. If every object is rectangular, you'd be ok with your way - but there's a lot of conditionals involved and you end up with code like this:</p>\n\n<p><code>if (!(a.maxY &lt; b.minY || a.minY &gt; b.maxY)) blocked = true;</code> ....</p>\n\n<p>The other (better) way:</p>\n\n<p>Use bounding circles. For each object, you store <code>float x, y, boundsRadius;</code> - the center and the distance to the entities point with the largest distance from the center.</p>\n\n<p>Then... pythagoras (a*a + b*b = c*c)! For entities <code>e1</code> and <code>e2</code>:</p>\n\n<pre><code>public static boolean maybeCollision(Entity e1, Entity e2) {\n float xDistance = e1.x - e2.x,\n yDistance = e1.y - e2.y,\n rSum = e1.boundsRadius + e2.boundsRadius\n ;\n return xDistance * xDistance + yDistance * yDistance &lt; rSum * rSum;\n}\n</code></pre>\n\n<p>It's like calculating the distance - <code>Math.sqrt(dx * dx + dy * dy)</code> - but we don't use square root (which is on the slow side) and square the sum of the radius instead. You can use <code>float</code> or <code>int</code> - it doesn't matter as long as there is no overflow. Just change the local variables.</p>\n\n<p>I really love how it's totally independend of the orientation of the objects towards each other - you don't need any <code>if</code>s, the square of the distance automatically makes the result positive and it just works.</p>\n\n<p>Here, I call the method <code>maybeCollision</code> (and that's a bad name, as it's not a verb. Still fits!) because you still have to check per pixel - it sees anything inside of the circle as a collision. But it's lightning fast and you have to check with bounding boxes, too (as long as you don't write Tetris or a round-based Minecraft)...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:37:51.520", "Id": "14788", "ParentId": "8414", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T04:22:10.227", "Id": "8414", "Score": "3", "Tags": [ "java", "design-patterns", "api", "collision" ], "Title": "Java Slick 2D Collision Detection Methodology" }
8414
<p>I have a multiview to insert and edit users. Users are listed in a gridview. In <code>selectedindexchanged</code> event of gridview I've placed this code:</p> <pre><code>protected void GrvList_SelectedIndexChanged(object sender, EventArgs e) { // EditView FrmaddEditUsers.ActiveViewIndex = 1; // Get Username UserName.Text = GrvList.DataKeys[GrvList.SelectedIndex].Value.ToString(); } </code></pre> <p>I wonder if it's necessary to change it as below, being afraid of values are changed by bad users:</p> <pre><code>protected void GrvList_SelectedIndexChanged(object sender, EventArgs e) { // change to EditView FrmaddEditUsers.ActiveViewIndex = 1; // Get Username from gridview and display in txtbox string ToBeEditedUser = GrvList.DataKeys[GrvList.SelectedIndex].Value.ToString(); UserName.Text = HttpUtility.HtmlEncode(ToBeEditedUser); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T07:43:22.657", "Id": "130768", "Score": "0", "body": "Depends upon whether you have the view state enabled or not and where you get the values of your list." } ]
[ { "body": "<p>It certainly wouldn't do any harm and if you users have a backend that does not do something like encode when the user's name goes into the database then this will prevent any nasties. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T10:14:09.437", "Id": "8418", "ParentId": "8417", "Score": "1" } }, { "body": "<p>Since you are taking data from the user and passing it straight back, I would go with the encoded method. Also, on the serverside, since you are separating out the acquisition of the data from its reuse it should help with debugging.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-29T12:07:31.877", "Id": "10441", "ParentId": "8417", "Score": "1" } } ]
{ "AcceptedAnswerId": "10441", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T07:53:07.157", "Id": "8417", "Score": "2", "Tags": [ "c#", "asp.net" ], "Title": "Multiview for inserting and editing users" }
8417
<p>I recently tried my hand at CodeSprint2 through Interview Street. Having not coded in quite some time, I wasn't surprised that I had difficulty writing optimized code, but on one problem in particular I can't find where I've gone wrong. I've compared my code to successful algorithms used by other programmers, and I don't see much difference. I tried in both Java and Ruby and hit a wall at the 4th test case with both (I'm just learning Ruby so thought it would be a fun exercise to try it - I tweaked my algorithm a little in the process).</p> <p>The problem is Picking Cards and the description is <a href="http://cs2.interviewstreet.com/recruit/challenges/solve/view/4f0a70674f380/4effeea14e3a7" rel="nofollow">here</a>.</p> <p><strong>Code in Java:</strong></p> <pre><code>import java.io.*; import java.util.*; import java.math.*; public class Cards3 { public Cards3() { } public void run() { ArrayList&lt;Integer&gt; cards = new ArrayList&lt;Integer&gt;(); try{ /* BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String input = reader.readLine(); StringTokenizer tokenizer = new StringTokenizer(input); int T = Integer.parseInt(tokenizer.nextToken()); */ DataInputStream reader = new DataInputStream(System.in); int T = reader.readInt(); reader.readChar(); System.out.println("T = " + T); //read in and test each subsequence for(int i = 0; i&lt;T; i++) { /* input = reader.readLine(); tokenizer = new StringTokenizer(input); int N = Integer.parseInt(tokenizer.nextToken()); //read in and store cards String nextLine = reader.readLine(); tokenizer = new StringTokenizer(nextLine); */ int N = reader.readInt(); reader.readChar(); for(int j=0; j&lt;N; j++) { int next = reader.readInt();//Integer.parseInt(tokenizer.nextToken()); reader.readChar(); cards.add(next); } Collections.sort(cards); System.out.println(numWays(cards) % 1000000007); cards = new ArrayList&lt;Integer&gt;(); } reader.close(); } catch (IOException e) { System.out.println("Can not read input."); } } //computers the number of ways to pick up cards in currCards given that //numPicked cards have already been picked up public long numWays(ArrayList&lt;Integer&gt; cardsLeft) { int numPicked = 0; long numWays = 1; //calculate until all cards are picked up while(cardsLeft.size() &gt;= 1) { //if we can't pick up the next card, we're at a dead end - no solutions if(cardsLeft.get(0) &gt; numPicked) return 0; int numCanPick = 0; for(int i: cardsLeft) { if(i &lt;= numPicked) { numCanPick++; } else { break; } } cardsLeft.remove(0); numWays *= numCanPick; numWays = numWays % 1000000007; numPicked++; } return numWays; } public static void main(String args[]) { Cards3 d = new Cards3(); d.run(); } } </code></pre> <p><strong>Code in Ruby</strong></p> <pre><code>def runProgram answers = [] t = STDIN.gets.to_i t.times{ n = STDIN.gets numWays = 1 cards = STDIN.gets.split.map(&amp;:to_i) numPicked = 0 for i in 0...cards.length numCanPick = cards.count{|a| a&lt;= i} numWays = numWays * (numCanPick-i) break if numCanPick==0 numWays = numWays % 1000000007 end answers &lt;&lt; numWays } puts answers end if __FILE__ == $0 runProgram end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T21:42:49.473", "Id": "13251", "Score": "0", "body": "I was not able to find a \"Picking Cards\" problem from the link you provided. The closest I found was the 2011 challenge called \"Card Shuffling\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T16:25:19.000", "Id": "13305", "Score": "0", "body": "Try this oneL http://cs2.interviewstreet.com/recruit/challenges/dashboard/\n\nFrom there you should be able to click on Picking Cards. \n\nOr, here's a reprint of the problem from a blogger: http://www.programminglogic.com/codesprint-2-problem-picking-cards/" } ]
[ { "body": "<p>The immediate thing that jumps out to me is your use of an ArrayList for this. By continuously removing the first element, you force the array list to shift everything left one space each time (an O(n) operation assuming no underlying optimizations!)</p>\n\n<p>Instead of removing from the array list (incurring an expensive shift), I would recommend that you keep an index.</p>\n\n<pre><code> while(cardsLeft.size() &gt;= 1)\n {\n //if we can't pick up the next card, we're at a dead end - no solutions\n if(cardsLeft.get(0) &gt; numPicked)\n return 0;\n\n // ...\n for(int i: cardsLeft)\n { \n // ...\n }\n\n // ...\n\n cardsLeft.remove(0);\n // ...\n }\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code> int cardIndex = 0;\n while(cardIndex &lt; cardsLeft.length())\n {\n //if we can't pick up the next card, we're at a dead end - no solutions\n if(cardsLeft.get(cardIndex) &gt; numPicked)\n return 0;\n // ...\n for(int i = cardIndex; i &lt; cardsLeft.length(); ++i)\n { \n // ...\n }\n // ...\n\n //cardsLeft.remove(0);\n ++cardIndex\n // ...\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T16:24:08.907", "Id": "13304", "Score": "0", "body": "I made the change and still hit the time limit after 3 test cases." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T16:18:42.990", "Id": "8458", "ParentId": "8419", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T12:31:40.467", "Id": "8419", "Score": "3", "Tags": [ "java", "ruby", "programming-challenge" ], "Title": "\"Picking Cards\" challenge" }
8419
<p>I'm trying to refactor some code for unit testing and was hoping you could critique it.</p> <p>This is the original method:</p> <pre><code>public class MyNonRefactoredClass { public List&lt;MyClass&gt; DoSomething() { List&lt;MyClass&gt; data = GetData(); if (data.Count == 0) return new List&lt;MyClass&gt;(); data = GetFormattedData(data); if (data.Count == 0) return new List&lt;MyClass&gt;(); //Do some more stuff return data; } public List&lt;MyClass&gt; GetData() { //Do db query and return data } public List&lt;MyClass&gt; GetFormattedData(List&lt;MyClass&gt; Data) { //Do some logic on Data variable. Might return empty if data is not what I like } } </code></pre> <p>Here is my new approach. I have done it like this as I believe I need an entry point to try and access methods that I want to test.</p> <pre><code>public class MyRefactoredClass { public List&lt;MyClass&gt; DoSomething() { //Dependency Injection needs to work somehow here MySeparateClass newClass = new MySeperateClass(new DataProvider()); List&lt;MyClass&gt; dbData = newClass.GetData(); if (db.Data.Count == 0) return new List&lt;MyClass&gt;(); dbData = newClass.GetFormattedData(); if (db.Data.Count == 0) return new List&lt;MyClass&gt;(); //Continue method doing other things... } } public class MySeparateClass { private IDataProvider dbProvider; public MySeparateClass(IDataProvider DataProvider) { dbProvider = DataProvider; } public List&lt;MyClass&gt; GetData() { //Do DB stuff return dbProvider.GetData(); } public List&lt;MyClass&gt; GetFormattedData(List&lt;MyClass&gt; Data) { //Format } } [Test] public DoSomething_DBReturnsNoData_ReturnEmptyList() { //Setup mock of IDataProvider //Tell mock to not return data from GetData //Assert that result.count == 0 } [Test] public DoSomething_FormattedReturnsNoData_ReturnsEmptyList() { //Setup mock of IDataProvider //Tell mock to return some data from GetData //Setup mock of MySeparateClass //Tell mock to return no data from GetFormattedData //Assert that result.Count == 0 } </code></pre>
[]
[ { "body": "<p>Looking at your code I see three responsibilities:</p>\n\n<ul>\n<li>the Data Provider (component that hits the db)</li>\n<li>the Data Formatter</li>\n<li>the business service (your class) that uses the other two components to execute a business flow.</li>\n</ul>\n\n<p>According to the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">SRP</a>, one class should have one responsibility, so we should end up having three classes.</p>\n\n<p>Therefore, I'd separate out the data provider and formatter interfaces, like so:</p>\n\n<pre><code>public interface IDataProvider\n{\n List&lt;MyClass&gt; GetData();\n}\n\npublic interface IDataFormatter\n{\n List&lt;MyClass&gt; GetFormattedData(List&lt;MyClass&gt; data);\n}\n</code></pre>\n\n<p>and refactor our business class to use these dependencies:</p>\n\n<pre><code>public class RefactoredClass\n{\n private readonly IDataProvider _dataProvider;\n private readonly IDataFormatter _dataFormatter;\n\n public RefactoredClass(IDataProvider dataProvider, IDataFormatter dataFormatter)\n {\n _dataProvider = dataProvider;\n _dataFormatter = dataFormatter;\n }\n\n public List&lt;MyClass&gt; DoSomething()\n {\n var data = _dataProvider.GetData();\n\n if (data.Count == 0)\n return new List&lt;MyClass&gt;();\n\n data = _dataFormatter.GetFormattedData(data);\n\n if (data.Count == 0)\n return new List&lt;MyClass&gt;();\n\n //Do some more stuff\n\n return data;\n }\n}\n</code></pre>\n\n<p>Now you can write all relevant unit tests, for each system component in isolation:</p>\n\n<ul>\n<li>you can test <code>RefactoredClass</code> providing your mocks/stubs for the two dependencies</li>\n<li>you can test the DataFormatter(s) in separate unit test(s)</li>\n<li>you can test the concrete DataProvider using integration tests (since this component touches the database)</li>\n</ul>\n\n<p>Regarding Depenedency Injection, this is how you should compose this component somewhere in your application root:</p>\n\n<pre><code>var dataProvider = new SqlDataProvider();\nvar dataFormatter = new MySlickDataFormatter();\n\nvar businessComponent = new RefactoredClass(\n dataProvider,\n dataFormatter);\n</code></pre>\n\n<p>This technique of manually instantiating the needed component and its dependencies is called \"Poor man's DI\". If things get any more complicated, you should consider using <a href=\"http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx\">an IoC container</a> for this.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>Your tests make sense, but there are more tests to be added. For example, the formatting logic is not tested. </p>\n\n<p>Also, regarding your second test - you have no mocks in there. The <code>MySeparateClass</code> instance is the <em>system under test</em> and the <code>IDataProvider</code> instance is a <em>stub</em>. Your test <em>does</em> make sense; that's just a small naming issue.</p>\n\n<p>A <em>mock</em> is basically a fake instance that you assert against.</p>\n\n<p>If you google for \"mocks and stubs\" you'll find plenty of articles on this subject that you can read. I also recommend the book <em>\"The Art of Unit Testing\"</em> by Roy Osherove - a great resource on this subject.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T17:00:43.130", "Id": "13181", "Score": "0", "body": "Thanks. SRP makes perfect sense. Do my tests make sense in terms of mocking etc?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T17:27:52.510", "Id": "13184", "Score": "0", "body": "@Jon I have updated my response with a small review of the tests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T17:30:26.513", "Id": "13185", "Score": "0", "body": "Agreed, the second test with your changes would need a mock of IDataProvider and IDataFormatter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T18:17:21.197", "Id": "13186", "Score": "0", "body": "If we setup IDataProvider and IDataFormatter in the second test, arent they both mocks according to the below definition as we are expecting them both to return specific sets of data http://martinfowler.com/articles/mocksArentStubs.html#TheDifferenceBetweenMocksAndStubs" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T18:24:42.963", "Id": "13187", "Score": "0", "body": "Actually they might be both stubs according to this http://osherove.com/blog/2007/9/16/mocks-and-stubs-the-difference-is-in-the-flow-of-information.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T18:38:53.843", "Id": "13190", "Score": "0", "body": "The comment you wrote in the code, \"Tell mock to return...\" suggests that this is a stub. If it were a mock, the comment would have been \"verify that the mock received a call on method X with parameters Y\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T18:40:07.087", "Id": "13191", "Score": "0", "body": "Some mocking libraries (I've seen this in Moq) call all these objects *Mock*, but that's not exactly what they are. Whether an object is a stub or mock depends on how it's used inside a test." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T16:00:04.633", "Id": "8424", "ParentId": "8420", "Score": "6" } } ]
{ "AcceptedAnswerId": "8424", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T13:42:44.343", "Id": "8420", "Score": "3", "Tags": [ "c#", ".net", "unit-testing" ], "Title": "Refactoring legacy code for unit testing" }
8420
<p>I have just started reading through <a href="http://learnyouahaskell.com/" rel="nofollow">Learn you a Haskell</a> I got up to list comprehension and started to play around in GHCi, my aim was to make a times table function that takes a number <code>n</code> and an upper limit <code>upperLimit</code> and return a nested list of all the 'tables' up to <code>n</code> for example</p> <pre><code>&gt; timesTable 2 12 [[1,2..12],[2,4..24]] </code></pre> <p>the actual function/list comprehension I came up with is</p> <pre><code>&gt; let timesTable n upperLimit = [[(n-y) * x | x &lt;- [1..upperLimit]] | y &lt;- reverse [0..(n-1)]] </code></pre> <p>Any feedback on the above would be greatly appreciated as this is the first time I have really used a functional language, so if there is a better way or something I have missed please let me know. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T17:06:17.597", "Id": "13182", "Score": "0", "body": "Note that `reverse [0..(n-1)]` (even though it isn't needed, as Nicolas' answer shows) could be written `[(n-1),(n-2)..0]`." } ]
[ { "body": "<p>Your function could be simplified a little, and I find it helpful to define functions using declarations, since type signatures are really helpful (although admittedly your example is simple enough that it doesn't matter):</p>\n\n<pre><code>timesTable :: Int -&gt; Int -&gt; [[Int]]\ntimesTable n u = [[y * x | x &lt;- [1 .. u]] | y &lt;- [1 .. n]]\n</code></pre>\n\n<p>The key thing I noticed was that you were using <code>n-y</code>: it should be obvious that this part of the expression becomes the following values in each iteration of y: <code>[n-(n-1), n-(n-2), ... n-0]</code>, which is just <code>[1 .. n]</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T15:37:10.490", "Id": "13175", "Score": "0", "body": "Thanks, I had a feeling that there was something fishy and convoluted with what I had done, feeling a bit silly now because it is very obvious, am just reading the Types and Type Classes chapter which covers declarations, cheers" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T02:18:20.963", "Id": "13206", "Score": "0", "body": "We all have silly moments :-) I'm glad I could help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-09T23:57:21.003", "Id": "13831", "Score": "0", "body": "Is there a specific reason you chose `Int` rather than `Integer` or a polymorphic type?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T18:46:54.173", "Id": "13879", "Score": "0", "body": "Oh, not really. You'd choose Int over Integer if you were interested in efficiency, and your numbers aren't too big. You'd choose Integer for unbounded precision, and you'd use a Num class constraint if you wanted to stay flexible (at the cost of having to pass a dictionary around)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T15:23:45.497", "Id": "8422", "ParentId": "8421", "Score": "5" } }, { "body": "<p>We need no stinkin' list comprehensions. And multiplication is overrated as well...</p>\n\n<pre><code>timesTable n = scanl1 (zipWith (+)) . replicate n . enumFromTo 1 \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-09T20:45:31.837", "Id": "8826", "ParentId": "8421", "Score": "1" } } ]
{ "AcceptedAnswerId": "8422", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T15:04:57.970", "Id": "8421", "Score": "4", "Tags": [ "beginner", "haskell" ], "Title": "Multiplication table using a list comprehension" }
8421
<p>I have been following <a href="https://stackoverflow.com/questions/4801242/algorithm-to-calculate-number-of-intersecting-discs">this</a> question on SO, copied below. I put together a solution, but which is \$O(n^2)\$. In order to get a more efficient \$O(n \log n)\$ or \$O(\log n)\$ solution, I tried to sort that array, but could not get it solved hence would like to ask here how to optimize this solution to get it in less time complexity in C?</p> <blockquote> <p>Given an array <code>A</code> of <code>N</code> integers we draw <code>N</code> discs in a 2D plane, such that <code>i</code>-th disc has center in <code>(0,i)</code> and a radius <code>A[i]</code>. We say that the <code>k</code>-th disc and <code>j</code>-th disc intersect if they have at least one common point.</p> <p>Write a function</p> <pre><code>int number_of_disc_intersections(int[] A); </code></pre> <p>which given an array A describing N discs as explained above, returns the number of pairs of intersecting discs. For example, given N=6 and</p> <pre><code>A[0] = 1 A[1] = 5 A[2] = 2 A[3] = 1 A[4] = 4 A[5] = 0 </code></pre> <p>there are 11 pairs of intersecting discs:</p> <ol> <li>0th and 1st</li> <li>0th and 2nd</li> <li>0th and 4th</li> <li>1st and 2nd</li> <li>1st and 3rd</li> <li>1st and 4th</li> <li>1st and 5th</li> <li>2nd and 3rd</li> <li>2nd and 4th</li> <li>3rd and 4th</li> <li>4th and 5th</li> </ol> <p>so the function should return 11. The function should return -1 if the number of intersecting pairs exceeds 10,000,000. The function may assume that N does not exceed 10,000,000.</p> </blockquote> <p>C language solution:</p> <pre><code>int disc_intersecn(int *A,int N) { int i,j,cnt=0; /* qsort(A,N,sizeof(A[0]),sort_fn_ascend); for(i=0;i&lt;(N-1);i++) { if(i+A[i] &gt; (i+1-A[i+1])) { cnt++; } } */ for (i = 0; i &lt; N; i++) { for (j = i+1; j &lt; N; j++) { if (i + A[i] &gt;= j - A[j]) cnt++; } } return cnt; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T15:50:57.567", "Id": "13176", "Score": "0", "body": "Seeing as that question already has an answer explaining the method, why are you asking here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T16:01:14.787", "Id": "13177", "Score": "0", "body": "@WinstonEwert - Because I am trying to solve it in C , not in C#, Python, Java which are mentioned, and i did not get the explanation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T16:11:39.590", "Id": "13178", "Score": "0", "body": "He's also looking for an improved solution (meaning faster, more efficient). His example solution was simply to illustrate an O(N²) solution. Clearly there is room for improvement if a fancier solution is available." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T18:37:33.660", "Id": "13188", "Score": "0", "body": "What do you think somebody is going to give you here besides a description of the same algorithm?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T18:37:49.947", "Id": "13189", "Score": "0", "body": "@ToddLehman, yes. But his link already describes the fancier solution." } ]
[ { "body": "<p>Ajit,</p>\n\n<p>Essentially this is a problem of 1-dimensional collision detection.</p>\n\n<p>A useful tool for that is spatial-partitioning.</p>\n\n<p>The book <a href=\"http://rads.stackoverflow.com/amzn/click/1558607323\" rel=\"nofollow\">\"Real-Time Collision Detection\" by Christer Ericson (Morgan-Kaufmann, 2005)</a> contains a wealth of information. See pages 300–307 for an excellent discussion of 1-dimensional spatial hashing and pages 316—318 describing Morton keys. The code given there is in C++ but could easily be adapted to C.</p>\n\n<p>You can view a sample by clicking on \"Search Inside This Book\" at Amazon and then searching for \"Hierarchical Grids\". The 5th link or so is page 300.</p>\n\n<p>—Todd</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T16:32:01.540", "Id": "8425", "ParentId": "8423", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T15:30:43.107", "Id": "8423", "Score": "2", "Tags": [ "algorithm", "c", "computational-geometry", "complexity" ], "Title": "Finding the pairs of intersecting discs" }
8423
<p>I had to replace all instances of scientific notation with fixed point, and wrote a Python script to help out. Here it is:</p> <pre><code>#!/usr/bin/python2 # Originally written by Anton Golov on 29 Jan 2012. # Feedback can be sent to &lt;email&gt; . """Provide functions for converting scientific notation to fixed point. When imported, reads lines from stdin and prints them back to stdout with scientific notation removed. WARNING: The resulting fixed point values may be of a different precision than the original values. This will usually be higher, but may be lower for large numbers. Please don't rely on the precision of the values generated by this script for error analysis. """ from re import compile exp_regex = compile(r"(\d+(\.\d+)?)[Ee](\+|-)(\d+)") def to_fixed_point(match): """Return the fixed point form of the matched number. Parameters: match is a MatchObject that matches exp_regex or similar. If you wish to make match using your own regex, keep the following in mind: group 1 should be the coefficient group 3 should be the sign group 4 should be the exponent """ sign = -1 if match.group(3) == "-" else 1 coefficient = float(match.group(1)) exponent = sign * float(match.group(4)) return "%.16f" % (coefficient * 10**exponent) def main(): """Read lines from stdin and print them with scientific notation removed. """ try: while True: line = raw_input('') print exp_regex.sub(to_fixed_point, line) except EOFError: pass if __name__ == "__main__": main() </code></pre> <p>I am primarily interested about the way the regex is used (can it match something it can't replace?), but comments on code clarity and features that may be simple to add are also welcome, as well as any further nitpicking .</p>
[]
[ { "body": "<pre><code>from re import compile\n\n\nexp_regex = compile(r\"(\\d+(\\.\\d+)?)[Ee](\\+|-)(\\d+)\")\n</code></pre>\n\n<p>Python style guide recommends that global constants be in ALL_CAPS. And what about numbers like \"1e99\"? They won't match this regex.</p>\n\n<pre><code>def to_fixed_point(match):\n \"\"\"Return the fixed point form of the matched number.\n\n Parameters:\n match is a MatchObject that matches exp_regex or similar.\n\n If you wish to make match using your own regex, keep the following in mind:\n group 1 should be the coefficient\n group 3 should be the sign\n group 4 should be the exponent\n\n \"\"\"\n</code></pre>\n\n<p>I'd suggest breaking the groups out of the match into local variables</p>\n\n<pre><code>coefficient, decimals, sign, exponent = match.groups()\n</code></pre>\n\n<p>And then use those names instead of match.group(1). That way your code will be easier to follow.</p>\n\n<pre><code> sign = -1 if match.group(3) == \"-\" else 1\n coefficient = float(match.group(1))\n exponent = sign * float(match.group(4))\n return \"%.16f\" % (coefficient * 10**exponent)\n</code></pre>\n\n<p>Here's the thing. Python already support scientific notation, so you should just ask python to do conversion for you:</p>\n\n<pre><code> value = float(match.group(0))\n</code></pre>\n\n<p>Less bugs, more efficient, better all around.</p>\n\n<pre><code>def main():\n \"\"\"Read lines from stdin and print them with scientific notation removed.\n\n \"\"\"\n try:\n while True:\n line = raw_input('')\n print exp_regex.sub(to_fixed_point, line)\n except EOFError:\n pass\n</code></pre>\n\n<p>I'd suggest using <code>for line in sys.stdin:</code>. It'll automatically get you the lines, stop when the file ends. That'll make this piece of code simpler.</p>\n\n<pre><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T19:11:23.603", "Id": "8429", "ParentId": "8428", "Score": "2" } } ]
{ "AcceptedAnswerId": "8429", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T18:24:19.200", "Id": "8428", "Score": "2", "Tags": [ "python", "regex" ], "Title": "Python program for converting scientific notation to fixed point" }
8428
<p>I wrote this program that recursively prints all the files and directories starting at the current directory:</p> <pre><code>import Data.Tree (Tree (..)) import System.Directory (doesDirectoryExist, getCurrentDirectory, getDirectoryContents) main :: IO () main = do currentDirectory &lt;- getCurrentDirectory tree &lt;- tree currentDirectory "." printTree 0 tree printTree :: Int -&gt; Tree FilePath -&gt; IO () printTree indent tree = do putStrLn $ (replicate indent ' ' ++ rootLabel tree) mapM_ (printTree $ indent + 2) (subForest tree) treeHelper :: FilePath -&gt; IO [Tree FilePath] treeHelper path = let filter' = filter (`notElem` [".", ".."]) in do contents &lt;- getDirectoryContents path trees &lt;- mapM (tree path) (filter' contents) return trees tree :: FilePath -&gt; FilePath -&gt; IO (Tree FilePath) tree parent path = let fullPath = (parent ++ "/" ++ path) in do isDirectory &lt;- doesDirectoryExist fullPath case isDirectory of False -&gt; return $ Node path [] True -&gt; treeHelper fullPath &gt;&gt;= (return . Node (path ++ "/")) </code></pre> <p>If you run it, it might print something like this:</p> <pre><code>./ dist/ build/ autogen/ cabal_macros.h Paths_Tree.hs tree/ tree tree-tmp/ Main.hi Main.o package.conf.inplace setup-config Setup.lhs tree.cabal Tree.hs </code></pre> <p>I think this is pretty nifty. It's a toy program, so I purposefully left out stuff like error checking and symlink handling and etc. How would you improve this program? Am I duplicating functionality available in a library? Are there places where the code could be tighter? Is my Haskell style not up to snuff?</p>
[]
[ { "body": "<p>Paths should be manipulated with functions from <code>System.FilePath</code>. You can also move <code>let</code>'s inside the <code>do</code>'s, replace the <code>case</code> on <code>Bool</code> with an <code>if</code>, and squeeze out the helper function with <code>&lt;$&gt;</code>.</p>\n\n<pre><code>import Control.Applicative\nimport System.FilePath ((&lt;/&gt;), addTrailingPathSeparator)\n\ntree :: FilePath -&gt; FilePath -&gt; IO (Tree FilePath)\ntree parent path = do\n let fullPath = parent &lt;/&gt; path\n isDirectory &lt;- doesDirectoryExist fullPath\n if isDirectory\n then do\n paths &lt;- filter (`notElem` [\".\", \"..\"]) &lt;$&gt; getDirectoryContents fullPath\n Node (addTrailingPathSeparator path) &lt;$&gt; mapM (tree fullPath) paths\n else return $ Node path []\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T20:41:54.203", "Id": "8432", "ParentId": "8431", "Score": "7" } }, { "body": "<p>You can also use <code>unfoldTree</code> (or <code>unfoldTreeM</code> here) to build <code>Data.Tree</code>:</p>\n\n<pre><code>import Control.Monad\nimport System.Directory\nimport System.FilePath\nimport Data.Tree\n\n\ndirTree :: FilePath -&gt; IO (Tree FilePath)\ndirTree root = unfoldTreeM step (root,root)\n where step (f,c) = do\n fs &lt;- getDirectoryContents f\n ds &lt;- filterM doesDirectoryExist fs\n return (c, [(f &lt;/&gt; d, d) | d &lt;- ds, d /= \".\" &amp;&amp; d /= \"..\"])\n\nmain :: IO ()\nmain = do\n t &lt;- dirTree \".\"\n putStrLn $ drawTree t\n</code></pre>\n\n<p><strong>Update</strong>: As Björn Lindqvist correctly noted in his edit suggestion, my use of <code>doesDirectoryExist</code> doesn't work here (it uses directory <em>names</em> instead of directory <em>paths</em>).</p>\n\n<p>The correct version of <code>dirTree</code> would be:</p>\n\n<pre><code>dirTree :: FilePath -&gt; IO (Tree FilePath)\ndirTree root = unfoldTreeM step (root,root)\n where step (p, c) = do\n isDirectory &lt;- doesDirectoryExist p\n fs &lt;- if isDirectory then getDirectoryContents p else return []\n return (c, [(p &lt;/&gt; f, f) | f &lt;- fs, f `notElem` [\".\", \"..\"]])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T00:05:30.690", "Id": "8438", "ParentId": "8431", "Score": "8" } } ]
{ "AcceptedAnswerId": "8438", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T20:15:22.770", "Id": "8431", "Score": "16", "Tags": [ "haskell", "file-system" ], "Title": "Recursive directory tree printer" }
8431
<p>I'm writing a JavaScript/PHP file uploader and I want to start this project off on the right track. I've started with this, a JavaScript <code>Uploader</code> object which will handle Ajax calls, display progress, show error messages, etc. I'm just hoping to get some feedback on the way I'm setting up my scripts.</p> <pre><code>function Uploader(method) { if(arguments.callee._singleton) return arguments.callee._singleton; var _this = arguments.callee._singleton = this; _this.opts = { form:"#uploader", filePath:"public/uploads/", errorCodes:{ 1:"No file/folder selected", 2:"Invalid file/folder type", 3:"File/folder exceeds upload size" } } _this.methods = { init: function(options) { for(var o in options) { _this.opts[o] = options[o]; } _this.methods.setup(); }, setup: function() { } } if(_this.methods[method]) return _this.methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); else if(typeof method === "object" || !method) return methods.init.apply(this, arguments); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T00:31:58.017", "Id": "13203", "Score": "1", "body": "Can you elaborate on how exactly you'll be using this `Uploader` object? The `_singleton` code at the very top and the code at the very bottom (as well as the use of a local `_this` variable) is confusing." } ]
[ { "body": "<p>Why not use an existing ajax file upload library, like <a href=\"https://github.com/valums/file-uploader\" rel=\"nofollow noreferrer\">Fine Uploader</a>?</p>\n<p>As for your code.</p>\n<h1>1)</h1>\n<p>I think you meant to return <code>_this.methods.init.apply(this, arguments);</code>.</p>\n<h1>2)</h1>\n<p>You should rewrite Uploader to not use <code>arguments.callee</code> for two reasons; it makes your code harder to read and for the browser to optimize.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T17:20:59.680", "Id": "29110", "Score": "0", "body": "Not to mention `arguments.callee` isn't supported in ECMAScript 5." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T21:44:36.687", "Id": "15337", "ParentId": "8433", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T20:57:29.273", "Id": "8433", "Score": "3", "Tags": [ "javascript", "object-oriented", "ajax", "file" ], "Title": "JavaScript/PHP file uploader" }
8433
<p>Is there a very short way to do this same thing in a pure LINQ based way? It seems like I should not have to do all of this below to get to the <code>OrderBy</code>.</p> <pre><code>Dictionary&lt;DataColumn, DateTime&gt; columns = new Dictionary&lt;DataColumn, DateTime&gt;(); int startIndex; int endIndex; for (int i = 0; i &lt; table.Columns.Count; ++i) { // these columns need to be sorted startIndex = table.Columns[i].Caption.IndexOf('('); endIndex = table.Columns[i].Caption.IndexOf(')'); if (startIndex &gt; 0 &amp;&amp; endIndex &gt; 0) { // create a standard date string monthYear = table.Columns[i].Caption.Substring( startIndex + 1, endIndex - startIndex - 1); columns.Add( table.Columns[i], DateTime.Parse(monthYear.Replace("/", "/01/")).Date); } else { // all other columns should be sorted first columns.Add(table.Columns[i], DateTime.MinValue); } } // perform the LINQ order by columns = columns.OrderBy(o =&gt; o.Value).ToDictionary(o =&gt; o.Key, o =&gt; o.Value); // order the original table uses the dictionary for (int i = 0; i &lt; columns.Count; ++i) { table.Columns[columns.Keys.ElementAt(i).Caption].SetOrdinal(i); } </code></pre>
[]
[ { "body": "<p>It's not an answer to the question, but a local variable for <code>table.Columns[i]</code> and <code>caption</code> would improve the readability.</p>\n\n<p>Additionally, <code>startIndex</code> and <code>endIndex</code> could be declared inside the loop. (<a href=\"https://codereview.stackexchange.com/questions/6283/variable-declaration-closer-to-usage-vs-declaring-at-the-top-of-method\">Variable declaration closer to usage Vs Declaring at the top of Method</a>)</p>\n\n<pre><code>for (int i = 0; i &lt; table.Columns.Count; ++i)\n{ \n DataColumn column = table.Columns[i];\n string caption = column.Caption;\n // these columns need to be sorted\n int startIndex = caption.IndexOf('(');\n int endIndex = caption.IndexOf(')');\n if (startIndex &gt; 0 &amp;&amp; endIndex &gt; 0)\n {\n // create a standard date\n string monthYear = caption.Substring(\n startIndex + 1, endIndex - startIndex - 1);\n columns.Add(\n column, \n DateTime.Parse(monthYear.Replace(\"/\", \"/01/\")).Date);\n }\n else\n {\n // all other columns should be sorted first\n columns.Add(column, DateTime.MinValue);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T23:25:21.503", "Id": "8437", "ParentId": "8434", "Score": "1" } }, { "body": "<p>Throwing the contents into a dictionary will lose any sorting you may have had. Dictionaries are unordered collections.</p>\n\n<p>The cleanest way to deal with this really is to implement your own custom comparer to compare the columns and reset their order based on the ordering.</p>\n\n<p>I believe this would be more or less logically equivalent:</p>\n\n<pre><code>public class MyColumnComparer : Comparer&lt;DataColumn&gt;\n{\n static Regex re = new Regex(@\"[^\\(\\)][^\\(]*\\((\\d{2}/\\d{4})\\).*\");\n public override int Compare(DataColumn x, DataColumn y)\n {\n // a regular expression might be overkill here but it will be easier to maintain\n var xMatch = re.Match(x.Caption);\n var yMatch = re.Match(y.Caption);\n\n // both did not contain the pair\n if (!xMatch.Success &amp;&amp; !yMatch.Success)\n {\n // use original ordering\n return x.Ordinal.CompareTo(y.Ordinal);\n }\n\n // one contained the pair\n if (xMatch.Success != yMatch.Success)\n {\n return yMatch.Success ? -1 : 1;\n }\n\n // both contains a pair\n var xDate = DateTime.ParseExact(xMatch.Groups[1].Value, \"MM/yyyy\",\n CultureInfo.InvariantCulture);\n var yDate = DateTime.ParseExact(yMatch.Groups[1].Value, \"MM/yyyy\",\n CultureInfo.InvariantCulture);\n return xDate.CompareTo(yDate);\n }\n}\n</code></pre>\n\n\n\n<pre><code>static void ProcessTable(DataTable table)\n{\n var sortedColumns = table.Columns\n .Cast&lt;DataColumn&gt;()\n .OrderBy(col =&gt; col, new MyColumnComparer())\n .ToList();\n var index = 0;\n foreach (var column in sortedColumns)\n column.SetOrdinal(index++);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T01:38:06.520", "Id": "10474", "ParentId": "8434", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T21:11:46.103", "Id": "8434", "Score": "1", "Tags": [ "c#", "linq" ], "Title": "How to order DataColumns with LINQ?" }
8434
<p>I am creating a Minecraft like terrain engine in XNA, and am having problems when I render water, sayings that the "numVertices" passed should be greater then zero - which they should always be. The terrain is seperated into regions 32x32x32 in size and the vertex buffers are set as dirty when a block is added, but when a water block is added, the region on which it has been added has its BuildVertexBuffers Function called passed with the parameter "BufferType.Water".</p> <p>Here is the code:</p> <pre><code>private void BuildVertexBuffers(BufferType buffer) { if (buffer == BufferType.All || buffer == BufferType.None) { Console.WriteLine("FAAAAAAAAAAAAAAAAAAAAAAIL!"); } if (buffer == BufferType.Water) { WaterVertices = new List&lt;VertexPositionTextureLight&gt;(); WaterIndexList = new List&lt;short&gt;(); offsetWater = 0; } else if (buffer == BufferType.Lava) { } else { SolidVertices = new List&lt;VertexPositionTextureLight&gt;(); SolidIndexList = new List&lt;short&gt;(); offsetSolid = 0; } for (short x = 0; x &lt; Variables.REGION_SIZE_X; x++) { for (short y = 0; y &lt; Variables.REGION_SIZE_Y; y++) { for (short z = 0; z &lt; Variables.REGION_SIZE_Z; z++) { int X = (int)(index.X * Variables.REGION_SIZE_X + x); int Y = (int)(index.Y * Variables.REGION_SIZE_Y + y); int Z = (int)(index.Z * Variables.REGION_SIZE_Z + z); if (buffer == BufferType.Water &amp;&amp; world.GetBlock(X, Y, Z).BlockType == BlockType.waterStill) { BuildCube(buffer, WaterVertices, WaterIndexList, X, Y, Z, ref offsetWater); } else if (buffer == BufferType.Solid &amp;&amp; world.GetBlock(X, Y, Z).BlockType != BlockType.waterStill) { BuildCube(buffer, SolidVertices, SolidIndexList, X, Y, Z, ref offsetSolid); } } } } if (buffer == BufferType.Water) { if (WaterVertices.Count &gt; 0) { CopyToBuffers(ref WaterVertexBuffer, ref WaterIndices, WaterVertices, WaterIndexList); } else { WaterVertexBuffer = null; } } else if (buffer == BufferType.Lava) { } else { if (SolidVertices.Count &gt; 0) { CopyToBuffers(ref SolidVertexBuffer, ref SolidIndices, SolidVertices, SolidIndexList); } else { SolidVertexBuffer = null; } } } public void BuildCube(BufferType buffer, List&lt;VertexPositionTextureLight&gt; vertices, List&lt;short&gt; indices, int X, int Y, int Z, ref int offset) { bool above, below, left, right, front, back; above = !world.GetBlock(X, Y + 1, Z).TransparentSolid; below = !world.GetBlock(X, Y - 1, Z).TransparentSolid; left = !world.GetBlock(X - 1, Y, Z).TransparentSolid; right = !world.GetBlock(X + 1, Y, Z).TransparentSolid; front = !world.GetBlock(X, Y, Z + 1).TransparentSolid; back = !world.GetBlock(X, Y, Z - 1).TransparentSolid; bool notVisible = above &amp;&amp; below &amp;&amp; left &amp;&amp; right &amp;&amp; front &amp;&amp; back; if (notVisible) return; if (world.GetBlock(X, Y, Z).BlockType == BlockType.none) return; if (!back) BuildCubeFace(vertices, indices, world.GetBlock(X, Y, Z), new Vector3(X, Y, Z), BlockFaceDirection.ZDecreasing, ref offset); if (!front) BuildCubeFace(vertices, indices, world.GetBlock(X, Y, Z), new Vector3(X, Y, Z), BlockFaceDirection.ZIncreasing, ref offset); if (!above) BuildCubeFace(vertices, indices, world.GetBlock(X, Y, Z), new Vector3(X, Y, Z), BlockFaceDirection.YIncreasing,ref offset); if (!below) BuildCubeFace(vertices, indices, world.GetBlock(X, Y, Z), new Vector3(X, Y, Z), BlockFaceDirection.YDecreasing, ref offset); if (!right) BuildCubeFace(vertices, indices, world.GetBlock(X, Y, Z), new Vector3(X, Y, Z), BlockFaceDirection.XIncreasing, ref offset); if (!left) BuildCubeFace(vertices, indices, world.GetBlock(X, Y, Z), new Vector3(X, Y, Z), BlockFaceDirection.XDecreasing, ref offset); } public void BuildCubeFace(List&lt;VertexPositionTextureLight&gt; vertices, List&lt;short&gt; indices, Block block, Vector3 pos, BlockFaceDirection blockFaceDirection, ref int offset) { Vector3 topLeftFront = new Vector3(0f, 1f, 0f) + pos; Vector3 bottomLeftFront = new Vector3(0f, 0f, 0f) + pos; Vector3 topRightFront = new Vector3(1f, 1f, 0f) + pos; Vector3 bottomRightFront = new Vector3(1f, 0f, 0f) + pos; Vector3 topLeftBack = new Vector3(0f, 1f, -1f) + pos; Vector3 topRightBack = new Vector3(1f, 1f, -1f) + pos; Vector3 bottomLeftBack = new Vector3(0f, 0f, -1f) + pos; Vector3 bottomRightBack = new Vector3(1f, 0f, -1f) + pos; Vector3 upNormal = new Vector3(0, 1, 0); Vector3 downNormal = new Vector3(0, -1, 0); Vector3 leftNormal = new Vector3(-1, 0, 0); Vector3 rightNormal = new Vector3(1, 0, 0); Vector3 backNormal = new Vector3(0, 0, -1); Vector3 frontNormal = new Vector3(0, 0, 1); int row = (int)block.BlockType / Variables.TILE_ALAIS.NumberOfColumns; int column = (int)block.BlockType - row * Variables.TILE_ALAIS.NumberOfColumns; float unit = 1.0f / (float)Variables.TILE_ALAIS.NumberOfColumns; float x = column * unit; float y = row * unit; Vector2 topLeft = new Vector2(x, y); Vector2 topRight = new Vector2(x + unit, y); Vector2 bottomLeft = new Vector2(x, y + unit); Vector2 bottomRight = new Vector2(x + unit, y + unit); float light = 12; switch (blockFaceDirection) { case BlockFaceDirection.ZIncreasing: light = world.GetLight((int)(frontNormal.X + pos.X), (int)(frontNormal.Y + pos.Y), (int)(frontNormal.Z + pos.Z)); vertices.Add(new VertexPositionTextureLight(bottomLeftFront, frontNormal, bottomLeft, light)); vertices.Add(new VertexPositionTextureLight(bottomRightFront, frontNormal, bottomRight, light)); vertices.Add(new VertexPositionTextureLight(topLeftFront, frontNormal, topLeft, light)); vertices.Add(new VertexPositionTextureLight(topRightFront, frontNormal, topRight, light)); AddIndices(indices, 0, 2, 3, 3, 1, 0, ref offset); break; case BlockFaceDirection.ZDecreasing: light = world.GetLight((int)(backNormal.X + pos.X), (int)(backNormal.Y + pos.Y), (int)(backNormal.Z + pos.Z)); vertices.Add(new VertexPositionTextureLight(bottomRightBack, backNormal, bottomLeft, light)); vertices.Add(new VertexPositionTextureLight(bottomLeftBack, backNormal, bottomRight, light)); vertices.Add(new VertexPositionTextureLight(topRightBack, backNormal, topLeft, light)); vertices.Add(new VertexPositionTextureLight(topLeftBack, backNormal, topRight, light)); AddIndices(indices, 0, 2, 3, 3, 1, 0, ref offset); break; case BlockFaceDirection.YIncreasing: light = world.GetLight((int)(upNormal.X + pos.X), (int)(upNormal.Y + pos.Y), (int)(upNormal.Z + pos.Z)); vertices.Add(new VertexPositionTextureLight(topLeftFront, upNormal, bottomLeft, light)); vertices.Add(new VertexPositionTextureLight(topRightFront, upNormal, bottomRight, light)); vertices.Add(new VertexPositionTextureLight(topLeftBack, upNormal, topLeft, light)); vertices.Add(new VertexPositionTextureLight(topRightBack, upNormal, topRight, light)); AddIndices(indices, 0, 2, 3, 3, 1, 0, ref offset); break; case BlockFaceDirection.YDecreasing: light = world.GetLight((int)(downNormal.X + pos.X), (int)(downNormal.Y + pos.Y), (int)(downNormal.Z + pos.Z)); vertices.Add(new VertexPositionTextureLight(bottomLeftBack, downNormal, bottomLeft, light)); vertices.Add(new VertexPositionTextureLight(bottomRightBack, downNormal, bottomRight, light)); vertices.Add(new VertexPositionTextureLight(bottomLeftFront, downNormal, topLeft, light)); vertices.Add(new VertexPositionTextureLight(bottomRightFront, downNormal, topRight, light)); AddIndices(indices, 0, 2, 3, 3, 1, 0, ref offset); break; case BlockFaceDirection.XIncreasing: light = world.GetLight((int)(rightNormal.X + pos.X), (int)(rightNormal.Y + pos.Y), (int)(rightNormal.Z + pos.Z)); vertices.Add(new VertexPositionTextureLight(bottomRightFront, rightNormal, bottomLeft, light)); vertices.Add(new VertexPositionTextureLight(bottomRightBack, rightNormal, bottomRight, light)); vertices.Add(new VertexPositionTextureLight(topRightFront, rightNormal, topLeft, light)); vertices.Add(new VertexPositionTextureLight(topRightBack, rightNormal, topRight, light)); AddIndices(indices, 0, 2, 3, 3, 1, 0,ref offset); break; case BlockFaceDirection.XDecreasing: light = world.GetLight((int)(leftNormal.X + pos.X), (int)(leftNormal.Y + pos.Y), (int)(leftNormal.Z + pos.Z)); vertices.Add(new VertexPositionTextureLight(bottomLeftBack, leftNormal, bottomLeft, light)); vertices.Add(new VertexPositionTextureLight(bottomLeftFront, leftNormal, bottomRight, light)); vertices.Add(new VertexPositionTextureLight(topLeftBack, leftNormal, topLeft, light)); vertices.Add(new VertexPositionTextureLight(topLeftFront, leftNormal, topRight, light)); AddIndices(indices, 0, 2, 3, 3, 1, 0, ref offset); break; } } public void AddIndices(List&lt;short&gt; IndexList, short i0, short i1, short i2, short i3, short i4, short i5, ref int offset) { IndexList.Add((short)(i0 + offset)); IndexList.Add((short)(i1 + offset)); IndexList.Add((short)(i2 + offset)); IndexList.Add((short)(i3 + offset)); IndexList.Add((short)(i4 + offset)); IndexList.Add((short)(i5 + offset)); offset += 4; } private void CopyToBuffers(ref VertexBuffer vertexBuffer, ref IndexBuffer indexBuffer, List&lt;VertexPositionTextureLight&gt; vertices, List&lt;short&gt; indices) { vertexBuffer = new VertexBuffer(Variables.GRAPHICS_DEVICE, VertexPositionTextureLight.VertexDeclaration, vertices.Count, BufferUsage.WriteOnly); vertexBuffer.SetData(vertices.ToArray()); indexBuffer = new IndexBuffer(Variables.GRAPHICS_DEVICE, typeof(short), indices.Count, BufferUsage.WriteOnly); indexBuffer.SetData(indices.ToArray()); } public void QueueForBuild(BufferType buffer) { if (buffer == BufferType.All) { QueueForBuild(BufferType.Solid); QueueForBuild(BufferType.Water); QueueForBuild(BufferType.Lava); } else if (!bufferQueued.Contains(buffer)) { bufferQueued.Enqueue(buffer); } } public void QueueForBuild(Block block) { if (block.BlockType == BlockType.waterStill) { QueueForBuild(BufferType.Water); } else if (block.BlockType == BlockType.lavaStill) { QueueForBuild(BufferType.Lava); } else { QueueForBuild(BufferType.Solid); } } </code></pre> <p>Any ideas? Note also that transparent blocks are either water, glass or air.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T04:00:21.350", "Id": "13208", "Score": "0", "body": "Could you please at least state what method is throwing the exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T09:52:57.857", "Id": "13215", "Score": "1", "body": "If the code is not working, this is a question for StackOverflow." } ]
[ { "body": "<p>Now that there is working code, we can review it. :)</p>\n\n<p>Comments:</p>\n\n<ul>\n<li>Class variables should use PascalCase;</li>\n<li>Local variables should use camelCase;</li>\n<li>You should avoid having <code>x</code> and <code>X</code> in the same scope, that is really asking for bugs...</li>\n<li>Taking into consideration <code>BufferType.All</code> and <code>BufferType.None</code>, you should probably look into using the <code>[Flags]</code> attribute, if you are not yet;</li>\n</ul>\n\n<hr>\n\n<p>Proposed code review of your answer code:</p>\n\n<pre><code>namespace QuarryCraft\n{\n public static class Extensions\n {\n public static int GetRow(this BlockType type) {\n int index;\n switch (type) {\n default:\n throw new NotImplementedException();\n }\n return index / Variables.TILE_ALAIS.NumberOfRows; // You probably had a bug here, you were using Variables.TILE_ALAIS.NumberOfColumns\n }\n public static int GetColumn(this BlockType type) {\n int index;\n switch (type) {\n default:\n throw new NotImplementedException();\n }\n return index / Variables.TILE_ALAIS.NumberOfColumns;\n }\n }\n\n public class World\n {\n // Really useful way of acessing!\n public Block this[int x, int y, int z] {\n get {\n throw new NotImplementedException();\n }\n set {\n throw new NotImplementedException();\n }\n }\n // ...\n }\n\n public class Block\n {\n public BlockType BlockType { get; private set; }\n public bool IsTransparentSolid { get; private set; }\n // ...\n }\n\n [Flags]\n public enum BufferType\n {\n None = 0,\n Water = 1,\n Solid = 2,\n Air = 4,\n Lava = 10,\n All = 15\n }\n public enum BlockType\n {\n // you had camelCase, should be PascalCase\n None,\n WaterStill,\n LavaStill\n }\n\n public class Something\n {\n World World;\n // ...\n\n private void BuildVertexBuffers(BufferType buffer) {\n if (buffer == BufferType.All || buffer == BufferType.None) {\n // I have the feeling you should either throw an exception or return.\n // Use Debug.WriteLine() instead of Console.WriteLine()\n Debug.WriteLine(\"FAAAAAAAAAAAAAAAAAAAAAAIL!\");\n }\n\n switch (buffer) {\n case BufferType.Water:\n WaterVertices = new List&lt;VertexPositionTextureLight&gt;();\n WaterIndexList = new List&lt;short&gt;();\n OffsetWater = 0; // PascalCase\n break;\n case BufferType.Lava:\n // Nothing // Always explicitly declare when you are doing nothing on purpose. An explanation might be useful too.\n break;\n default:\n SolidVertices = new List&lt;VertexPositionTextureLight&gt;();\n SolidIndexList = new List&lt;short&gt;();\n OffsetSolid = 0; // PascalCase\n break;\n }\n\n int xOffset = Index.X // not \"index\" - class variables should use PascalCase\n // We can calculate these in advance, no need to repeat.\n * Variables.REGION_SIZE_X; // I would use Variables.Region.SIZE_X\n int yOffset = Index.Y * Variables.REGION_SIZE_Y; // I would use Variables.Region.SIZE_Y\n int zOffset = Index.Z * Variables.REGION_SIZE_Z; // I would use Variables.Region.SIZE_Z\n for (short x = 0; x &lt; Variables.REGION_SIZE_X; x++) {\n for (short y = 0; y &lt; Variables.REGION_SIZE_Y; y++) {\n for (short z = 0; z &lt; Variables.REGION_SIZE_Z; z++) {\n int newX = xOffset + x; // Local variables, camelCase; also, using x and X is asking for accidental bugs!\n int newY = yOffset + y;\n int newZ = zOffset + z;\n\n if (buffer == BufferType.Water &amp;&amp; World[newX, newY, newZ].BlockType == BlockType.WaterStill) {\n BuildCube(buffer, WaterVertices, WaterIndexList, newX, newY, newZ, ref OffsetWater);\n } else if (buffer == BufferType.Solid &amp;&amp; World[newX, newY, newZ].BlockType != BlockType.WaterStill) {\n BuildCube(buffer, SolidVertices, SolidIndexList, newX, newY, newZ, ref OffsetSolid);\n }\n }\n }\n }\n\n switch (buffer) {\n case BufferType.Water:\n if (WaterVertices.Count &gt; 0) {\n CopyToBuffers(ref WaterVertexBuffer, ref WaterIndices, WaterVertices, WaterIndexList);\n } else {\n WaterVertexBuffer = null;\n }\n break;\n case BufferType.Lava:\n // Nothing // Always explicitly declare when you are doing nothing on purpose. An explanation might be useful too.\n break;\n default:\n if (SolidVertices.Count &gt; 0) {\n CopyToBuffers(ref SolidVertexBuffer, ref SolidIndices, SolidVertices, SolidIndexList);\n } else {\n SolidVertexBuffer = null;\n }\n break;\n }\n }\n\n public void BuildCube(BufferType buffer, List&lt;VertexPositionTextureLight&gt; vertices, List&lt;short&gt; indices, int x, int y, int z, ref int offset) {\n Block target = World[x, y, z];\n if (target.BlockType == BlockType.None)\n return;\n\n bool above = !World[x, y + 1, z].IsTransparentSolid;\n bool below = !World[x, y - 1, z].IsTransparentSolid;\n bool left = !World[x - 1, y, z].IsTransparentSolid;\n bool right = !World[x + 1, y, z].IsTransparentSolid;\n bool front = !World[x, y, z + 1].IsTransparentSolid;\n bool back = !World[x, y, z - 1].IsTransparentSolid;\n\n bool notVisible = above &amp;&amp; below &amp;&amp; left &amp;&amp; right &amp;&amp; front &amp;&amp; back;\n\n if (notVisible)\n return;\n\n Vector3 vector = new Vector3(x, y, z);\n if (!back)\n BuildCubeFace(vertices, indices, target, vector, BlockFaceDirection.ZDecreasing, ref offset);\n if (!front)\n BuildCubeFace(vertices, indices, target, vector, BlockFaceDirection.ZIncreasing, ref offset);\n if (!above)\n BuildCubeFace(vertices, indices, target, vector, BlockFaceDirection.YIncreasing, ref offset);\n if (!below)\n BuildCubeFace(vertices, indices, target, vector, BlockFaceDirection.YDecreasing, ref offset);\n if (!right)\n BuildCubeFace(vertices, indices, target, vector, BlockFaceDirection.XIncreasing, ref offset);\n if (!left)\n BuildCubeFace(vertices, indices, target, vector, BlockFaceDirection.XDecreasing, ref offset);\n }\n\n public void BuildCubeFace(List&lt;VertexPositionTextureLight&gt; vertices, List&lt;short&gt; indices, Block block, Vector3 pos, BlockFaceDirection blockFaceDirection, ref int offset) {\n Vector3 topLeftFront = new Vector3(0f, 1f, 0f) + pos;\n Vector3 bottomLeftFront = new Vector3(0f, 0f, 0f) + pos;\n Vector3 topRightFront = new Vector3(1f, 1f, 0f) + pos;\n Vector3 bottomRightFront = new Vector3(1f, 0f, 0f) + pos;\n Vector3 topLeftBack = new Vector3(0f, 1f, -1f) + pos;\n Vector3 topRightBack = new Vector3(1f, 1f, -1f) + pos;\n Vector3 bottomLeftBack = new Vector3(0f, 0f, -1f) + pos;\n Vector3 bottomRightBack = new Vector3(1f, 0f, -1f) + pos;\n\n Vector3 upNormal = new Vector3(0, 1, 0);\n Vector3 downNormal = new Vector3(0, -1, 0);\n Vector3 leftNormal = new Vector3(-1, 0, 0);\n Vector3 rightNormal = new Vector3(1, 0, 0);\n Vector3 backNormal = new Vector3(0, 0, -1);\n Vector3 frontNormal = new Vector3(0, 0, 1);\n\n float unit = 1.0f / Variables.TILE_ALAIS.NumberOfColumns;\n\n float x = unit * block.BlockType.GetColumn();\n float y = unit * block.BlockType.GetRow();\n\n Vector2 topLeft = new Vector2(x, y);\n Vector2 topRight = new Vector2(x + unit, y);\n Vector2 bottomLeft = new Vector2(x, y + unit);\n Vector2 bottomRight = new Vector2(x + unit, y + unit);\n\n float light = Variables.Light; // 12\n\n switch (blockFaceDirection) {\n case BlockFaceDirection.ZIncreasing:\n light = world.GetLight((int)(frontNormal.X + pos.X), (int)(frontNormal.Y + pos.Y), (int)(frontNormal.Z + pos.Z));\n\n vertices.Add(new VertexPositionTextureLight(bottomLeftFront, frontNormal, bottomLeft, light));\n vertices.Add(new VertexPositionTextureLight(bottomRightFront, frontNormal, bottomRight, light));\n vertices.Add(new VertexPositionTextureLight(topLeftFront, frontNormal, topLeft, light));\n vertices.Add(new VertexPositionTextureLight(topRightFront, frontNormal, topRight, light));\n break;\n case BlockFaceDirection.ZDecreasing:\n light = world.GetLight((int)(backNormal.X + pos.X), (int)(backNormal.Y + pos.Y), (int)(backNormal.Z + pos.Z));\n\n vertices.Add(new VertexPositionTextureLight(bottomRightBack, backNormal, bottomLeft, light));\n vertices.Add(new VertexPositionTextureLight(bottomLeftBack, backNormal, bottomRight, light));\n vertices.Add(new VertexPositionTextureLight(topRightBack, backNormal, topLeft, light));\n vertices.Add(new VertexPositionTextureLight(topLeftBack, backNormal, topRight, light));\n break;\n case BlockFaceDirection.YIncreasing:\n light = world.GetLight((int)(upNormal.X + pos.X), (int)(upNormal.Y + pos.Y), (int)(upNormal.Z + pos.Z));\n\n vertices.Add(new VertexPositionTextureLight(topLeftFront, upNormal, bottomLeft, light));\n vertices.Add(new VertexPositionTextureLight(topRightFront, upNormal, bottomRight, light));\n vertices.Add(new VertexPositionTextureLight(topLeftBack, upNormal, topLeft, light));\n vertices.Add(new VertexPositionTextureLight(topRightBack, upNormal, topRight, light));\n break;\n case BlockFaceDirection.YDecreasing:\n light = world.GetLight((int)(downNormal.X + pos.X), (int)(downNormal.Y + pos.Y), (int)(downNormal.Z + pos.Z));\n\n vertices.Add(new VertexPositionTextureLight(bottomLeftBack, downNormal, bottomLeft, light));\n vertices.Add(new VertexPositionTextureLight(bottomRightBack, downNormal, bottomRight, light));\n vertices.Add(new VertexPositionTextureLight(bottomLeftFront, downNormal, topLeft, light));\n vertices.Add(new VertexPositionTextureLight(bottomRightFront, downNormal, topRight, light));\n break;\n case BlockFaceDirection.XIncreasing:\n light = world.GetLight((int)(rightNormal.X + pos.X), (int)(rightNormal.Y + pos.Y), (int)(rightNormal.Z + pos.Z));\n\n vertices.Add(new VertexPositionTextureLight(bottomRightFront, rightNormal, bottomLeft, light));\n vertices.Add(new VertexPositionTextureLight(bottomRightBack, rightNormal, bottomRight, light));\n vertices.Add(new VertexPositionTextureLight(topRightFront, rightNormal, topLeft, light));\n vertices.Add(new VertexPositionTextureLight(topRightBack, rightNormal, topRight, light));\n break;\n case BlockFaceDirection.XDecreasing:\n light = world.GetLight((int)(leftNormal.X + pos.X), (int)(leftNormal.Y + pos.Y), (int)(leftNormal.Z + pos.Z));\n\n vertices.Add(new VertexPositionTextureLight(bottomLeftBack, leftNormal, bottomLeft, light));\n vertices.Add(new VertexPositionTextureLight(bottomLeftFront, leftNormal, bottomRight, light));\n vertices.Add(new VertexPositionTextureLight(topLeftBack, leftNormal, topLeft, light));\n vertices.Add(new VertexPositionTextureLight(topLeftFront, leftNormal, topRight, light));\n break;\n }\n AddIndices(indices, 0, 2, 3, 3, 1, 0, ref offset);\n }\n\n public void AddIndices(List&lt;short&gt; IndexList, short i0, short i1, short i2, short i3, short i4, short i5, ref int offset) {\n // ...\n }\n\n private void CopyToBuffers(ref VertexBuffer vertexBuffer, ref IndexBuffer indexBuffer, List&lt;VertexPositionTextureLight&gt; vertices, List&lt;short&gt; indices) {\n //...\n }\n\n public void QueueForBuild(BufferType buffer) {\n // ...\n }\n\n public void QueueForBuild(Block block) {\n // ...\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T11:30:55.863", "Id": "8495", "ParentId": "8436", "Score": "1" } } ]
{ "AcceptedAnswerId": "8495", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T23:13:08.167", "Id": "8436", "Score": "0", "Tags": [ "c#" ], "Title": "Water flow problems in Minecraft-like terrain engine" }
8436
<p>We have a setup script for setting up a development environment, and setting up the image libraries is getting a bit messy:</p> <pre><code># this is to get PNG and JPEG support working in PIL on Ubuntu if [ -d /usr/lib/x86_64-linux-gnu ] ; then # 64 bit ubuntu sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib/ sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib/ sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib/ fi if [ -d /usr/lib/i386-linux-gnu/ ] ; then # 32 bit ubuntu sudo ln -s /usr/lib/i386-linux-gnu/libfreetype.so /usr/lib/ sudo ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib/ sudo ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib/ fi if [ -d /usr/lib64/ ] ; then # Redhat sudo ln -s /usr/lib64/libjpeg.so /usr/lib/ sudo ln -s /usr/lib64/libz.so /usr/lib/ sudo ln -s /usr/lib64/libfreetype.so /usr/lib/ fi </code></pre>
[]
[ { "body": "<p>Seems like you can do the if statement to set a variable to the first part of the path, then put all the file copies at the end after that.</p>\n\n<p>(Warning: My bash is kind of bad. Haven't used it for a while. I think this is how it's done though... Might need quotes around the libpath assignments?)</p>\n\n<pre><code># this is to get PNG and JPEG support working in PIL on Ubuntu\nif [ -d /usr/lib/x86_64-linux-gnu ] ; then # 64 bit ubuntu\n libpath=/usr/lib/x86_64-linux-gnu\nfi\n\nif [ -d /usr/lib/i386-linux-gnu/ ] ; then # 32 bit ubuntu\n libpath=/usr/lib/i386-linux-gnu\nfi\n\nif [ -d /usr/lib64/ ] ; then # Redhat\n libpath=/usr/lib64\nfi\n\nsudo ln -s $libpath/libfreetype.so /usr/lib/\nsudo ln -s $libpath/libz.so /usr/lib/\nsudo ln -s $libpath/libjpeg.so /usr/lib/\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T08:15:08.500", "Id": "13214", "Score": "4", "body": "This looks good, you can use `elif` for the last two if statements as only 1 option should be chosen." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T05:16:54.767", "Id": "8442", "ParentId": "8441", "Score": "3" } }, { "body": "<p>In the interests of dryness, and invoking as small number of commands as possible.</p>\n\n<pre><code>for dir in /usr/lib{/x86_64-linux-gnu,/i386-linux-gnu,64}; do\n [ -d $dir ] &amp;&amp; echo $dir\ndone | {read dir;\nfor lib in {libfreetype,libz,libjpeg}.so; do\n echo ln -s $dir/$lib /usr/lib/\ndone} | sudo bash\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-22T04:48:34.503", "Id": "11071", "ParentId": "8441", "Score": "0" } }, { "body": "<p>I'm not quite sure if your script should consist of <code>elifs</code> instead of <code>ifs</code>. I'm going to assume that it should be <code>elifs</code> since you don't want to be overwriting your links. If not just remove <code>break</code> or reverse the order of the directories.</p>\n\n<pre><code>for dir in /usr/lib{/x86_64-linux-gnu,/i386-linux-gnu,64}; do\n if [[ -d $dir ]]; then\n sudo ln -s $dir/{libfreetype,libz,libjpeg}.so /usr/lib\n break\n fi\ndone\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-11T17:35:22.383", "Id": "113632", "ParentId": "8441", "Score": "3" } } ]
{ "AcceptedAnswerId": "113632", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T04:38:18.917", "Id": "8441", "Score": "6", "Tags": [ "file-system", "bash", "installer" ], "Title": "Symlinking shared libraries from a platform-specific directory" }
8441
<p>I'd like to check the following process relating to the uploading of data by FTP, after the data is read from a database. </p> <p>I have a stored procedure that returns data in the following pipe delimited format in a single column. It typically returns around 300 rows, each row has about 300 bytes. </p> <pre><code>1234|||||PROPERTY|||MARKET INDEX|||||ADDRESS|||||1||||GBP|||||||20110930||||||||C|OFFICE|F|| </code></pre> <p>The application then submits that data by FTP, typically &lt;100k overall.</p> <p>Here's the mechanism used, restricted to .NET 3.5. </p> <pre><code>// database method returns dataset/datareader, converted and passed to method as // IEnumerable&lt;string&gt; data string ftpServerIP = "5.4.3.2:21"; string targetFileName = "mann.txt"; string username = "manfred"; string password = "*******"; Uri uri = new Uri(String.Format("ftp://{0}/{1}", ftpServerIP, targetFileName)); FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri); reqFTP.Credentials = new NetworkCredential(username, password); reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.KeepAlive = false; reqFTP.UsePassive = false; MemoryStream stIn = new MemoryStream(); using (StreamWriter sw = new StreamWriter(stIn)) { foreach (string item in data) { sw.WriteLine(item); } sw.Flush(); using (Stream stOut = reqFTP.GetRequestStream()) { stOut.Write(stIn.GetBuffer(), 0, (int)stIn.Length); } } FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); response.Close(); </code></pre> <p>I'd like to check whether the stream and ftp processing looks ok, or whether there are other stream types to consider (<code>BufferedStream</code>?), or closure/disposal steps, etc...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T16:24:05.570", "Id": "13868", "Score": "0", "body": "Looks like you are not dealing with a lot of data, so speed is not a huge concern, thus you could separate code (FTP from DB) a bit. I personally would have a method that returns a LinkedList<string> or IEnumerable<string> of stuff that comes from the database. Then I would pass that object to the method with the FTP logic. If your code in this project will never be larger than two pages, then this probably does not matter. My other small pieves are: I would skip a line after `}` (as StyleCop would suggest). I would also build out a URI with `String.Format`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-29T16:37:56.660", "Id": "51079", "Score": "0", "body": "@Leonid, apologies for the extremely tardy reply. If you haven't since retired ... and want to add these notes as an answer, I'll add my vote. Question updated with your suggestions meanwhile (though I need to check the [StyleCop](http://www.stylecop.com/docs/SA1513.html) implementation that you mentioned)." } ]
[ { "body": "<p>In general it looks fine to me. <code>BufferedStream</code> would not help anything here, your data is already in memory by the time any streams get created.</p>\n\n<p>I would prefer to see the <code>MemoryStream</code> in a using block, although in this case it is being disposed when the <code>StreamWriter</code> is disposed.</p>\n\n<p>It may be a good idea to check the response and handle any error status. If you do ever add any code that uses the <code>FtpWebResponse</code>, I would change to a using block, instead of the call to close. </p>\n\n<p>Not really related to the code, but avoid using FTP if you can.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-09T14:21:09.197", "Id": "245324", "Score": "0", "body": "Can you elaborate on why to avoid FTP, and what alternatives you'd suggest?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T02:17:36.890", "Id": "8843", "ParentId": "8450", "Score": "2" } } ]
{ "AcceptedAnswerId": "8843", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T12:28:29.073", "Id": "8450", "Score": "3", "Tags": [ "c#", ".net" ], "Title": "Data to FTP upload by stream copy" }
8450
<p>I'm trying to symmetrically encrypt some data using C#, and there seems to be a lot of misleading or incorrect information out there on the subject.</p> <p>I created a project on GitHub to act as some sort of standard for encrypting and decrypting data in C#: <strong><a href="https://github.com/jbubriski/Encryptamajig" rel="nofollow">Encryptamajig on Github</a></strong></p> <p>It would be great if you guys could review the code below for any security holes, but also, please check out the verbiage in the README on Github. I tried to do some research and be as accurate as possible, but I'm sure that there are some things I'm missing.</p> <p>If you do find anything, don't hesitate to send me a pull request.</p> <pre><code>namespace Encryptamajig { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.Diagnostics; using System.IO; /// &lt;summary&gt; /// A simple wrapper to the AesManaged class and the AES algorithm. /// To create a new Key and IV simple "new up" an AesManaged object and grab the Key and IV from that. /// Make sure to save the Key and IV if you want to decrypt your data later! /// &lt;/summary&gt; public class AesEncryptamajig { public static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv) { // Check arguments. if (string.IsNullOrEmpty(plainText)) throw new ArgumentNullException("plainText"); if (key == null || key.Length &lt;= 0) throw new ArgumentNullException("key"); if (iv == null || iv.Length &lt;= 0) throw new ArgumentNullException("iv"); MemoryStream memoryStream = null; AesManaged aesAlg = null; try { // Create the encryption algorithm object with the specified key and IV. aesAlg = new AesManaged(); aesAlg.Key = key; aesAlg.IV = iv; // Create an encryptor to perform the stream transform. var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. memoryStream = new MemoryStream(); using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) using (var streamWriter = new StreamWriter(cryptoStream)) { //Write all data to the stream. streamWriter.Write(plainText); } } finally { if (aesAlg != null) aesAlg.Clear(); } // Return the encrypted bytes from the memory stream. return memoryStream.ToArray(); } public static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv) { // Check arguments. if (cipherText == null || cipherText.Length &lt;= 0) throw new ArgumentNullException("cipherText"); if (key == null || key.Length &lt;= 0) throw new ArgumentNullException("key"); if (iv == null || iv.Length &lt;= 0) throw new ArgumentNullException("iv"); AesManaged aesAlg = null; string plaintext = null; try { // Create a the encryption algorithm object with the specified key and IV. aesAlg = new AesManaged(); aesAlg.Key = key; aesAlg.IV = iv; // Create a decrytor to perform the stream transform. var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption. using (var memoryStream = new MemoryStream(cipherText)) using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) using (var streamReader = new StreamReader(cryptoStream)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = streamReader.ReadToEnd(); } } finally { if (aesAlg != null) aesAlg.Clear(); } return plaintext; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T15:30:50.633", "Id": "13224", "Score": "0", "body": "Why the `using` **inside** the namespace? Is that just style, or something else?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T16:30:32.610", "Id": "13226", "Score": "1", "body": "There is a subtle difference outlined in [this StackOverflow question](http://stackoverflow.com/questions/125319/should-usings-be-inside-or-outside-the-namespace)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T01:49:43.363", "Id": "28336", "Score": "1", "body": "@ANeves It's a Resharper thing. Helps with scoping." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T03:31:45.757", "Id": "28380", "Score": "0", "body": "I'm getting an invalid padding exception when trying to decrypt." } ]
[ { "body": "<p>A not encryption related note: I'd change the following</p>\n\n<pre><code>AesManaged aesAlg = null;\ntry {\n aesAlg = new AesManaged();\n ...\n} finally {\n if (aesAlg != null)\n aesAlg.Clear();\n}\n</code></pre>\n\n<p>to a simpler one:</p>\n\n<pre><code>AesManaged aesAlg = new AesManaged();\ntry {\n ...\n} finally {\n aesAlg.Clear();\n}\n</code></pre>\n\n<p>If the constructor of <code>AesManaged</code> throws an exception the reference remains <code>null</code>, so <code>Clear</code> won't be called.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T22:47:25.390", "Id": "8523", "ParentId": "8452", "Score": "2" } }, { "body": "<p>I wouldn't have the IV passed in either routine. There is two much potential for it to be used incorrectly. I've seen lots of examples out there which will either reuse the IV all the time or just use the same IV per Key. If your IV is predictable there are possible exploits for an adversary to get your plain text, such as a <a href=\"http://en.wikipedia.org/wiki/Padding_oracle_attack\">padding oracle</a> since your above uses CBC.</p>\n\n<p>The best practice would be to use <code>aesAlg.GenerateIV()</code> and then prepend the iv to the cipher text. When you decrypt you just read that block out first before you decrypt the rest.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:06:54.017", "Id": "14893", "ParentId": "8452", "Score": "6" } }, { "body": "<p>You need to <code>Dispose()</code> of your disposable objects (those which implement <code>IDisposable</code>: <code>MemoryStream</code> in <code>EncryptStringToBytes</code> and <code>AesManaged</code> and the <code>encryptor</code> in both methods. They can be simplified as such:</p>\n\n<pre><code>namespace Encryptamajig\n{\n using System;\n using System.IO;\n using System.Security.Cryptography;\n\n /// &lt;summary&gt;\n /// A simple wrapper to the AesManaged class and the AES algorithm.\n /// To create a new Key and IV simple \"new up\" an AesManaged object and grab the Key and IV from that.\n /// Make sure to save the Key and IV if you want to decrypt your data later!\n /// &lt;/summary&gt;\n public static class AesEncryptamajig\n {\n public static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)\n {\n // Check arguments.\n if (string.IsNullOrEmpty(plainText))\n throw new ArgumentNullException(\"plainText\");\n if (key == null || key.Length &lt;= 0)\n throw new ArgumentNullException(\"key\");\n if (iv == null || iv.Length &lt;= 0)\n throw new ArgumentNullException(\"iv\");\n\n // Create the encryption algorithm object with the specified key and IV.\n using (var aesAlg = new AesManaged { Key = key, IV = iv })\n // Create an encryptor to perform the stream transform.\n using (var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV))\n // Create the streams used for encryption.\n using (var memoryStream = new MemoryStream())\n using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))\n using (var streamWriter = new StreamWriter(cryptoStream))\n {\n // Write all data to the stream.\n streamWriter.Write(plainText);\n\n // Return the encrypted bytes from the memory stream.\n return memoryStream.ToArray();\n }\n }\n\n public static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)\n {\n // Check arguments.\n if (cipherText == null || cipherText.Length &lt;= 0)\n throw new ArgumentNullException(\"cipherText\");\n if (key == null || key.Length &lt;= 0)\n throw new ArgumentNullException(\"key\");\n if (iv == null || iv.Length &lt;= 0)\n throw new ArgumentNullException(\"iv\");\n\n // Create a the encryption algorithm object with the specified key and IV.\n using (var aesAlg = new AesManaged { Key = key, IV = iv })\n // Create a decryptor to perform the stream transform.\n using (var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV))\n // Create the streams used for decryption.\n using (var memoryStream = new MemoryStream(cipherText))\n using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))\n using (var streamReader = new StreamReader(cryptoStream))\n {\n // Read the decrypted bytes from the decrypting stream\n // and place them in a string.\n return streamReader.ReadToEnd();\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:51:35.010", "Id": "24269", "Score": "1", "body": "Good point, it looks like I did end up doing that in the code: https://github.com/jbubriski/Encryptamajig/blob/master/src/Encryptamajig/Encryptamajig/AesEncryptamajig.cs" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:22:25.007", "Id": "14894", "ParentId": "8452", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T14:15:33.277", "Id": "8452", "Score": "11", "Tags": [ "c#", "security", "aes" ], "Title": "Symmetrical encryption in C#" }
8452
<p>I'd like to make this SQL scalar function more efficient. How can I do that?</p> <pre><code>CREATE FUNCTION [dbo].[fnFilterBySampleType] ( @context VARCHAR(10), @contextId INT, @sampleTypeId INT ) RETURNS BIT AS BEGIN IF ( @context = 'batch' AND @sampleTypeId = 247 AND EXISTS( SELECT * FROM batch WHERE batchid = @contextId AND (batch.sampletypeid = @sampleTypeId OR batch.sampletypeid IS NULL) ) ) RETURN 1 IF ( @context = 'batch' AND @sampleTypeId = 3301 AND EXISTS( SELECT * FROM batch WHERE batchid = @contextId AND batch.sampletypeid = @sampleTypeId ) ) RETURN 1 IF ( @context = 'batch' AND @sampleTypeId IS NULL AND EXISTS( SELECT * FROM batch WHERE batchid = @contextId AND batch.sampletypeid IS NULL ) ) RETURN 1 IF ( @context = 'sample' AND @sampleTypeId = 247 AND EXISTS( SELECT * FROM sample WHERE sampleid = @contextId AND ([sample].sampletypeid = @sampleTypeId OR [sample].sampletypeid IS NULL) ) ) RETURN 1 IF ( @context = 'sample' AND @sampleTypeId = 3301 AND EXISTS( SELECT * FROM sample WHERE sampleid = @contextId AND sample.sampletypeid = @sampleTypeId ) ) RETURN 1 IF ( @context = 'sample' AND @sampleTypeId IS NULL AND EXISTS( SELECT * FROM sample WHERE sampleid = @contextId AND [sample].sampletypeid IS NULL ) ) RETURN 1 RETURN 0 END </code></pre>
[]
[ { "body": "<p>I am rewriting my answer to be more clear... </p>\n\n<p>the way you have it written the exists clause will be executed many times...</p>\n\n<p>You should move the exists clauses inside the if block so that in the cases that the other parts don't match it will be forced to short circuit. You can't depend on SQL server tsql statements to short circuit in the manner you expect.</p>\n\n<p>So this will not execute the inner \"IF exists\" if the @context isn't 'batch' etc...</p>\n\n<p>The way you have it written it may or may not execute the exists query.</p>\n\n<pre><code>IF (@context = 'batch' AND @sampleTypeId = 247)\nbegin\n\n if EXISTS(\n SELECT * \n FROM batch \n WHERE batchid = @contextId \n AND (batch.sampletypeid = @sampleTypeId OR batch.sampletypeid IS NULL)\n ) RETURN 1 ELSE RETURN 0\n\nend\n</code></pre>\n\n<p>for more reading on this subject check out this articles.</p>\n\n<p><a href=\"http://beingmarkcohen.com/?p=62\" rel=\"nofollow\">http://beingmarkcohen.com/?p=62</a></p>\n\n<p><a href=\"http://www.sqlmag.com/article/tsql3/short-circuit\" rel=\"nofollow\">http://www.sqlmag.com/article/tsql3/short-circuit</a></p>\n\n<p><a href=\"http://blogs.msdn.com/b/bartd/archive/2011/03/03/don-t-depend-on-expression-short-circuiting-in-t-sql-not-even-with-case.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/bartd/archive/2011/03/03/don-t-depend-on-expression-short-circuiting-in-t-sql-not-even-with-case.aspx</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T04:12:34.133", "Id": "13220", "Score": "0", "body": "sorry, I accidentally gave you an upvote. This is not correct though. Adding more tags so others will see it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T15:00:25.763", "Id": "13221", "Score": "0", "body": "where did the 3301 and NULL checks go?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T15:23:55.477", "Id": "13223", "Score": "0", "body": "I didn't rewrite them all just the first one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T22:50:20.287", "Id": "13265", "Score": "0", "body": "oh ok. is there a way I can combine more than 1 of them above to a single query?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T12:50:58.553", "Id": "13289", "Score": "0", "body": "there might be but I think doing so would make the code more confusing." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-11T16:59:26.923", "Id": "8454", "ParentId": "8453", "Score": "3" } } ]
{ "AcceptedAnswerId": "8454", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-11T16:51:25.553", "Id": "8453", "Score": "2", "Tags": [ "optimization", "sql" ], "Title": "How can I make this SQL Bit scalar function more efficient?" }
8453
<p>I wrote <a href="https://github.com/becomingGuru/python-restconsumer" rel="nofollow">this</a>, which essentially acts as a single library for all possible REST services.</p> <p>Here is the main file, as of alpha version 1:</p> <pre><code>import requests, json class RestConsumer(object): def __init__(self,base_url,append_json=False,**kwargs): self.base_url = base_url self.uriparts = [] self.append_json = append_json self.kwargs = kwargs def __getattr__(self,k): if k=='spc': return self.spc if not k[0] == '_': self.uriparts.append(k) else: if k[1:3]=='in': self.uriparts.append(k[3:]) elif k[1:3] == 'uh': self.uriparts.append(k.replace('_','-')) return self def spc(self,k): self.uriparts.append(k) return self def __call__(self, **kwargs): uri_constructed = '/'.join(self.uriparts) self.uriparts = [] self.uri_constructed = "%s%s"%(uri_constructed,'.json') if self.append_json else uri_constructed self.url = '/'.join([self.base_url,self.uri_constructed]) return self.get(self.url,**kwargs) def get(self,url,**kwargs): print url r = requests.get(url,**kwargs) return json.loads(r.content) def post(self,**kwargs): r = requests.post(**kwargs) return json.loads(r.content) if __name__=='__main__': from pprint import pprint t = RestConsumer(base_url='https://api.twitter.com/1',append_json=True) public_timeline = t.statuses.public_timeline() pprint(public_timeline) g = RestConsumer(base_url='https://api.github.com') repos = g.users.kennethreitz.repos() pprint(repos) s = RestConsumer(base_url='http://api.stackoverflow.com/1.1') sr = s.users.spc('55562').questions.unanswered() pprint(sr) sr2 = s.tags.python.spc('top-answerers').spc('all-time')() pprint(sr2) </code></pre> <p>The rationale and usage is all explained in the <a href="https://github.com/becomingGuru/python-restconsumer/blob/master/README.rst" rel="nofollow">README</a>.</p> <p>Please critique the library, the idea, implementation and shed light on alternatives.</p>
[]
[ { "body": "<pre><code>import requests, json\n\nclass RestConsumer(object):\n\n def __init__(self,base_url,append_json=False,**kwargs):\n self.base_url = base_url\n self.uriparts = []\n self.append_json = append_json\n self.kwargs = kwargs\n</code></pre>\n\n<p>Since you treat attributes \"special\", I recommend putting _ in front of these attributes so that are clearly offset.</p>\n\n<pre><code> def __getattr__(self,k):\n</code></pre>\n\n<p>I recommend not using the random letter <code>k</code> for the name.</p>\n\n<pre><code> if k=='spc':\n return self.spc\n</code></pre>\n\n<p><code>__getattr__</code> only gets invoked if the attribute cannot be found. Since <code>spc</code> will be found this won't ever get used.</p>\n\n<pre><code> if not k[0] == '_':\n self.uriparts.append(k)\n else:\n if k[1:3]=='in':\n self.uriparts.append(k[3:])\n</code></pre>\n\n<p>What's the point of this rule? <code>_infoo</code> means <code>foo</code>? </p>\n\n<pre><code> elif k[1:3] == 'uh':\n self.uriparts.append(k.replace('_','-'))\n</code></pre>\n\n<p><code>uh</code>?</p>\n\n<pre><code> return self\n</code></pre>\n\n<p>I don't like the way you've implemented this. Accessing attributes modifying the object's state is deeply counter-intuitive.</p>\n\n<pre><code> def spc(self,k):\n self.uriparts.append(k)\n return self\n</code></pre>\n\n<p><code>spc</code> is not a clear name. Its hard to guess what it means. </p>\n\n<pre><code> def __call__(self, **kwargs):\n uri_constructed = '/'.join(self.uriparts)\n self.uriparts = []\n self.uri_constructed = \"%s%s\"%(uri_constructed,'.json') if self.append_json else uri_constructed\n self.url = '/'.join([self.base_url,self.uri_constructed])\n return self.get(self.url,**kwargs)\n\n def get(self,url,**kwargs):\n print url\n r = requests.get(url,**kwargs)\n return json.loads(r.content)\n\n def post(self,**kwargs):\n r = requests.post(**kwargs)\n return json.loads(r.content)\n</code></pre>\n\n<p><code>get</code> prints while <code>post</code> doesn't. Probably neither should be printing, a log facility might be useful.</p>\n\n<p>The way you've designed this, some useful things won't work:</p>\n\n<pre><code>public_timeline = twitter.statuses.public_timeline\nwhile True:\n print public_timeline()\n</code></pre>\n\n<p>or</p>\n\n<pre><code>user = s.users.spc(55562)\nprint user.questions.unanswered()\nprint user.questions.answered()\n</code></pre>\n\n<p>I suggest that instead of modifying the object, you return new objects. That way it will work in an intuitive manner. </p>\n\n<p>Instead of <code>spc</code> I suggest that you provide a <code>__getitem__</code>. That way you can do:</p>\n\n<pre><code> s.users[55562].questions.unanswered()\n</code></pre>\n\n<p>Which I think will make it cleaner. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T06:47:35.933", "Id": "13278", "Score": "0", "body": "All excellent feedback. Thank you. I am modifying it now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T08:37:45.810", "Id": "13281", "Score": "0", "body": "I changed it from mutating self to returning new objects. But can't figure out how to enable the last useful things you talk about. http://stackoverflow.com/questions/9076403/python-how-to-enable-the-following-api-using-class-magic" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T18:47:17.513", "Id": "8462", "ParentId": "8455", "Score": "4" } }, { "body": "<p>you should include a docstring on what the program is (steal from readme \"RestConsumer is a generic python wrapper for consuming JSON REST APIs\" although maybe add alittle more on use).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T13:07:57.080", "Id": "15830", "ParentId": "8455", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T14:58:53.893", "Id": "8455", "Score": "5", "Tags": [ "python", "rest" ], "Title": "A generic REST API consuming Python library" }
8455
<p>I'm doing a site at the moment (first Rails site, learning as I code) and I'm concerned that I'm over complicating the routes.</p> <p>My associations boil down to:</p> <pre><code>class Recipe &lt; ActiveRecord::Base has_and_belongs_to_many :categories belongs_to :book end class Category &lt; ActiveRecord::Base belongs_to :category_type has_and_belongs_to_many :recipes end class Book &lt; ActiveRecord::Base has_many :recipes end </code></pre> <p>I want to end up with URLs like this:</p> <pre><code>/books/3/recipes #to show all recipes from book 3 /category/12/recipes #to show all categories from category 12 /recipes/3 #to show recipe 3 </code></pre> <p>The good news is I have this all working, but in the course of doing so I feel like I may have strayed a little from "the Rails way" and I was wondering if someone could take a look and let me know if I've gone wrong. The bits I'm particularly concerned about are my routes.rb file (because I appear to be repeating myself):</p> <pre><code>resources :books do resources :recipes end resources :categories do resources :recipes end </code></pre> <p>In particular, the <code>recipes#index</code> action, which seems a little verbose:</p> <pre><code>def index if(params[:category_id]) @recipes = Recipe.find_by_category(params[:category_id]) elsif(params[:book_id]) @recipes = Recipe.where(:book_id =&gt; params[:book_id]) else @recipes = Recipe.find(:all) end end </code></pre> <p>Now, it might be that this is all absolutely fine, but I just want to check before I get too much further in!</p>
[]
[ { "body": "<p>This is probably fine, though there are other ways to do it like passing filters to /recipes (?category_id=x or ?book_id=x). Your controller action is probably fine too, though I may have considered making multiple controllers. </p>\n\n<p>Though i'm not sure why you're doing <code>find_by_category</code> instead of the a <code>find_all_by_category</code> or the same .where as you're doing for book_id. Also, <code>Recipe.all</code> is more rails 3.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T17:32:25.727", "Id": "13372", "Score": "0", "body": "Thank you, I eventually ended up refactoring all of this. I realized that I was trying to organize my routes around URLs which \"sounded nice\" without realizing that I was sacrificing quite a lot of nice-ness in the process (essentially by becoming obsessed with the \"/recipes\" bit at the end of the URL). You've given me something to check out though!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T05:59:11.510", "Id": "8530", "ParentId": "8461", "Score": "2" } } ]
{ "AcceptedAnswerId": "8530", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T18:46:46.253", "Id": "8461", "Score": "2", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Route structure for multiple associations in Rails" }
8461
<p>This code is for handling addition of two binary numbers, which can be as long as 100,000 bits... and up to 500,000 queries are performed.</p> <p>High-level pseudocode:</p> <ol> <li>First input <code>N</code>: number of bits in binary number <code>A</code> and <code>B</code>.</li> <li>Second input <code>Q</code>: number of queries to be performed.</li> <li>Next <code>N</code> inputs: 0/1s ... bits for <code>A</code></li> <li>Next <code>N</code> inputs: 0/1s ... bits for <code>B</code></li> <li><p>Next <code>Q</code> inputs are one of the following:</p> <ol> <li><code>set_a INDEX VALUE</code>: as a result I set <code>a[INDEX] = VALUE</code></li> <li><code>set_b INDEX VALUE</code>: as a result I set <code>b[INDEX] = VALUE</code></li> <li><code>get_c INDEX</code>: as a result I print <code>c[INDEX]</code> where <code>C = A+B</code> (binary addition, like <code>100 + 101 = 1001</code>)</li> </ol></li> </ol> <p></p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;set&gt; #include &lt;algorithm&gt; #include &lt;utility&gt; // For pair #include &lt;iterator&gt; // For iterator, bidirectional_iterator_tag, reverse_iterator #include &lt;climits&gt; // For CHAR_BIT, ULONG_MAX using namespace std; class VanEmdeBoasTree {}; int main(int argc, char * argv[]) { int n, q; char c; bool a[100005] = {0}, b[100005] = {0}; VanEmdeBoasTree equals; cin&gt;&gt;n; cin&gt;&gt;q; for(int i=0;i&lt;n;i++){ cin&gt;&gt;c; if(c=='1') a[n-i-1] = true; } for(int i=0;i&lt;n;i++){ cin&gt;&gt;c; if(c=='1') b[n-i-1] = true; if(a[n-i-1] == b[n-i-1]){ equals.insert(n-i-1); } } string query; int index, val, lastval; for(int i=0;i&lt;q;i++){ cin&gt;&gt;query; cin&gt;&gt;index; if(query[4] == 'a'){ cin&gt;&gt;val; if(a[index] != val){ a[index] = val; if(a[index] == b[index]){ equals.insert(index); }else{ equals.erase(index); } } }else if(query[4] == 'b'){ cin&gt;&gt;val; if(b[index] != val){ b[index] = val; if(a[index] == b[index]){ equals.insert(index); }else{ equals.erase(index); } } }else if(query[4] == 'c'){ int final = 0; if(index == n){ if(equals.size() &gt; 0){ VanEmdeBoasTree::const_iterator it = equals.predecessor(index+1); if(it!=equals.end() &amp;&amp; a[*it] == 1){ final = 1; } } }else{ final = (a[index] + b[index])%2; if(equals.size() &gt; 0){ VanEmdeBoasTree::const_iterator it = equals.predecessor(index); int last = -1; if(it != equals.end()) last = *it; if( last!=-1 &amp;&amp; index!=0 &amp;&amp; it!=equals.end() &amp;&amp; a[last] == 1){ final = 1-final; } } } cout&lt;&lt;final; } } return 0; } </code></pre> <p>My solution is not fast enough as the Judge says "time out" after some test cases.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:21:38.217", "Id": "13241", "Score": "4", "body": "Can you link the online judge for this problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:28:14.440", "Id": "13242", "Score": "0", "body": "@WinstonEwert its the same one posted in one of the issues raised in meta.codereview.stackexchange.com by you. :-/" } ]
[ { "body": "<p>Profile and you will find your bottlenecks, you can do that with gprof under gcc/g++. You have to set the <code>-g -pg</code> on compile and then run your program like you would do normally. It will then produce a gmon.out file which you can open with <code>gprof main gmon.out</code> (assuming main is the name of your executable).</p>\n\n<p>It will show you, in which functions your program spends most of the time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:20:12.810", "Id": "13240", "Score": "0", "body": "The code in is C++ and gcc wont compile it, i tired what you said with g++ but no gmon.out was created." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:28:50.720", "Id": "13243", "Score": "0", "body": "@Pheonix Oh, I forgot, you have to add `-g`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T23:34:58.343", "Id": "13267", "Score": "0", "body": "@Pheonix: The gmon.out is generated after you run the program." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:05:32.093", "Id": "8464", "ParentId": "8463", "Score": "1" } }, { "body": "<p>I've just solved this problem (using a different technique then you)</p>\n\n<p>Things I learned that you might find useful:</p>\n\n<ol>\n<li>There is a lot of input for the test cases. I found that I was spending the bulk of my time just reading in the input. However, this didn't didn't show up in the output of gprof</li>\n<li>I had to construct test cases with pathalogical natures to find the performance issues with my solution. </li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T18:24:58.590", "Id": "13376", "Score": "0", "body": "congratulations... but on the other hand, i am struggling a lot, i changed quiet a few things, not using stl::map anymore, my own testcases are coming fine, tested with hundreds of them now, but wrong answer after #5... and its been 2 days with that :( am out of test cases" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T18:32:52.310", "Id": "13380", "Score": "0", "body": "@Pheonix, if you share the latest version of the code, I'll see if I can pinpoint where yours fails" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T19:02:34.483", "Id": "13382", "Score": "0", "body": "i updated my code in the question, removed the implementation of VanEmdeBoasTree from code, http://www.keithschwarz.com/interesting/code/?dir=van-emde-boas-tree .. i dont get timeout (thanks to van-emde-boas), but wrong answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T19:04:26.803", "Id": "13383", "Score": "0", "body": "additionally, there is one more implementation with some changes, which i made to make testing easier, it sets random bits and A/B and prints all A, B, C... so i see if result is matching or not, if u wish i will post that code too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T19:36:11.800", "Id": "13384", "Score": "0", "body": "@Pheonix, your code doesn't print a newline after all the bits. Other then that, I haven't found a case where my version differs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T19:46:41.787", "Id": "13385", "Score": "0", "body": "They want it all in a single line, isn't it ? did i miss something ? i am feeling stupid, `Output must be placed in a single line.` that's what i still see there, :( i am really confused now !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T00:13:42.467", "Id": "13392", "Score": "0", "body": "@Pheonix, you need a newline after all the bits, i.e. one at the very end of your program." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T16:08:10.807", "Id": "8561", "ParentId": "8463", "Score": "0" } } ]
{ "AcceptedAnswerId": "8464", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T18:51:52.657", "Id": "8463", "Score": "5", "Tags": [ "c++", "time-limit-exceeded" ], "Title": "Handling addition of two binary numbers" }
8463
<p>I'm new to Java. I'm trying to build a simple hierarchy of classes. </p> <pre><code>abstract class Vegetable { public Vegetable(double weight) { this.weight = weight; ... } ... } class Tomato extends Vegetable { public Tomato(double weight) { super(weight); ... } ... } class Cucumber extends Vegetable { public Cucumber(double weight) { super(weight); ... } ... } </code></pre> <p>I have some abstract methods in class <code>Vegetable</code>, which are overridden in <code>Tomato</code> and <code>Cucumber</code>. I want to implement logic of buying vegetables. I've created the following class for it: </p> <pre><code>public class VegetableFactory { public static ArrayList&lt;Vegetable&gt; buy(int num, Class vegetableClass) { ArrayList&lt;Vegetable&gt; res = new ArrayList&lt;Vegetable&gt;(num); for (int i = 0; i &lt; num; i++) { double weight = (Math.random() * 200) + 100; Vegetable v = null; try { v = (Vegetable) vegetableClass.getDeclaredConstructor(Double.TYPE).newInstance(weight); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } res.add(v); } return res; } } </code></pre> <p>Is it a good way of doing that? And is it ideologically correct to name it factory? Any suggestions of improvement are highly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T09:21:21.517", "Id": "64508", "Score": "0", "body": "I would use dictionary instead of switch look at this question my answer\n[Factory design pattern](http://codereview.stackexchange.com/questions/5752/is-this-correct-factory-method-pattern/5755#comment8705_5755)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-19T18:27:16.257", "Id": "66415", "Score": "0", "body": "I take exception to both tomatoes and cucumbers being classified as vegetables ;-)" } ]
[ { "body": "<p>I would use an enum type instead of having to pass a class in. This way, it's impossible to pass something bad in, and you can catch errors at compile time instead of runtime.</p>\n\n<pre><code>enum VegetableType { CARROT, TOMATO, CUCUMBER };\n</code></pre>\n\n<p>Then your buy method would be simply</p>\n\n<pre><code>static ArrayList&lt;Vegetable&gt; buy(int num, VegetableType vegType) {\n ArrayList&lt;Vegetable&gt; veggies = new ArrayList&lt;Vegetable&gt;(n); //n is the initial capacity - size is still zero.\n for(int i=0; i &lt; num; ++i) {\n double weight = (Math.random() * 200) + 100;\n\n switch(vegType) {\n case VegetableType.CARROT:\n veggies.add(new Carrot(weight));\n break;\n case VegetableType.TOMATO:\n veggies.add(new Tomato(weight));\n break;\n case VegetableType.CUCMBER:\n veggies.add(new Cucumber(weight));\n break;\n }\n }\n return veggies;\n }\n</code></pre>\n\n<p>Now of course the problem is that you end up having a big <code>switch</code> statement in the middle in your loop. Generally, while ugly I'd say that this is sufficient - you get some more control over each of the individual constructors, so you're not constrained to the same set of parameters.</p>\n\n<p>The other thing that you could do is have a factory method on the <code>VegetableType</code> to create an instance:</p>\n\n<pre><code>enum VegetableType {\n CARROT { Vegetable createInstance(int weight) { return new Carrot(weight); }},\n TOMATO { Vegetable createInstance(int weight) { return new Tomato(weight); } },\n CUCUMBER { Vegetable createInstance(int weight) { return new Cucumber(weight); } };\n\n abstract Vegetable createInstance(int weight);\n}\n</code></pre>\n\n<p>Then your list becomes</p>\n\n<pre><code>static ArrayList&lt;Vegetable&gt; buy(int num, VegetableType vegType) {\n ArrayList&lt;Vegetable&gt; veggies = new ArrayList&lt;Vegetable&gt;();\n for(int i=0; i &lt; num; ++i) {\n double weight = (Math.random() * 200) + 100;\n veggies.add(vegType.createInstance(weight));\n }\n return veggies;\n } \n</code></pre>\n\n<p>Finally, if you want to get fancy, <code>java.lang.reflect</code> has the <code>Constructor</code> class:</p>\n\n<p><a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/reflect/Constructor.html\">http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/reflect/Constructor.html</a></p>\n\n<p>You can then use this to get the constructor to the <code>Vegetable</code> type of your choice, and then call construct repeatedly in the loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T01:07:32.550", "Id": "8481", "ParentId": "8467", "Score": "14" } }, { "body": "<blockquote>\n <p>Is it a good way of doing that? </p>\n</blockquote>\n\n<p>No. Give more thought about the <em>separation of concerns</em> for each class. The buy logic does not belong in a factory. A factory is only for creating the various veggie types. <code>Buy</code> should be in a <code>VegetableStand</code> class or perhaps in the <code>Vegetable</code> class. </p>\n\n<p>If \"buying\" logic is unique per vegetable then put buy() in the <code>Vegetable</code> class - especially if it also has a <code>price</code> property. Even so, I can see a <code>VegetableCart.Buy()</code> that accumulates everything into a \"bag\" so the different veggies, quantities, and prices can be added - for a total price to the customer.</p>\n\n<blockquote>\n <p>And is it ideologically correct to name it factory?</p>\n</blockquote>\n\n<p>Not the way you've written it. A veggie factory is for creating various veggies. I expect to see a <code>create()</code> method, passing in an enum as suggested above. </p>\n\n<pre><code>public class VegetableStand {\n VeggieFactory myVF = new VeggieFactory();\n\n public ArrayList&lt;Vegetable&gt; bag = new ArrayList&lt;Vegetable&gt;;\n\n public ArrayList&lt;Vegetable&gt; Buy (VegetableType whatKind ,int howMany){\n for (int i=0, i&lt;howMany; i++) {\n bag.add(myVF.Create(whatKind);\n }\n }\n\n public double TotalSale (ArrayList&lt;Vegetable&gt; bag) {\n double totalPrice = new double;\n\n foreach (Vegetable item in Bag) {\n totalPrice += item.Price;\n }\n\n return totalPrice;\n }\n}\n\ninternal class VeggieFactory {\n public static Vegetable Create(VegetableType whatKind) {\n Vegetable thisKind;\n\n switch(whatKind) {\n case: VegetableType.carrot\n thisKind = CreateCarrot();\n break;\n case: VegetableType.cucumber\n thisKind = CreateCucumber();\n break;\n default:\n throw new Veggie not invented yet exception;\n }\n return thisKind;\n }\n}\n</code></pre>\n\n<p>Then, in the <code>buy()</code> method you should not have a big <code>switch</code> statement in the <code>for</code> loop. If you're passing in a veggie instance, that doesn't make sense. If you already created that veggie, why the factory?</p>\n\n<ul>\n<li>You should separate the creation of the <code>ArrayList&lt;Vegetable&gt;</code> from the creation of the vegetables themselves. The <code>buy()</code> method creates a new list for every veggie you buy. And, you may want to instantiate a veggie w/o a list.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T00:31:00.450", "Id": "33380", "Score": "0", "body": "Would it make sense in this case you pass the `VeggieFactory` into the `VegetableStand` via the constructor to decouple them?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-23T17:55:03.947", "Id": "35569", "Score": "0", "body": "@Supericy, doesn't hurt, if I expected the factory design to evolve such that there will be various kinds of VeggieFactory then absolutely." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T04:46:34.840", "Id": "8486", "ParentId": "8467", "Score": "6" } }, { "body": "<p>As far I see nobody pointed out yet that the reference type of the list should be only <code>List</code>. Instead of</p>\n\n<pre><code>ArrayList&lt;Vegetable&gt; res = new ArrayList&lt;Vegetable&gt;(num);\n</code></pre>\n\n<p>use</p>\n\n<pre><code>List&lt;Vegetable&gt; res = new ArrayList&lt;Vegetable&gt;(num);\n</code></pre>\n\n<p>The signature of the method also should be changed:</p>\n\n<pre><code>public static List&lt;Vegetable&gt; buy(int num, Class vegetableClass)\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/2279030/type-list-vs-type-arraylist-in-java\">Type List vs type ArrayList in Java</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T12:17:35.473", "Id": "8497", "ParentId": "8467", "Score": "3" } }, { "body": "<p>Apart from what's already been said, when dealing with <code>Class</code>, you should use type boundaries to eliminate the possibility of receiving something you weren't expecting:</p>\n\n<pre><code>public static &lt;T extends Vegetable&gt; ArrayList&lt;Vegetable&gt; buy(int num, Class&lt;T&gt; vegetableClass)\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code>v = (T) vegetableClass.getDeclaredConstructor(Double.TYPE).newInstance(weight);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T12:40:55.960", "Id": "8498", "ParentId": "8467", "Score": "2" } } ]
{ "AcceptedAnswerId": "8481", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T20:54:21.080", "Id": "8467", "Score": "10", "Tags": [ "java", "design-patterns", "object-oriented" ], "Title": "Vegetable factory" }
8467
<p>Is there a better or easier way of doing this?</p> <pre><code>if array[1] and array[2] and array[3] and array[4] and array[5] == false then --somthing end </code></pre> <p>I have a lot of arrays to check and was wondering if there is a way to work with arrays where you can do something like <code>array[1-6]</code> or <code>[1,6]</code> or something. Can't seem to find anything online.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T22:58:07.327", "Id": "13245", "Score": "0", "body": "The code in the title is different than what you put in the text. Which one you you want to \"shrink\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T23:41:08.963", "Id": "13246", "Score": "0", "body": "the one in text... But it doesnt seem to be possible.." } ]
[ { "body": "<p>I'm not sure of the lua syntax but something like</p>\n\n<pre><code>arrayAllFalse=TRUE;\nfor element in array\n if (element) then \n arrayAllFalse=FALSE\n end\n\nif (arrayALLFalse) then\n --something\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T21:20:21.113", "Id": "8469", "ParentId": "8468", "Score": "2" } }, { "body": "<p>If the amount is known (5 elements, etc) then I'd use <a href=\"http://www.lua.org/manual/5.1/manual.html#pdf-unpack\" rel=\"nofollow\">unpack</a> (table.unpack in Lua 5.2), especially if your last condition is \"== false\" instead of \"true\", like the rest:</p>\n\n<pre><code>local t1,t2,t3,t4,t5 = unpack(array)\n\nif t1 and t2 and t3 and t4 and not t5 then\n ...\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T23:47:19.860", "Id": "13247", "Score": "0", "body": "this wont shrink the amount of text written." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T00:51:25.730", "Id": "13248", "Score": "0", "body": "On each line, it does. And it's also clearer, especially if you give the variables a good name." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T23:03:34.063", "Id": "8470", "ParentId": "8468", "Score": "1" } }, { "body": "<p>You can use a function like this:</p>\n\n<pre><code>function checktruth(t, i, e)\n local r = true\n for j = i, e do\n r = r and t[j]\n end\n return r\nend\n</code></pre>\n\n<p>And then call:</p>\n\n<pre><code>if checktruth(array, 1, 4) and not array[5] then\n</code></pre>\n\n<p>As you can see, it can not handle the last part (not array[5]), but you can modify it (not without making it more verbose).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T13:12:01.227", "Id": "13249", "Score": "0", "body": "the arrays to check is not always in numbers right after each other, but this inspired me to find a solution :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T01:02:06.860", "Id": "8471", "ParentId": "8468", "Score": "2" } }, { "body": "<p>If you'resure you'll never have strings as keys formatted as \"number-number\" in the table, you could give this a metamethod twist:</p>\n\n<pre><code>tab={'a','b','c','d','e'}\nmt={ __index=function(t,k)\n if type(k)==\"string\" then\n from,to=k:match(\"(%d+)-(%d+)\")\n res={}\n print(from,to)\n for i = tonumber(from),tonumber(to) do\n print(\"\",i-from+1)\n res[i-from+1]=t[tonumber(i)]\n end\n return res\n end\nend}\nsetmetatable(tab,mt)\nprint(unpack(tab[\"1-3\"]))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T09:26:33.960", "Id": "8472", "ParentId": "8468", "Score": "1" } } ]
{ "AcceptedAnswerId": "8471", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T21:13:24.950", "Id": "8468", "Score": "3", "Tags": [ "lua" ], "Title": "Consolidating array accesses" }
8468
<p>I have a custom validator that checks the min and max score of different sporting leagues -- e.g., MLB, NBA, NFL, NCAAB, etc.</p> <p>Here's short version of what it looks like:</p> <pre><code>class ScoreValidator &lt; ActiveModel::Validator def validate(event) if event.league_is_mlb? if event.total_score &lt; 1 event.errors.add :base, 'min total score for an MLB event is 1' elsif event.total_score &gt; 49 event.errors.add :base, 'max total score for an MLB event is 49' end elsif event.league_is_nba? if event.total_score &lt; 119 event.errors.add :base, 'min total score for an NBA event is 119' elsif event.total_score &gt; 370 event.errors.add :base, 'max total score for an NBA event is 370' end end end end </code></pre> <p>Seems like this code could be much cleaner by making smarter use of ruby data structures and methods. Any creative suggestions you could make would be educational and much appreciated.</p>
[]
[ { "body": "<ol>\n<li><p>You can refactor each condition using <a href=\"http://martinfowler.com/refactoring/catalog/extractMethod.html\" rel=\"nofollow\">extract method</a></p>\n\n<pre><code>def validate_mlb_score\ndef validate_nba_score\n</code></pre></li>\n<li><p>Also you can methods to determine min/max score</p>\n\n<pre><code>def max_score_for(event)\n event.league_is_mlb? ? 49 : 370 # judging by your elseif without else I've suggested about only two leagues\nend\n</code></pre></li>\n</ol>\n\n<p>I think my code would look like:</p>\n\n<pre><code>def validate(event)\n if event.total_score &lt; event.min_score\n event.errors.add :base, \"min total score for an #{event.name} event is #{event.min_score}\"\n elsif event.total_score &gt; event.max_score\n event.errors.add :base, \"max total score for an #{event.name} event is #{event.max_score}\"\n end\nend\n\n# I also suggest what you have this kind of model\nclass Event &lt; ActiveRecord::Base\n\n def min_score\n self.league_is_mlb? ? 1 : 119\n end\n\n def max_score\n self.league_is_mlb? ? 49 : 370\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T20:51:08.167", "Id": "13250", "Score": "0", "body": "I like your suggestion on using extract method to make clearer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T18:41:01.860", "Id": "8475", "ParentId": "8473", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T18:11:04.417", "Id": "8473", "Score": "1", "Tags": [ "ruby-on-rails", "ruby" ], "Title": "Refactoring custom validator using lots of if's" }
8473
<p>I am looking for best practice on how I may write this function more efficiently. </p> <pre><code> var d = new Date(), time = d.getHours(), day = d.getDay(); if (day &gt; 0 || day &lt; 7){ if (time &gt; 18 || time &lt; 8){ // execute code } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:20:28.423", "Id": "13253", "Score": "2", "body": "What makes you think your current code is inefficient?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:22:20.927", "Id": "13254", "Score": "0", "body": "I thought there may be a way to run everything in one if statement to make it more efficient. I am not really sure just looking to see if I can optimize." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:23:33.730", "Id": "13255", "Score": "0", "body": "Yes, you can combine the two `if` statements into one with the logical AND operator `&&`, but I don't think the efficiency difference will be noticeable, if there is one at all. If you find your current code more readable, there's nothing wrong in keeping it as it is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:28:56.953", "Id": "13256", "Score": "1", "body": "You are doing something I see a lot of new programmers do, which is worrying about *efficiency* (to the point of silliness) when there's *lots and lots* of better stuff a new programmer *should* be worrying about. Some free advice (that's worth its cost, I'm sure): Don't ask any more questions about efficiency until you know enough to ask questions about efficiency, at which time you will no longer want to ask questions about efficiency." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T22:37:04.703", "Id": "13263", "Score": "0", "body": "@lwburk Don't the 2 go hand in hand? I am just trying to learn through example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T22:40:27.193", "Id": "13264", "Score": "0", "body": "@user10480 - You're using a PC that can perform billions of instructions every second. How many *billions* of instructions do you think you can save here? Get my point? Any change you make will be imperceptible." } ]
[ { "body": "<pre><code>if ( (day &gt; 0 || day &lt; 7) &amp;&amp; (t &gt; 18 || t &lt; 8))\n</code></pre>\n\n<p>Is this what you want?</p>\n\n<p>Second condition will only be evaluated only if the first one is true. If the first one is true, then only the second one is evaluated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:24:28.963", "Id": "13257", "Score": "0", "body": "yes, this is what I was looking for. Thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:25:29.943", "Id": "13258", "Score": "2", "body": "But, `(day > 0 || day < 7)` makes no sense to me. Why would you want to do that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:27:59.743", "Id": "13259", "Score": "0", "body": "I do not want my code to run on Sat / Sun. Is this wrong?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:29:00.750", "Id": "13260", "Score": "0", "body": "@jnolte, Saturday is day `6`, since days are zero-based." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:35:46.590", "Id": "13261", "Score": "0", "body": "@jnolte Have a look at this. http://sprunge.us/NGKi I guess, this is what you want." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:22:40.973", "Id": "8477", "ParentId": "8476", "Score": "1" } }, { "body": "<p>Change the first conditional to </p>\n\n<pre><code>if(day&gt;0)\n</code></pre>\n\n<p>The Date.getDay() function always returns an integer between 0 - 6 so it will never be greater than or equal to seven.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:38:51.833", "Id": "8478", "ParentId": "8476", "Score": "0" } } ]
{ "AcceptedAnswerId": "8477", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T19:18:53.440", "Id": "8476", "Score": "0", "Tags": [ "javascript" ], "Title": "Better way to determine date" }
8476
<pre><code>(defmacro with-condition-retries(retries expected-errors fail-function &amp;body body) "Attempts to execute `body` `retries` times, watching for `expected-errors`. Optionally, if `fail-function` is set, each time a failure occurs, prior to retrying, `fail-function` is executed. Other conditions beside `expected-errors` will exit out of this macro" (let ((counter (gensym)) (result (gensym)) (start-tag (gensym)) (error-handler #'(lambda (c) (let ((r (find-restart 'handler c))) (when r (invoke-restart r c)))))) `(let ((,counter 0) (,result)) (tagbody ,start-tag (restart-case (handler-bind ,(mapcar #'(lambda (error-val) (list error-val error-handler)) expected-errors) (setf ,result ,@body)) ;;the restart pointed at by the error-handler lambda (handler (&amp;rest args) (declare (ignore args)) (incf ,counter) (unless (&gt; ,counter ,retries) (when ,fail-function (funcall ,fail-function)) (go ,start-tag))))) ,result))) </code></pre>
[]
[ { "body": "<p>This is the sort of thing you want to get as many eyes on as possible. My gut tells me that you'd want to break it up into smaller functions, but I'm not entirely sure where I'd cut. Any chance of getting an example use or test case? Could you explain the reasoning behind using <code>tagbody</code> with a single <code>go</code> rather than a <code>loop</code>?</p>\n\n<p>Preliminary stuff I've noticed</p>\n\n<hr>\n\n<p><code>with-gensyms</code> can save you a few lines at the beginning, and you should probably define it in a macro-heavy package.</p>\n\n<pre><code>(defmacro with-gensyms (syms &amp;body body)\n `(let ,(loop for s in syms collect `(,s (gensym)))\n ,@body))\n</code></pre>\n\n<hr>\n\n<p>The expression <code>(setf ,result ,@body)</code> might do some odd things if <code>body</code> is composed of multiple expressions. That should probably be <code>(setf ,result (progn ,@body))</code> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T17:48:34.623", "Id": "13309", "Score": "0", "body": "I didn't want to scrape the loop facility to get exactly the right parameters - tagbody/go expresses things pretty well, if a rather imperatively. Also I've noticed loop in macros tends to require careful handling of quoting." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T15:59:34.633", "Id": "8508", "ParentId": "8488", "Score": "1" } }, { "body": "<p>You may try breaking this task up into two smaller tasks.</p>\n\n<ol>\n<li>A macro that tries to execute &amp;body, watching for errors. Calls a fail function if defined. Returns information related to error, etc., and </li>\n<li>A macro that executes <a href=\"http://letoverlambda.com/lol.lisp\" rel=\"nofollow\">1</a> n times.</li>\n</ol>\n\n<p>Also, since you are watching out for unintentional variable capture, you may want to look at the <a href=\"http://letoverlambda.com/lol.lisp\" rel=\"nofollow\">defmacro!</a> abstraction. I find the ,g! syntax even more direct than with-gensyms. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T00:06:45.987", "Id": "8526", "ParentId": "8488", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T07:46:33.843", "Id": "8488", "Score": "7", "Tags": [ "common-lisp" ], "Title": "Common Lisp macro: review for code quality & leaky name escaping" }
8488
<p>I need to determine a meeting date which convenes on the second Thursday of every month.</p> <p>I've written the following code to do this:</p> <pre><code>//Determine next monthly meeting (occurs on 2nd thursday of each month) define('MAX_POSSIBLE_SECOND_THURS', 14); define('JANUARY', 1); define('DECEMBER', 12); define('THURSDAY', 4); $current_month = intval(date('n')); $next_month = $current_month == DECEMBER ? 1 : $current_month + 1; $current_day = intval(date('j')); $iThursdayCount = 0; $month_to_use = $current_day &lt;= MAX_POSSIBLE_SECOND_THURS ? $current_month : $next_month; $year_to_use = $month_to_use &lt;&gt; JANUARY ? intval(date('Y')) : intval(date('Y')) + 1; for ($iDay = 1; $iDay &lt;= MAX_POSSIBLE_SECOND_THURS; $iDay++) { $date_to_check = strtotime($year_to_use.'-'.$month_to_use.'-'.$iDay); if(date('N', $date_to_check)== THURSDAY) { $iThursdayCount++; if ($iThursdayCount == 2) break; } } $next_meeting_date = $month_to_use.'/'.$iDay.'/'.$year_to_use; echo $next_meeting_date; </code></pre> <p>Although the loop is small, it seems like a lot of work to determine the second Thursday. Are there any improvements that can be made? Or would you do something totally different?</p>
[]
[ { "body": "<p>Try the <a href=\"http://www.php.net/manual/en/class.datetime.php\">DateTime class</a>. With this you can use <a href=\"http://www.php.net/manual/en/datetime.formats.relative.php\">relative formats</a>:</p>\n\n<pre><code>new DateTime('second thu of next month');\nnew DateTime('second thu of jul');\n</code></pre>\n\n<p>That should make the code a lot easier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T14:13:18.910", "Id": "13291", "Score": "0", "body": "I turned 20 lines of code to 3 with no loops. Beautiful! ty." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T12:01:58.083", "Id": "8496", "ParentId": "8493", "Score": "6" } } ]
{ "AcceptedAnswerId": "8496", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T10:53:05.303", "Id": "8493", "Score": "1", "Tags": [ "php" ], "Title": "Best way to get day-of-week occurance" }
8493
<p>I'm seeing a lot of code like this at my new site</p> <pre><code> try { Task.Factory.StartNew(() =&gt; { ... }); } catch (AggregateException ex) { ex.Handle((x) =&gt; { Log.Write(x); return true; }); } </code></pre> <p>From what I've read, as Wait(), Result or Exception are not called the AggregateException will not have been marshalled. Also the Task may not even of started yet. I'm thinking of using Joe Albahari's extension method that uses a continuation as these are mainly fire and forget Tasks</p> <pre><code>public static void PrintExceptions (this Task task) { task.ContinueWith (t =&gt; { var ignore = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted); } </code></pre> <p>Am I on the right track?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T02:08:37.493", "Id": "13284", "Score": "1", "body": "That looks wrong to me. You should inspect the code base for other, subtler, worse mistakes or misconceptions. Threading is hard, and I have yet to see correctly multi-threaded corporate code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T16:30:23.680", "Id": "13371", "Score": "0", "body": "What can be worse than never checking for exceptions? That's what this code does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-10T22:26:29.233", "Id": "210214", "Score": "1", "body": "This is bad code and should never be written. http://blog.stephencleary.com/2013/08/startnew-is-dangerous.html" } ]
[ { "body": "<p>You are quite right. These exception handling blocks will never catch any task exceptions. The code should be modified to check the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.isfaulted.aspx\" rel=\"nofollow\">Task.IsFaulted</a> flag in the continuation and check the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.exception.aspx\" rel=\"nofollow\">Task.Exception</a> property for the actual exception. </p>\n\n<p>In fact, should an exception occur it will remain unhandled and your application will crash unless you attach an exception handler to <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.unobservedtaskexception.aspx\" rel=\"nofollow\">TaskScheduler.UnobservedTaskException</a>.</p>\n\n<p>You should definitely check the \"<a href=\"http://msdn.microsoft.com/en-us/library/dd997415.aspx\" rel=\"nofollow\">Exception Handling (Task Parallel Library)</a>\" article in MSDN for the proper ways to handle Task exceptions. </p>\n\n<p>You should also take a look at the <a href=\"http://msdn.microsoft.com/en-us/vstudio/gg316360\" rel=\"nofollow\">Async CTP for C#</a>. It has a production license even though it is technically a CTP and it will make coding with Tasks a lot easier and safer, as you can see from the snippet I found <a href=\"http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions\" rel=\"nofollow\">here</a>:</p>\n\n<pre><code>private async void FetchData()\n{\n using (var wc = new WebClient())\n {\n try\n {\n string content = await wc.DownloadStringTaskAsync(\n new Uri(\"http://www.interact-sw.co.uk/oops/\"));\n\n textBox1.Text = content;\n }\n catch (WebException x)\n {\n textBox1.Text = \"Error: \" + x.Message;\n }\n }\n}\n</code></pre>\n\n<p>You can use the CTP just by adding a reference to the appropriate DLL. The resulting code will certainly be safer that what you posted here, CTP or not.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T16:40:13.077", "Id": "8562", "ParentId": "8494", "Score": "3" } }, { "body": "<p>I agree with what has been said before. Here is what I think</p>\n\n<p>As far as I was aware, there are certain methods/properties that cause a Task to have its Exceptions \"Observed\", these are \"Result/Wait()\"</p>\n\n<p>As already stated you would also need to handle TaskScheduler.UnobservedTaskException is 100% correct as far my knowledge goes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-15T19:36:47.350", "Id": "310719", "Score": "0", "body": "This is much better as a (terse) comment" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T10:24:09.913", "Id": "9216", "ParentId": "8494", "Score": "2" } } ]
{ "AcceptedAnswerId": "8562", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T02:04:10.870", "Id": "8494", "Score": "7", "Tags": [ "c#", "exception" ], "Title": "Is this the wrong way to handle AggregateException with Tasks" }
8494
<p>I've written this class for two purposes (I think only this fact shows that this code violates <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="nofollow">SRP</a>): convert weight from one unit to another and to represent them accurate or not accurate. So class methods can be used for calculation and the <code>present</code> method rounds the value for presentation. I don't like this code - can you propose better solution?</p> <pre><code>class Temperature UNITS = %w(C F) DEFAULT_UNITS = "C" attr_reader :value, :units def initialize(value, units = DEFAULT_UNITS) @value = value @units = units.to_s end def as(units, accurate) return unless UNITS.include?(units.to_s) value = units.to_s == @units ? @value : self.class.try("#{@units.downcase}_to_#{units.downcase}", @value) accurate ? value : self.class.new(value, units).present end def default(accurate = false) as(DEFAULT_UNITS, accurate) end def present value.round(1) end def self.c_to_f(val) val * 9 / 5 + 32 end def self.f_to_c(val) (val - 32) * 5 / 9 end end </code></pre>
[]
[ { "body": "<p>First of all, don't use plural identifiers if the variable or constant doesn't hold multiple values (e.g. rename <code>DEFAULT_UNITS</code> to <code>DEFAULT_UNIT</code> and <code>units</code> to <code>unit</code>) as it can be very confusing.</p>\n\n<hr>\n\n<p>Why don't you just always store the temperature in ℃? Having only one possible data representation in a class can significantly simplify the methods in that class. Convert lazily to ℉ lazily, when you need to.</p>\n\n<pre><code>class Temperature\n ...\n\n def initialize(value, unit = DEFAULT_UNIT)\n raise SomeError unless UNITS.include?(unit)\n if unit == \"C\"\n @value = value\n else\n @value = (value - 32) * 5 / 9\n end\n end\n\n ...\nend\n</code></pre>\n\n<hr>\n\n<p>Also, in your <code>Temperature#as</code> method you might want to change the ternary operator to an <code>if</code>-<code>else</code> statement to make it more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T09:01:15.440", "Id": "13326", "Score": "0", "body": "Measurements::Temperature stores the temperature values only in ℃. I cannot predict in what format temperature will be created: it has a value field and units accessor:" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T18:56:12.917", "Id": "8513", "ParentId": "8499", "Score": "0" } }, { "body": "<pre><code>class Numeric\n\n def fahrenheit_to_celsius\n (self - 32) * 5 / 9\n end\n\n def celsius_to_fahrenheit\n self * 9 / 5 + 32\n end\n\nend\n\np -7.5.celsius_to_fahrenheit #=&gt; 18.5\n</code></pre>\n\n<p>Classes are open for a reason in ruby. A temperature is just a number, converting it is just a method. The accuracy thing disappears by itself - an integer results in an integer, a float will give a float.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T23:20:51.830", "Id": "8524", "ParentId": "8499", "Score": "2" } }, { "body": "<p>I would separated logic for Celsius and Fahrenheit into separate classes. Here is a code to demonstrate the general approach:</p>\n\n<pre><code>class Temperature\n attr_reader :value\n\n def initialize value # or you can go further and dont\n @value = value\n end\nend\n\nclass Celsius &lt; Temperature \n def to_fahrenheit\n Fahrenheit.new value * 9 / 5 + 32\n end\nend\n\nclass Fahrenheit &lt; Temperature\n def to_celsius\n Celsius.new (value - 32) * 5 / 9\n end\nend\n</code></pre>\n\n<p>With this approach you have good abstractions for different types of temperature and you don't mess different logic in the single class. Probably you will not need 'unit' property because you will have class names holding it (you can add it easily in both classes if you want). </p>\n\n<p>Then you can write factory methods in <code>Numeric</code> class to write more clear code with temperature classes:</p>\n\n<pre><code>class Numeric\n def fahrenheit\n Fahrenheit.new(self)\n end\n\n def celsius\n Celsius.new(self)\n end\nend\n\ncels = -5.celsius\ncels.to_fahrenheit.value # =&gt; 23\n</code></pre>\n\n<p>Regarding <code>accurate</code> property - you can accept it in the initializer or you can accept it in conversion methods (<code>to_celsius</code>, <code>to_fahrenheit</code>).</p>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p>You can also implement <code>accurate</code> as a mixin (kind of decorator):</p>\n\n<pre><code>module Inaccurate\n def value\n @value.round(1)\n end\nend\n\nclass Numeric\n def fahrenheit accurate = true\n Fahrenheit.new(self).tap { |t| t.extend(Inaccurate) unless accurate }\n end\n\n def celsius accurate = true\n Celsius.new(self).tap { |t| t.extend(Inaccurate) unless accurate }\n end\nend\n\nputs -5.45.celsius.value # =&gt; -5.45\nputs -5.45.celsius(false).value # =&gt; -5.5\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p><code>Temperature</code> is abstraction of real-world temperature. Your <code>as</code> conversion method is specific to your application's data format ('C' and 'F' strings in user profile). Taking SRP principle into account, it is better to extract this conversion logic from <code>Temperature</code> class. You can do this with module, something like this:</p>\n\n<pre><code>module UserTemperatureConverter\n def as value, t_type, accurate = true\n case t_type\n when 'C'\n value.celsius(accurate)\n when 'F'\n value.fahrenheit(accurate)\n end\n end\n\n extend self # make 'as' a class method of UserTemperatureConverter\nend\nTemperature.extend UserTemperatureConverter # make 'as' a class method of Temperature\n\nUserTemperatureConverter.as(17, 'C') # =&gt; Celsius\n# or\nTemperature.as(18, 'F') # =&gt; Celsius\n\n# or make temperature conversion instance method and include it into `Temperature` as `Temperature#as`\n</code></pre>\n\n<p>Also you may find useful in your application to define basic self-conversion methods for <code>Celsius</code> and <code>Fahrenteit</code>:</p>\n\n<pre><code>class Celsius\n def to_celsius; self; end\nend\n\nclass Fahrenheit\n def to_fahrenheit; self; end\nend\n\n17.celsius.to_celsius # Celsius\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-06T09:16:49.157", "Id": "13607", "Score": "0", "body": "Cool approach! But I need method as() instead of named methods because I get units from the current_user profile to display values in desired units." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-06T11:55:20.870", "Id": "13612", "Score": "0", "body": "@Antiarchitect, added some thoughts on how you may implement temperature conversion/construction logic with my approach." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T18:53:51.960", "Id": "8604", "ParentId": "8499", "Score": "2" } }, { "body": "<p>I would avoid to maintain different classes for different temperature scales. I mae an example based on Kelvin.</p>\n\n<p>With <code>Temperature.new( value[, unit])</code> you can define a temperature, the unit is optional.</p>\n\n<p>Later you have access to the values with <code>Temperature#celcius</code>, <code>Temperature#kelvin</code> od <code>Temperature#fahrenheit</code>. If you need other scales (e.g. Réaumur) you could add them without any problem.</p>\n\n<p>The <code>as</code> is also implemented, it has two parameters: The unit and a rounding factor.</p>\n\n<p>My code:</p>\n\n<pre><code>class Temperature\n\n class Too_Cold &lt; ArgumentError; end\n UNITS = %w(C F K)\n DEFAULT_UNIT = \"K\"\n\n attr_reader :kelvin\n\n def initialize(value, unit = DEFAULT_UNIT)\n case unit\n when 'K'\n @kelvin = value\n when 'C' \n @kelvin = 273.15 + value\n when 'F'\n @kelvin = (value + 459.67) * 5/9\n else\n raise ArgumentError, \"Unknown Unit #{unit}\"\n end\n raise Too_Cold if @kelvin &lt; 0\n\n @celcius = @kelvin - 273.15\n @fahrenheit = @kelvin * 1.8 - 459.67\n end\n\n attr_reader :kelvin\n attr_reader :celcius\n attr_reader :fahrenheit\n\n def ==(other)\n @kelvin == other.kelvin\n end\n\n def as(unit, round = nil)\n return unless UNITS.include?(unit.to_s)\n value = case unit\n when 'C'; @celcius\n when 'F'; @fahrenheit\n when 'K'; @kelvin\n end\n round ? value.round(round) : value\n end\n\n def default(accurate = false)\n as(DEFAULT_UNITS, accurate)\n end\n\n def to_s(unit=DEFAULT_UNIT)\n \"#{as(unit,2)}#{unit}\"\n end\nend\n</code></pre>\n\n<p>I calculated once the values for all units. You could also re-implement the class and calculate the value only if you need it.</p>\n\n<p>And a corresponding test code. Please see the <code>assert_in_delta</code>-checks. I used float operations, so test on equality may fail.</p>\n\n<pre><code>require 'test/unit'\n\nclass TempTest &lt; Test::Unit::TestCase\n def test_unit\n assert_raise(ArgumentError){ Temperature.new(0,'X')}\n assert_nothing_raised{ Temperature.new(0,'K')}\n assert_nothing_raised{ Temperature.new(0,'C')}\n assert_nothing_raised{ Temperature.new(0,'F')}\n end\n def test_0K\n assert_nothing_raised{ Temperature.new(0,'K') }\n assert_nothing_raised{ Temperature.new(-273.15,'C')}\n assert_nothing_raised{ Temperature.new(-459.67,'F')}\n assert_equal(0, Temperature.new(0,'K').kelvin)\n assert_equal(-273.15, Temperature.new(0,'K').celcius)\n assert_equal(-459.67, Temperature.new(0,'K').fahrenheit)\n assert_equal(Temperature.new(0,'K'), Temperature.new(-273.15,'C'))\n assert_equal(Temperature.new(0,'K'), Temperature.new(-459.67,'F'))\n end\n def test_too_cold\n assert_raise(Temperature::Too_Cold){ Temperature.new(-1,'K') }\n assert_raise(Temperature::Too_Cold){ Temperature.new(-273.16,'C')}\n assert_raise(Temperature::Too_Cold){ Temperature.new(-459.68,'F')}\n end\n def test_similar\n -200.upto(300){|i|\n assert_in_delta(i, Temperature.new(i,'K').kelvin) if i &gt;= 0\n assert_in_delta(i, Temperature.new(i,'C').celcius)\n assert_in_delta(i, Temperature.new(i,'F').fahrenheit)\n }\n end\n\n def test_as_kelvin\n assert_equal(0, Temperature.new(0,'K').as('K'))\n end\n def test_as_celcius\n assert_in_delta(10, Temperature.new(10,'C').as('C'))\n assert_in_delta(10.2, Temperature.new(10.2,'C').as('C'))\n assert_in_delta(10, Temperature.new(10.2,'C').as('C',0))\n\n assert_equal(10, Temperature.new(10.2,'C').as('C',0))\n assert_equal(10.2, Temperature.new(10.2,'C').as('C',2))\n end\n def test_as_fahrenheit\n assert_in_delta(10, Temperature.new(10,'F').as('F'))\n assert_in_delta(10.2, Temperature.new(10.2,'F').as('F'))\n assert_in_delta(10, Temperature.new(10.2,'F').as('F',0))\n\n assert_equal(10, Temperature.new(10.2,'F').as('F',0))\n assert_equal(10.2, Temperature.new(10.2,'F').as('F',2))\n end\n def test_to_s\n assert_equal(\"283.15K\", Temperature.new(10,'C').to_s)\n assert_equal(\"10.0C\", Temperature.new(10,'C').to_s('C'))\n end\nend\n</code></pre>\n\n<p>One last remark:\nSee also the <a href=\"https://stackoverflow.com/questions/6322441/units-of-measurement-conversion-gem\">SO-question Units of measurement conversion gem</a>. The ruby-units-gem supports also temperatures.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-03T22:35:22.590", "Id": "48890", "ParentId": "8499", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T14:47:29.527", "Id": "8499", "Score": "4", "Tags": [ "ruby", "ruby-on-rails", "converting" ], "Title": "Temperature converter that seems to violate SRP" }
8499
<p>How can I code this in a better way, in one file? Output must be more than one (if there is more that one status_update with the given word &quot;online or performancedegradation&quot;), like:</p> <blockquote> <pre><code>#online System is operating at peak performance. #directonly Traffic is bypassing Smart CDN system, and going directly to websites. </code></pre> </blockquote> <pre><code>&lt;?php $filename = &quot;export_file_system_status_output&quot;; $status_update = &quot;online&quot;; $handle = fopen($filename, &quot;r&quot;); $file = fread($handle,filesize($filename)); if (preg_match('#' . $status_update . '#', $file, $match)) { echo &quot;&lt;div id=badge_subpage_system&gt; &lt;h5&gt;#online&lt;/h5&gt; &lt;p&gt;System is operating at peak performance.&lt;/p&gt; &lt;/div&gt;&quot;; } ?&gt; &lt;?php $filename = &quot;export_file_system_status_output&quot;; $status_update = &quot;performancedegradation&quot;; $handle = fopen($filename, &quot;r&quot;); $file = fread($handle,filesize($filename)); if (preg_match('#' . $status_update . '#', $file, $match)) { echo &quot;&lt;div id=badge_subpage_system&gt; &lt;h5&gt;#performancedegradation&lt;/h5&gt; &lt;p&gt;Performance is slower than normal.&lt;/p&gt; &lt;/div&gt;&quot;; } ?&gt; &lt;?php $filename = &quot;export_file_system_status_output&quot;; $status_update = &quot;directonly&quot;; $handle = fopen($filename, &quot;r&quot;); $file = fread($handle,filesize($filename)); if (preg_match('#' . $status_update . '#', $file, $match)) { echo &quot;&lt;div id=badge_subpage_system&gt; &lt;h5&gt;#directonly&lt;/h5&gt; &lt;p&gt;Traffic is bypassing Smart CDN system, and going directly to websites.&lt;/p&gt; &lt;/div&gt;&quot;; } ?&gt; </code></pre> <p>It must sort by first status_update found:</p> <ol> <li><p><strong>online</strong></p> <pre><code>#online System is operating at peak performance. </code></pre> </li> <li><p>then <strong>performancedegradation</strong></p> <pre><code>#directonly Traffic is bypassing Smart CDN system, and going directly to websites. </code></pre> </li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T15:05:33.043", "Id": "13296", "Score": "0", "body": "It must sort by first status_update found: Online => then #online\nSystem is operating at peak performance.\n\nperformancedegradation => #directonly\nTraffic is bypassing Smart CDN system, and going directly to websites." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T15:04:04.507", "Id": "137276", "Score": "0", "body": "use conditions, if there are more then use a switch case. File name ends with type of file. Your code is not having full file name" } ]
[ { "body": "<p>I'll give you a hint. Try using a foreach loop:\n<a href=\"http://www.php.net/manual/en/control-structures.foreach.php\" rel=\"nofollow\">http://www.php.net/manual/en/control-structures.foreach.php</a></p>\n\n<p>You can store all your files and associated information in an associative array, such as:</p>\n\n<pre><code>$files = array(\n 0 =&gt; array(\n 'filename' =&gt; \"export_file_system_status_output\"; \n 'status_update' =&gt; \"online\";\n ),\n 1 =&gt; array(\n 'filename' =&gt; \"another_file\"; \n 'status_update' =&gt; \"offline\";\n )\n);\n</code></pre>\n\n<p>You should really try this on your own :) If you don't get it, I'll give you a more complete answer :)</p>\n\n<p>On a side note, your HTML is not valid. Use classes instead of ids when possible, and use quotes:</p>\n\n<pre><code>&lt;div class=\"badge_subpage_system\"&gt;\n &lt;h5&gt;#performancedegradation&lt;/h5&gt;\n &lt;p&gt;Performance is slower than normal.&lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Hope this helps :)</p>\n\n<p>EDIT:</p>\n\n<p>Here's what your final code will look like, with the array I posted above:</p>\n\n<pre><code>foreach($files as $file)\n{\n $handle = fopen($file['filename'], \"r\");\n $file = fread($handle,filesize($file['filename']));\n if (preg_match('#' . $file['status_update'] . '#', $file, $match))\n {\n echo '&lt;div id=\"badge_subpage_system\"&gt;&lt;h5&gt;#performancedegradation&lt;/h5&gt;&lt;p&gt;Performance is slower than normal.&lt;/p&gt;&lt;/div&gt;';\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T16:05:50.693", "Id": "13301", "Score": "0", "body": "like this:\n $arr = array(\"0\", \"1\", \"2\");\n reset($arr);\n while (list(, $value) = each($arr)) {\n echo \"Value: $value<br />\\n\";\n }\n\n foreach ($arr as $value) {\n echo \"Value: $value<br />\\n\";\n }" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T16:22:22.453", "Id": "13303", "Score": "0", "body": "The second line seems right, yes :) The first line is just messy :s Always think about the fact that if others read your code, they should be able to understand easily what your code does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:59:43.743", "Id": "13365", "Score": "0", "body": "Can't get it fixed :( Can you help me on this one?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-05T03:45:48.847", "Id": "13561", "Score": "0", "body": "Sorry for being so late :s anyway, in case you still need help, I've updated my answer aboce :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T15:41:05.203", "Id": "8507", "ParentId": "8502", "Score": "1" } }, { "body": "<ol>\n<li>Write D.R.Y. code. Do not ask php to open the same unchanged file 3 times, just open it once.</li>\n<li>Be precise about where in your text you expect to find your specified keywords.</li>\n<li>Use a lookup to generate the regex and to quickly determine the desired text to present for each occurrence.</li>\n<li>HTML markup must have unique <code>id</code> attributes in the document. Since your output is repeating, you should use a <code>class</code> instead of <code>id</code>. Your attribute values should be quoted as well.</li>\n<li>Though I typically advise against using single-use variables, in this case it serves to separate and describe specific pieces of data / operations.</li>\n</ol>\n<p>Code: (<a href=\"https://3v4l.org/CJUV6\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>$lookup = [\n '#online' =&gt; 'System is operating at peak performance.',\n '#performancedegradation' =&gt; 'Performance is slower than normal.',\n '#directonly' =&gt; 'Traffic is bypassing Smart CDN system, and going directly to websites.'\n];\n$regex = '/^(?:' . implode('|', array_keys($lookup)) . ')(?=\\s)/m';\n\n$contents = file_get_contents(&quot;export_file_system_status_output.txt&quot;);\n$matches = preg_match_all($regex, $contents, $m) ? $m[0] : [];\nforeach ($matches as $keyword) {\n printf(\n '&lt;div class=&quot;badge_subpage_system&quot;&gt;&lt;h5&gt;%s&lt;/h5&gt;&lt;p&gt;%s&lt;/p&gt;&lt;/div&gt;',\n $keyword,\n $lookup[$keyword]\n );\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>&lt;div class=&quot;badge_subpage_system&quot;&gt;&lt;h5&gt;#online&lt;/h5&gt;&lt;p&gt;System is operating at peak performance.&lt;/p&gt;&lt;/div&gt;\n&lt;div class=&quot;badge_subpage_system&quot;&gt;&lt;h5&gt;#directonly&lt;/h5&gt;&lt;p&gt;Traffic is bypassing Smart CDN system, and going directly to websites.&lt;/p&gt;&lt;/div&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-28T23:23:09.977", "Id": "255347", "ParentId": "8502", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-01-31T14:59:54.710", "Id": "8502", "Score": "2", "Tags": [ "php", "html", "parsing", "regex" ], "Title": "Read a text file and print pre-defined html when specific keywords are found" }
8502
<p>I need some second or third eyes to look over this, since right now, the necessary actions to make this work sound just bad and I suppose I am missing something due to a lack of C# experience.</p> <p>I am currently working on a winforms c# application. More specifically, I am reworking a highly convoluted control flow between a custom winforms widget and the corresponding controller.</p> <p>To nail down some terms, the widget is called a DrawingPanel. On the drawing panel, the user can place certain components, which can be considered orange squares for now. He can select single components by clicking on them with the left button, he can select multiple components by dragging a box around them. Once he has components selected, he can right click and select operations like cut, paste, copy and so on with the obvious semantics. For usability reasons, he can also use these operations on a single component without selecting it.</p> <p>In the old state, the control flow between the DrawingPanel and the so-called EventManager mostly looks like two angry cats wrestling in mud, as it goes back and forth about 4 - 6 times in order to deduce the set of selected components. Somewhere in there, they are highlighted, but after an hour, I gave up deducing that for now, especially because there are about 2 dead highlighting functions in there. Since I have to add quite a bit of funcionality here, I guess it is up to me to redo this.</p> <p>In order to redo this, I figured a good way to straighten this out would be the following:</p> <p>I add one event per user command to the DrawingPanel. The Controller of the DrawingPanel subscribes to these events and modifies the model accordingly in the event handler. For example, if a set of components is selected and the user clicks on "Copy" in the context menu, a CopyRequest-Event is raised which has this set of arguments as an argument. If a user clicks on "Paste" in the component menu, a PasteRequest-Event is raised, which is parametrized by the position of the paste request.</p> <p>This should encapsulate the user interface, as the interface is reduced to a black box which is parametrized by the data model and raises events from the user. The EventManager could handle all user interfaces, which provide the appropiate events. Furthermore, the control flow would be greatly simplified, as it would become unidirectional: UI goes to Controller goes to Model.</p> <p>Now, onto my problem. I have some very heavy code duplication in my event handlers in the DrawingPanel. A ton of event handlers subscribe to the Click-Event of a context menu, wrap the currently selected components into an ComponentSetArgument-object and fire the request-event with this new argument (if its not null). I am failing to remove this duplication.</p> <p>So far, I have tried to implement a higher order event handler generator (which would take a component set event and generate an evenhandler to subscribe at the click-event) and a mapping function on events (which would handle the click-event, apply a function and signal the outgoing event). Both of these fail because the multiway delegates are immutable. Thus, correct functionality would depend on creating the mapping or calling the wrap+call-higher order function after all subscribers are subscribed to the event. This yells "recipe for disaster" for me.</p> <p>So, is there anything I can do beyond either tolerating this massive duplication or rolling my own subscription management there? Or, do I take the totally wrong way there and there is a massively better architecture here?</p> <p>Edit 1:</p> <p>I have been asked for sample code. I will try my best to condense the code without removing essential information. I will use the current state of code, which has event-based, improved control flow, but a heavy smell due to duplication. </p> <p>These are the significant portions of the DrawingPanel. </p> <pre><code>// IComponent is something of the model. This class moves them around as black boxes public class ComponentSetEventArguments { public ISet&lt;IComponent&gt; Components; } public delegate void ComponentSetHandler(object sender, ComponentSetEventArguments args); public partial class DrawingPanel { // These events signal an action of the user to the controller. // In order to maintain brevity and demonstrate the problem, I // include just these 2. There are about 6 ComponentSetHandlers // and various other handlers, for example the mentioned PasteRequest // with a PositionEventArgument. // These events closely mimic the events found in actual WinForms-classes, // like ToolStripMenuItem.Click or IPanel.MouseDown. public event ComponentSetHandler CopyRequest; public event ComponentSetHandler CutRequest; // this contains components which were selected by the user. This happens // by clicking on a single component or dragging a box around these // components. This component and the following as well as selecing the // correct context menu to display are done in mouseDown/mouseUp-Handlers, // which are mostly big if-else-chains, so I won't show them. ISet&lt;IComponent&gt;() selectedComponents; // this contains the last component hovered, so you can use the context menu on // a component by just right-clicking on top of it if no other components are // selected IComponent lastHoveredComponent; public DrawingControl() { ... // Let us look at the names first. These are toolstrips in // the componentSetContextMenu. This context menu pops up if the user // right-clicks while more than one component is selected. I have to // differntiate between "1 component selected" and "more than 1 component // selected", because certain operations are only possible for multiple // components. Second, the "cutIn..." means it is the toolstrip item // with the text cut on it. this.copyInComponentSetContextMenu.Click += copyComponentSetHandler; this.cutInComponentSetContextMenu.Click += cutComponentSetHandler; // note the difference, this is just in the component context menu, // not the component set context menu. this.cutInComponentContextMenu.Click += cutComponentHandler; ... } // SMELL: Duplication (I.I) // these two somethingComponentSetHandlers just wrap the selected components // into event arguments and fire the corresponding user request. void copyComponentSetHandler(object sender, EventArgs e) { if (CopyRequest == null) return; // im just omitting safety copies here. ComponentSetArguments a = new ComponentSetArguments(selectedComponents); CopyRequest(this, a); } // SMELL: Duplication (I.II) void cutComponentSetHandler(object sender, EventArgs e) { if (CutRequest == null) return; ComponentSetArgument a = new ComponentSetARguments(selectedComponents); CutRequest(this, a); } // This handler is mostly included as a demonstration why I think this is // a decent approach. It encapsulates the difference of handling a single // component in a convenient way in the UI itself. Further objects do not // need to consider this minor detail. void cutComponentHandler(object sender, EventArgs e) { if (CopyRequest == null) return; ISet&lt;IComponent&gt; components; // if the user selected a single component, cut that component. // if the user selected no components, cut the component he pointed at. if (selectedComponents.Count == 0) { components = new HashSet&lt;IComponent&gt;(); components.Add(lastHoveredComponent); } else { components = selectedComponents; } CutRequest(this, components); } } </code></pre> <p>I am pleasently surprised that it looks like the EventManager is not relevant for this problem. For completeness, the EventManager has a method that subscribes to the CutRequest event. When the CutRequest is fired, the EventManager copies the components from the event argument into a separate collection and removes the cut components from the model itself. </p> <p>Given all that, the smell I am annoyed by becomes apparent, I have marked them as smell I.I and I.II. These methods differ in exactly one thing. The event to signal, CutRequest and CopyRequest and this continues through a number of more methods. </p> <p>My current fixes generally fail because of the immutability of multiway delegates in C#. I cannot create a closure which contains for example CutRequest, because the subscription of new Handlers in CutRequest create a new Multiway delegate and replace the old value of CutRequest with this new delegate. If I need to elaborate more on this, let me know. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T20:56:09.100", "Id": "13297", "Score": "0", "body": "Make sure you have tests in place (unit, integration, functional, etc) to ensure you don't break existing functionality" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T21:09:46.370", "Id": "13298", "Score": "1", "body": "Can you break the problem down to some sample code? This is so hard to answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T10:49:42.910", "Id": "13299", "Score": "0", "body": "Anway, in order to not delay further progress on my part, I just implemented my own mutable multiway delegate. It's precisely the same as a normal delegate, just that it is mutable. That means, I can pass this delegate around into classes during setup time and add handlers later on and things still work. Furthermore, this allowed me to implement a functional map on events, so I have such a channel which maps all EventArgs e on the currently selected components and signals the new event. This reduces the duplication on about 6 lines in the constructor. Thank you all for participating." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T15:41:32.623", "Id": "16714", "Score": "0", "body": "@Tetha You should post the above, preferably with some code samples, as the answer." } ]
[ { "body": "<p>I implemented my own MVC (Model-View-Controller) framework. In order to reduce the number of view events the controller had to subscribe to, I made my views send messages. I.e. I created a <code>Message</code> class containing different useful pieces of information. One of them is a message type that I realized as an enum. Another vital piece of information is the type of the entity which is concerned (like customer, order, invoice). The view exposes only one event to the controller, a ViewEvent event which sends a Message.</p>\n\n<pre><code>public delegate void ViewEventHandler(MvcMessage message);\n\npublic interface IView // Simplified\n{\n event ViewEventHandler ViewEvent;\n}\n\npublic class MvcMessage // Simplified\n{\n public object Source { get; private set; }\n public MessageType MessageType { get; private set; }\n public Type EntityType { get; private set; }\n public EventArgs SourceEventArgs { get; internal set; }\n}\n\npublic enum MessageType // Simplified\n{\n None,\n\n // Requests\n RequestingNew,\n RequestingInsert,\n RequestingOpen,\n RequestingClose,\n RequestingDelete,\n RequestingDraw,\n\n // View Events\n ViewFilterChanged,\n ViewSelectionChanged,\n ViewClosing\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T21:17:02.600", "Id": "8505", "ParentId": "8504", "Score": "0" } }, { "body": "<p>First, I would probably switch to EventHandler&lt;ComponentSetArguments&gt; and ditch ComponentSetHandler, since generics render it obsolete.</p>\n\n<p>Next, it may be useful to have a helper extension method to raise events that do your null check (for several reasons).</p>\n\n<pre><code>public static void SafeInvoke&lt;T&gt; (this EventHandler&lt;T&gt; evt, object sender, T args)\n{\n EventHandler&lt;T&gt; theEvent = evt;\n\n if (theEvent != null)\n {\n theEvent (sender, args);\n }\n}\n</code></pre>\n\n<p>Finally, I notice your events in the example code use the same type of handler, so you could create a common method to raise your events that uses default arguments.</p>\n\n<pre><code>private void RaiseEvent (EventHandler&lt;ComponentSetArguments&gt; evt)\n{\n ISet&lt;IComponent&gt; components;\n // if the user selected a single component, cut that component.\n // if the user selected no components, cut the component he pointed at.\n if (selectedComponents.Count == 0)\n {\n components = new HashSet&lt;IComponent&gt;();\n components.Add(lastHoveredComponent);\n } else\n {\n components = selectedComponents;\n }\n\n evt.SafeInvoke (this, new ComponentSetArguments (components));\n}\n</code></pre>\n\n<p>Then, you just call it as follows:</p>\n\n<pre><code>RaiseEvent (CopyEvent);\nRaiseEvent (CutEvent);\n</code></pre>\n\n<p>For those that are just using selectedComponents, it's just a single line as well:</p>\n\n<pre><code>CopyEvent.SafeInvoke (this, new ComponentSetArguments (selectedComponents));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T18:36:07.310", "Id": "8512", "ParentId": "8504", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T20:48:29.847", "Id": "8504", "Score": "2", "Tags": [ "c#", "user-interface" ], "Title": "How to refactor these C#-events or fix this architecture?" }
8504
<p>How can I script this in a better way?</p> <pre><code>// Tweets $twitter_username_string = "aasampat OR ashwinsampat OR somemore"; $twitter_number_of_tweets = 1; $twitter_hashtags = "ashwinsampat+OR+franq2+OR+franq2.net"; // Instantiate a Twitter object which will scan Twitter depending on the parameters $twitter = new Twitter($twitter_username_string, $twitter_number_of_tweets, $twitter_hashtags); $tweets = $twitter-&gt;getTweets(); foreach ( $tweets as $tweet ) { $tweetoutput = "&lt;p&gt;".$tweet-&gt;title." &lt;em&gt;Tweeted by &lt;a href=".$tweet-&gt;permalink." target=_blank title=@".$tweet-&gt;user."&gt;".$tweet-&gt;author."&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;"; } $twitter_username_string = "aasampat OR ashwinsampat OR somemore"; $twitter_number_of_tweets = 2; $twitter_hashtags = "ashwinsampat+OR+franq2+OR+franq2.net"; // Instantiate a Twitter object which will scan Twitter depending on the parameters $twitter = new Twitter($twitter_username_string, $twitter_number_of_tweets, $twitter_hashtags); $tweets = $twitter-&gt;getTweets(); foreach ( $tweets as $tweet ) { $tweetoutput_secondline = "&lt;p&gt;".$tweet-&gt;title." &lt;em&gt;Tweeted by &lt;a href=".$tweet-&gt;permalink." target=_blank title=@".$tweet-&gt;user."&gt;".$tweet-&gt;author."&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;"; } $myFile = "export_file_twitter_output"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = $tweetoutput; fwrite($fh, $stringData); fclose($fh); $filename = 'export_file_twitter_output'; $somecontent = "$tweetoutput_secondline"; // Let's make sure the file exists and is writable first. if (is_writable($filename)) { // In our example we're opening $filename in append mode. // The file pointer is at the bottom of the file hence // that's where $somecontent will go when we fwrite() it. if (!$handle = fopen($filename, 'a')) { echo "Cannot open file ($filename)"; exit; } // Write $somecontent to our opened file. if (fwrite($handle, $somecontent) === FALSE) { echo "Cannot write to file ($filename)"; exit; } fclose($handle); } else { echo "The file $filename is not writable"; } </code></pre>
[]
[ { "body": "<p>There is a lot of duplication here. The code </p>\n\n<ol>\n<li>downloads one tweet, then stores it in the <code>$tweetoutput</code> variable,</li>\n<li>downloads two tweets, then stores the second in the <code>$tweetoutput_secondline</code> variable,</li>\n<li>opens a file called <code>export_file_twitter_output</code>, then writes the first tweet into it (and closes the file),</li>\n<li>opens the same <code>export_file_twitter_output</code> file and writes the second tweet into it (and closes the file).</li>\n</ol>\n\n<p>I'd download simultaneously the two tweets (<code>$twitter_number_of_tweets = 2</code>), then store both in the same variable:</p>\n\n<pre><code>$tweetoutput = \"\";\nforeach ( $tweets as $tweet )\n{\n $tweetoutput .= \"&lt;p&gt;\" . $tweet-&gt;title . \" &lt;em&gt;Tweeted by &lt;a href=\" .\n $tweet-&gt;permalink .\n \" target=_blank title=@\" . $tweet-&gt;user . \"&gt;\" .\n $tweet-&gt;author . \"&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;\\n\";\n}\n</code></pre>\n\n<p>(Note the <code>.=</code>.)</p>\n\n<p>After that I'd write the contents of <code>$tweetoutput</code> to the file in one step. This would remove a lot of code duplication and it would work with only one network connection instead of two.</p>\n\n<p>I prefer the second file-writing code, it has error handling on <code>fwrite</code> and it checks that the file is writable before opening.</p>\n\n<p>I'd also change the string concatenation to <a href=\"http://php.net/manual/en/function.sprintf.php\" rel=\"nofollow\">sprintf</a> inside the <code>foreach</code> loop. It would result more readable code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T19:10:11.340", "Id": "8514", "ParentId": "8506", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T15:29:19.083", "Id": "8506", "Score": "2", "Tags": [ "php", "optimization" ], "Title": "Twitter scanner" }
8506
<p>This does the job, and it's pretty much all the functionality I need at the moment. However, I feel like it could be optimized a bit. Namely, is there a way I can do this without the <code>div#boundary</code>? Also, the drop down re-fires if I go back up into the menu, which not a big deal, but it would be nice to prevent this behavior.</p> <p><a href="http://jsfiddle.net/NAyWQ/7/" rel="nofollow noreferrer">Demo</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('#press, #contact, #about').bind('mouseenter', function() { var n = $(this).attr("id"); $('#dd_'+n).stop(true, true).slideDown('fast'); $('#menu').children().not('#'+n).bind('mouseenter', function () { $('#dd_'+n).slideUp('fast'); }); $('#boundary').bind('mouseenter', function () { $('#dd_'+n).slideUp('fast'); }); $('#dd_'+n).bind('mouseleave', function () { $('#dd_'+n).slideUp('fast'); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="container"&gt; &lt;div id="header"&gt; &lt;div id="boundary"&gt;&lt;/div&gt; &lt;div id="menu"&gt; &lt;div id="press"&gt;&lt;/div&gt; &lt;div id="contact"&gt;&lt;/div&gt; &lt;div id="about"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="dd_press"&gt;&lt;/div&gt; &lt;div id="dd_contact"&gt;&lt;/div&gt; &lt;div id="dd_about"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T13:46:16.240", "Id": "13336", "Score": "0", "body": "What do you think the purpose of the boundary is? It currently has both a visual and programmatic purpose; is the visual purpose important?" } ]
[ { "body": "<p>I've come up with two options, but I'm not sure if either are an acceptable replacement for you.</p>\n\n<hr>\n\n<p><strong>Option 1</strong></p>\n\n<p>Overlay the expanding menu on the original menu. This allows simplification of the eventing. Only tricky part is that by moving quickly, you could leave one menu and enter another before your mouse was in the expanding menu. Hence the last line of the \"mouseover\" function. Also, the original menu basically must be duplicated between the two menus, as you are overlaying it. If you were going to have some sort of effect on the original menu anyway, this could be an OK thing.</p>\n\n<p><a href=\"http://jsfiddle.net/KY2kY/1/\" rel=\"nofollow\">http://jsfiddle.net/KY2kY/1/</a></p>\n\n<hr>\n\n<p><strong>Option 2</strong></p>\n\n<p>Add everything to the header menu, but hide most of it. Expand and contract that element. Biggest downside here is that now your heights must be set in the code, not the CSS. But it is very, very clean.</p>\n\n<p><a href=\"http://jsfiddle.net/KY2kY/2/\" rel=\"nofollow\">http://jsfiddle.net/KY2kY/2/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T14:30:51.377", "Id": "13421", "Score": "0", "body": "excellent answers jdmichal. a much appreciated code review. \noption 1 - works very well, however from a UI standpoint, I'd rather the containers appear to grow from below the control blocks, which granted is a small thing but to me feels more normal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T14:40:01.583", "Id": "13423", "Score": "0", "body": "option 2 - very nice! in my final layout however my containers are rather wide so they overlap each other visually on drop down... in order to never have them on top of each other (when one is rolling up while the other is rolling down), I'd have to devise some way to stop the animation and go directly back to the default height? I'll \"fiddle\" with it a bit.. but if you see an easy way to do this, I'd much rather use 4 lines of code instead of 10. \n\nagain, many thanks. I'll try to go help someone out now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T06:04:49.177", "Id": "13469", "Score": "0", "body": "@lyndonr For option 1, if the top looks the same, the user would not notice the first part of the animation. Just change the #dd background to yellow and remove the white color from .header and you will see what I mean." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T06:05:30.140", "Id": "13470", "Score": "0", "body": "@lyndonr As for your concerns about option 2, it wouldn't be impossible to queue the sliding actions, since `slideUp` and `slideDown` offer a \"complete\" callback. But, it would decidedly have to be more complicated code to achieve that. The conciseness of option 2 comes directly from each element only having to be concerned about itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T16:58:18.753", "Id": "13482", "Score": "0", "body": "well explained. thank you again for the review." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:55:39.663", "Id": "8560", "ParentId": "8509", "Score": "2" } } ]
{ "AcceptedAnswerId": "8560", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T17:14:53.620", "Id": "8509", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "jQuery drop down" }
8509
<p><strong>Background</strong></p> <p>I'm converting Unicode text to <a href="http://en.wikipedia.org/wiki/TeX" rel="nofollow">TeX</a> for typesetting. In the input, I'm allowing simple fractions like ½ and ⅔ using single Unicode characters and complex fractions like ¹²³/₄₅₆ using superscripted and subscripted numerals. First I convert the simple fractions (½ becomes <code>\frac{1}{2}</code>) and superscripted and subscripted numerals (¹²³ becomes <code>$^{123}$</code> and ₄₅₆ becomes <code>$_{456}$</code>) using a character lookup table, then I make a second pass to collapse runs of numerals and combine numerator and denominator into a fraction (so ¹²³/₄₅₆ then becomes <code>\frac{123}{456}</code>). Finally, I make a third pass to insert a ⅙-em thin space between an integer and a fraction (so that, for example, 2¼ displays as 2 ¼).</p> <p><strong>Question(s)</strong></p> <p>Code works great, but I'm wondering how to simplify the regular expressions. There are three transformations.</p> <ul> <li>In the first transformation, is there a way to avoid the alternation operator (<code>|</code>) and simply match on either <code>\^</code> or <code>\_</code>? I don't see a way to do it using <code>([\^\_])</code> and <code>\1</code>.</li> <li>Also in the first transformation, is there a way to avoid the nested substitutions?</li> <li>Is there some completely other solution to this that would work even better? (By better I don't mean faster but easier to understand.)</li> </ul> <p>Here are the guts:</p> <pre><code># First collapse runs of superscripted and/or subscripted numerals. $text =~ s{ ( (?: \$ \^ [0-9] \$ ){2,} # Match superscripted numerals | (?: \$ \_ [0-9] \$ ){2,} # Match subscripted numerals ) }{ my $x = $1; $x =~ s{\$}{}g; # Remove '$'s $x =~ s{(?&lt;!^)[\^\_]}{}g; # Remove redundant '^'s and '_'s $x =~ s{^(.)(.*)$}{\$${1}{$2}\$}; # Wrap in '{}' and replace '$'. $x }xeg; # Now combine complete fractions. $text =~ s{ \$ \^ \{? ([0-9]+) \}? \$ # $1 = numerator (?: / | \x{2044} ) # Slash or Fraction Slash \$ \_ \{? ([0-9]+) \}? \$ # $2 = denominator }{ "\\frac{$1}{$2}" }xeg; # Finally, add a thin space between a whole number and a fraction. # (But do not add space between a whole number and an exponent.) $text =~ s{(?&lt;=[0-9])(?=\\frac\{.*?\}\{.*?\})}{\\,}g; </code></pre> <p>Note that this (probably) cannot be done in a single translation step, because it must also collapse superscripts like ¹²³ without an accompanying fraction, for if ¹²³ is left as <code>$^1$$^2$$$^3$</code> (instead of collapsing it to <code>$^{123}$</code>), then it will contain undesirable tiny spaces between the numerals.</p> <p>Additionally, it must convert 2¼ (add thin space) to 2 ¼ when it appears in the input using either the single character ¼ or the pair of superscript/subscript characters ¹ and ₄. Hence the very separate translation steps.</p> <p><strong>Test cases</strong></p> <blockquote> <p>Use ⅔ cup chopped garlic and 1½ cups chopped onion.<br> ➥ <code>Use \frac{2}{3} cup chopped garlic and 1\frac{1}{2} cups chopped onion.</code><br> ➥ <code>Use \frac{2}{3} cup chopped garlic and 1\,\frac{1}{2} cups chopped onion.</code></p> <p>This DeLorean DMC-12 runs on ²³⁹Pu and uses 1.21×10⁹ W.<br> ➥ <code>This DeLorean DMC-12 runs on $^2$$^3$$^9$Pu and uses 1.21$\times$10$^9$ W.</code><br> ➥ <code>This DeLorean DMC-12 runs on $^{239}$Pu and uses 1.21$\times$10$^9$ W.</code></p> <p>A googol is 10¹⁰⁰<br> ➥ <code>A googol is 10$^1$$^0$$^0$</code><br> ➥ <code>A googol is 10$^{100}$</code></p> <p>1 ns = ¹/₁₀₀₀ µs<br> ➥ <code>1 ns = $^1$/$_1$$_0$$_0$$_0$ µs</code><br> ➥ <code>1 ns = \frac{1}{1000} µs</code></p> <p>π ≅ ²²/₇ = 3¹/₇<br> ➥ <code>π ≅ $^2$$^2$/$_7$ = 3$^1$/$_7$</code><br> ➥ <code>π ≅ \frac{22}{7} = 3\,\frac{1}{7}</code></p> </blockquote> <p><strong>Complete working example</strong></p> <p>Here is the complete program, with test cases:</p> <pre><code>#!/usr/bin/perl -w use strict; use utf8; binmode STDOUT, ":utf8"; my $unicode_to_tex = { # Unicode TeX "\x{2070}" =&gt; "\$^0\$", # ⁰ (superscript 0) "\x{00B9}" =&gt; "\$^1\$", # ¹ (superscript 1) "\x{00B2}" =&gt; "\$^2\$", # ² (superscript 2) "\x{00B3}" =&gt; "\$^3\$", # ³ (superscript 3) "\x{2074}" =&gt; "\$^4\$", # ⁴ (superscript 4) "\x{2075}" =&gt; "\$^5\$", # ⁵ (superscript 5) "\x{2076}" =&gt; "\$^6\$", # ⁶ (superscript 6) "\x{2077}" =&gt; "\$^7\$", # ⁷ (superscript 7) "\x{2078}" =&gt; "\$^8\$", # ⁸ (superscript 8) "\x{2079}" =&gt; "\$^9\$", # ⁹ (superscript 9) "\x{2080}" =&gt; "\$_0\$", # ₀ (subscript 0) "\x{2081}" =&gt; "\$_1\$", # ₁ (subscript 1) "\x{2082}" =&gt; "\$_2\$", # ₂ (subscript 2) "\x{2083}" =&gt; "\$_3\$", # ₃ (subscript 3) "\x{2084}" =&gt; "\$_4\$", # ₄ (subscript 4) "\x{2085}" =&gt; "\$_5\$", # ₅ (subscript 5) "\x{2086}" =&gt; "\$_6\$", # ₆ (subscript 6) "\x{2087}" =&gt; "\$_7\$", # ₇ (subscript 7) "\x{2088}" =&gt; "\$_8\$", # ₈ (subscript 8) "\x{2089}" =&gt; "\$_9\$", # ₉ (subscript 9) "\x{00BD}" =&gt; "\\frac{1}{2}", # ½ (fraction one half) "\x{2153}" =&gt; "\\frac{1}{3}", # ⅓ (fraction one third) "\x{2154}" =&gt; "\\frac{2}{3}", # ⅔ (fraction two thirds) "\x{00BC}" =&gt; "\\frac{1}{4}", # ¼ (fraction one fourth) "\x{00BE}" =&gt; "\\frac{3}{4}", # ¾ (fraction three fourths) "\x{2155}" =&gt; "\\frac{1}{5}", # ⅕ (fraction one fifth) "\x{2156}" =&gt; "\\frac{2}{5}", # ⅖ (fraction two fifths) "\x{2157}" =&gt; "\\frac{3}{5}", # ⅗ (fraction three fifths) "\x{2158}" =&gt; "\\frac{4}{5}", # ⅘ (fraction four fifths) "\x{2159}" =&gt; "\\frac{1}{6}", # ⅙ (fraction one sixth) "\x{215A}" =&gt; "\\frac{5}{6}", # ⅚ (fraction five sixths) "\x{215B}" =&gt; "\\frac{1}{8}", # ⅛ (fraction one eighth) "\x{215C}" =&gt; "\\frac{3}{8}", # ⅜ (fraction three eighths) "\x{215D}" =&gt; "\\frac{5}{8}", # ⅝ (fraction five eighths) "\x{215E}" =&gt; "\\frac{7}{8}", # ⅞ (fraction seven eighths) "\x{00D7}" =&gt; "\$\\times\$", # × (multiplication sign) }; sub convert($) { my ($text) = @_; $text =~ s{(.)}{$unicode_to_tex-&gt;{$1}||$1}eg; return $text; } sub combine($) { my ($text) = @_; # First collapse runs of superscripted and/or subscripted numerals. $text =~ s{ ( (?: \$ \^ [0-9] \$ ){2,} # Match superscripted numerals | (?: \$ \_ [0-9] \$ ){2,} # Match subscripted numerals ) }{ my $x = $1; $x =~ s{\$}{}g; # Remove '$'s $x =~ s{(?&lt;!^)[\^\_]}{}g; # Remove redundant '^'s and '_'s $x =~ s{^(.)(.*)$}{\$${1}{$2}\$}; # Wrap in '{}' and replace '$'. $x }xeg; # Now combine complete fractions. $text =~ s{ \$ \^ \{? ([0-9]+) \}? \$ # $1 = numerator (?: / | \x{2044} ) # Slash or Fraction Slash \$ \_ \{? ([0-9]+) \}? \$ # $2 = denominator }{ "\\frac{$1}{$2}" }xeg; # Finally, add a thin space between a whole number and a fraction. # (But do not add space between a whole number and an exponent.) $text =~ s{(?&lt;=[0-9])(?=\\frac\{.*?\}\{.*?\})}{\\,}g; return $text; } while (defined(my $text = &lt;DATA&gt;)) { print $text; $text = convert($text); print $text; $text = combine($text); print $text; print "\n"; } __DATA__ Use ⅔ cup chopped garlic and 1½ cups chopped onion. This DeLorean DMC-12 runs on ²³⁹Pu and uses 1.21×10⁹ W. A googol is 10¹⁰⁰ 1 ns = ¹/₁₀₀₀ µs π ≅ ²²/₇ = 3¹/₇ </code></pre>
[]
[ { "body": "<p><em>(Disclaimer: I don't know perl, just regular expressions)</em></p>\n\n<h3>First question</h3>\n\n<blockquote>\n <p>is there a way to avoid the alternation operator (<code>|</code>) and simply match on either <code>\\^</code> or <code>\\_</code>?</p>\n</blockquote>\n\n<pre><code> (?: \\$ \\^ [0-9] \\$ ){2,} # Match superscripted numerals\n | (?: \\$ \\_ [0-9] \\$ ){2,} # Match subscripted numerals\n</code></pre>\n\n<p>Try doing this:</p>\n\n<pre><code> (?: \\$ [_^] [0-9] \\$ ){2,} # Match (super|sub)scripted numerals\n</code></pre>\n\n<p><em>(edit: this above regex actually wouldn't work for this case, see comments below for another suggestion)</em></p>\n\n<p>The item <code>[_^]</code> is a Character Class - same as <code>[0-9]</code>. Perl syntax might require the escape characters, in which case it would look like <code>[\\^\\_]</code> - but generally in regexes you don't need to escape inside a character class. As you mentioned, in this case if the <code>^</code> character is first then it is a negated character class - and it tends to be up to the developer (my preference is to escape only when necessary).</p>\n\n<p>Here's some more information on character classes: <a href=\"http://www.regular-expressions.info/charclass.html\" rel=\"nofollow\">http://www.regular-expressions.info/charclass.html</a></p>\n\n<h3>Second question</h3>\n\n<blockquote>\n <p>in the first transformation, is there a way to avoid the nested substitutions?</p>\n</blockquote>\n\n<p>I assume you mean this:</p>\n\n<pre><code>$x =~ s{\\$}{}g; # Remove '$'s\n$x =~ s{(?&lt;!^)[\\^\\_]}{}g; # Remove redundant '^'s and '_'s\n$x =~ s{^(.)(.*)$}{\\$${1}{$2}\\$}; # Wrap in '{}' and replace '$'.\n</code></pre>\n\n<p>With regular expressions, I've found that the most compact ones aren't necessarily the easiest ones to read. The way you have it split up here and documented seems helpful if it doesn't cause a performance hit.\nThat said, you could probably combine the first two lines like this:</p>\n\n<pre><code>$x =~ s{\\$|(?&lt;!^)[_^]}{}g; # Remove '$'s and redundant ^ and _ chars\n</code></pre>\n\n<h3>Third question</h3>\n\n<blockquote>\n <p>Is there some completely other solution to this that would work even better?</p>\n</blockquote>\n\n<p>I can only think of one way to do part of this differently... \nIn the beginning, it looks like you can safely (maybe?) hunt down and kill ALL <code>$$^</code> instances, e.g.:</p>\n\n<blockquote>\n <p><code>This DeLorean DMC-12 runs on $^2$$^3$$^9$Pu and uses 1.21$\\times$10$^9$ W.</code>\n <code>This DeLorean DMC-12 runs on $^239$Pu and uses 1.21$\\times$10$^9$ W.</code></p>\n</blockquote>\n\n<p>Then you could search for instances of <code>(&lt;?=\\$^)(.*)(?=\\$)</code> and wrap those with the <code>{}</code> characters:</p>\n\n<blockquote>\n <p><code>This DeLorean DMC-12 runs on $^{239}$Pu and uses 1.21$\\times$10$^9$ W.</code></p>\n</blockquote>\n\n<p>You'll have to make the best judgement as to whether or not <code>$$^</code> occurs validly another way, however, in which case this wouldn't help.</p>\n\n<p>You could also write it as a humongous <code>sed</code> command if you're looking to spend a lot of time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T13:49:35.407", "Id": "13337", "Score": "0", "body": "Thanks, this helps. The reason I didn't write `[\\^\\_]` in the first case (the alternation) is because it needs to collapse runs of the same type only. The problem with `[\\^\\_]` in that case is that it would capture `$^2$$_1$` and then munge it to `$^{21}$` when it should be left as `$^2$$_1$`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T13:51:25.500", "Id": "13338", "Score": "0", "body": "p.s. In Perl, the `^` has to be escaped in `[\\^\\_]`, otherwise the `^` in that context means the negation of the character class. That is, `[^_]` means all characters except `_`. One could write `[_^]` without problems, but I like to avoid ordering issues so I use backslash-escapes liberally." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T22:08:56.723", "Id": "13490", "Score": "0", "body": "Ah yes, forgot about the negated character class, good point (I'll edit that). I'm a bit confused about your first comment though, since `(?: \\$ \\^ [0-9] \\$ ){2,}|(?: \\$ \\_ [0-9] \\$ ){2,}` is logically equivalent to `(?: \\$ [_^] [0-9] \\$ ){2,}`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T22:20:38.827", "Id": "13492", "Score": "0", "body": "They're not quite logically equivalent. The first version will only match ^1^2^3^4 or _1_2_3_4 (which is what I want), while the second version will match ^1_2^3_4 (something that I don't want)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T22:32:35.843", "Id": "13495", "Score": "0", "body": "OK, I see what you're saying: you're definitely right. In this case you could technically use backreferences like this: `(\\$[_^])\\d\\$(?:\\1\\d\\$)+` but then you're not really making it easier to read later :) (not to mention you'd have to be careful with the capturing group that I added)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T06:29:24.950", "Id": "8532", "ParentId": "8510", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T17:16:22.247", "Id": "8510", "Score": "3", "Tags": [ "regex", "perl", "unicode", "tex" ], "Title": "Simplify regular expression? (Converting Unicode fractions to TeX)" }
8510
<p>I'm new to Rails/Ruby and I would like to get feedback on my little <code>ApplicationController</code> which is able to detect the visitor's language. I'm especially interested in optimizations on the control structure in the <code>set_locale</code> method (2 nested <code>if</code> statements and 3 assignments to one variable). I'm using the <a href="https://github.com/iain/http_accept_language" rel="nofollow">http_accept_language</a> gem.</p> <pre><code>class ApplicationController &lt; ActionController::Base AVAILABLE_LANGUAGES = %w{de en} before_filter :set_locale protect_from_forgery def set_locale if params[:locale].nil? if preferred_language = request.preferred_language_from(AVAILABLE_LANGUAGES) I18n.locale = preferred_language else I18n.locale = I18n.default_locale end else I18n.locale = params[:locale] end end def default_url_options(options={}) logger.debug "default_url_options is passed options: #{options.inspect}\n" { :locale =&gt; I18n.locale } end end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-30T17:02:54.293", "Id": "143274", "Score": "0", "body": "Just a note: In Ruby, an empty string is `true`. Checking for `params[:local].empty?` is better than `nil?` since `nil?` returns false for empty strings, and the locale can be an empty string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-30T17:07:47.737", "Id": "143276", "Score": "0", "body": "@Mohamad Completely agree with you on a technical basis, but I think you need to reword your first sentence because ```\"\" == true => false```" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-30T17:24:17.043", "Id": "143281", "Score": "0", "body": "Sorry, I meant to say an empty string would **evaluate** to true, and not that it equals or returns true. Thanks for pointing that out. For exmaple: `{foo: ''}[:foo].nil?\n => false`" } ]
[ { "body": "<p>You can do it in an \"one-liner\". Although one-liners are frequently associated with less readability, I honestly believe this is <strong>not</strong> the case. Something like this would work:</p>\n\n<pre><code>I18n.locale = params[:locale] || \n request.preferred_language_from(AVAILABLE_LANGUAGES) ||\n I18n.default_locale\n</code></pre>\n\n<p>I see a few advantages in this solution:</p>\n\n<ul>\n<li>Your code will be a bit cleaner, since you can collapse 9 lines of code filled with <code>if</code>/<code>else</code> conditions into 3 (or 1, if you don't break the line);</li>\n<li>You won't need to allocate <code>preferred_language</code> in case params[:locale] is <code>nil</code>;</li>\n<li>And the biggest advantage of them all: clarity. The precedence of the options is much more explicit.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T08:07:11.363", "Id": "13325", "Score": "0", "body": "This is so simple and great, how could I not come up with it in the firstplace? Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T05:55:36.147", "Id": "8529", "ParentId": "8511", "Score": "1" } }, { "body": "<p>I like the one liner from goncalossilva, but I would probably add a check to the first clause. </p>\n\n<pre><code>def valid_locale(locale)\n locale if AVAILABLE_LANGUAGES.include?(locale)\nend\n\n\nI18n.locale = valid_locale(params[:locale]) || \n request.preferred_language_from(AVAILABLE_LANGUAGES) ||\n I18n.default_locale\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T12:36:55.060", "Id": "13332", "Score": "0", "body": "Good catch there, I tought Rails would fallback to the default language if the locale wasn't found, as a quick test showed I was wrong!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T11:10:08.333", "Id": "8541", "ParentId": "8511", "Score": "1" } } ]
{ "AcceptedAnswerId": "8529", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T18:14:07.940", "Id": "8511", "Score": "2", "Tags": [ "beginner", "ruby", "ruby-on-rails", "i18n" ], "Title": "Small: Setting locale" }
8511
Internationalization, also known as i18n, refers to the techniques and tools to make the software change its behavior based on the country or culture of the user running it. This is a matter not only of changing the language which the software presents (e.g. in its user interface), but of changing the date format, the orientation of the text, the numeric format, and other aspects of its behavior to reflect the culture.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T19:22:19.560", "Id": "8516", "Score": "0", "Tags": null, "Title": null }
8516
<h3>More readable way to do this?</h3> <pre><code>renderHtmlTable(function(tableItems) { var tableArray,_i,item,_len; tableArray = ['&lt;table id = sampleTable &gt;&lt;thead&gt;&lt;tr&gt;' + '&lt;th&gt;Header 1&lt;/th&gt;' + '&lt;th&gt;Header 2&lt;/th&gt;' + '&lt;th&gt;Header 3&lt;/th&gt;' + '&lt;th&gt;Header 4&lt;/th&gt;' + '&lt;/tr&gt;&lt;/thead&gt;']; for (_i = 0, _len = tableItems.length; _i &lt; _len; _i++) { item = tableItems[_i]; tableArray.push('&lt;tr&gt;&lt;td&gt;' + item.foo + '&lt;/td&gt;' + '&lt;td&gt;' + item.bar + '&lt;/td&gt;' + '&lt;td&gt;' + item.baz + '&lt;/td&gt;' + '&lt;td&gt;' + item.qux + '&lt;/td&gt;&lt;/tr&gt;') } tableArray.push('&lt;/table&gt;'); ($('#TableDiv')).html(function() { return lessonArray.join(&quot;&quot;); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T14:56:33.800", "Id": "62858", "Score": "0", "body": "Could also use DataTables, a plugin for jQuery. Datatables.net" } ]
[ { "body": "<p>Use mustache.js! It's a js templating engine which will point you in the right direction :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T06:59:06.977", "Id": "8535", "ParentId": "8517", "Score": "4" } }, { "body": "<p>this seems a little bit more readable (at least to me :)</p>\n\n<pre><code> var table = $(\"&lt;table&gt;\").attr(\"id\", \"sampleTable \")\n .append($(\"&lt;thead&gt;\")\n .append($(\"&lt;tr&gt;\")\n .append($(\"&lt;th&gt;\").text(\"Header 1\"))\n .append($(\"&lt;th&gt;\").text(\"Header 2\"))\n .append($(\"&lt;th&gt;\").text(\"Header 3\"))\n .append($(\"&lt;th&gt;\").text(\"Header 4\"))\n )\n );\n\n for (var i = 0; i &lt; 10; i++) {\n table.append($(\"&lt;tr&gt;\")\n .append($(\"&lt;td&gt;\").text(\"foo\"))\n .append($(\"&lt;td&gt;\").text(\"bar\"))\n .append($(\"&lt;td&gt;\").text(\"foo\"))\n .append($(\"&lt;td&gt;\").text(\"bar\"))\n );\n }\n table.appendTo(\"body\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:36:36.043", "Id": "8558", "ParentId": "8517", "Score": "3" } } ]
{ "AcceptedAnswerId": "8558", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:15:44.270", "Id": "8517", "Score": "3", "Tags": [ "javascript", "jquery", "html" ], "Title": "Building an HTML table using JavaScript" }
8517
<p>Today, I do not have a coding question, but just a general question about a piece of code that I have written.</p> <p>As you guys can see, I run the following JavaScript code every ten seconds. I tried to run it every second, but it started eating up the CPU of my hosting company like crazy. With it running every ten seconds, I have no problems when there are a few users online, but have not massively tested this with a lot of people online at once.</p> <p>Let's say that I have 100 users online at a time; do you guys think that running this code once every ten seconds would flood the server and cause it to run slowly? Should I keep it at 10 seconds, or maybe push it back to, let's say, 20 seconds? Or maybe even reduce it to 5 seconds? The shorter the time here, the better; I just do not want to be running too many processes at once and flood my server.</p> <p>Here it is:</p> <pre><code>&lt;script language='javascript' type='text/javascript'&gt; setInterval( function() { $('#clicktoenteraconversation').load('getnewonlinefriends.php'); //$('#friendstochatwith').load('checkloggedinchat.php?username=&lt;?php echo $username; ?&gt;&amp;otherchatuser=&lt;?php echo $otherchatuser; ?&gt;'); }, 10000); &lt;/script&gt; </code></pre> <p>Here is getnewonlinefriends.php:</p> <pre><code>&lt;?php if($username) { $resettime = time(); mysql_query("UPDATE loggedin SET time = '$resettime' WHERE username='$username'"); echo "&lt;div id='showfriendsforchat'&gt;&lt;div id='friendstochatwithcontainer'&gt;&lt;div id='friendstochatwith'&gt;"; $construct = "SELECT * FROM acceptedfriends WHERE profilename='$username' ORDER BY id DESC"; $run = mysql_query($construct); while ($runrows = mysql_fetch_assoc($run)) { $users = $runrows['username']; $location = $runrows['chatpictures']; $image = "&lt;img src='$location' style='width:25px; height:20px;' /&gt;"; $readmessagequery = mysql_query("SELECT * FROM conversation WHERE yourusername='$username' and theirusername='$users' and readmessages='0'"); $numrowsreadmessagequery = mysql_num_rows($readmessagequery); if ($numrowsreadmessagequery &gt; 0) { $echonumrowsreadmessagequery = '&lt;div id="numberofunreadmessages"&gt;&lt;div style="padding:1px; padding-left:4px; padding-right:4px;"&gt;'.$numrowsreadmessagequery.'&lt;/div&gt;&lt;/div&gt;'; echo " &lt;style&gt; #clicktoenteraconversation{ background: #C67171; /* Old browsers */ background: -moz-linear-gradient(top, #DEDEDE 0%, #C67171 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#DEDEDE), color-stop(100%,#C67171)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #DEDEDE 0%,#C67171 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #DEDEDE 0%,#C67171 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #DEDEDE 0%,#C67171 100%); /* IE10+ */ background: linear-gradient(top, #DEDEDE 0%,#C67171 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#DEDEDE', endColorstr='#C67171',GradientType=0 ); /* IE6-9 */ } } &lt;/style&gt; "; } $subtractlogintime = time() - 600; $data4 = mysql_query("SELECT * FROM loggedin WHERE username='$users' and time &gt; '$subtractlogintime'"); if (mysql_num_rows($data4)==1) { $loggedninpicture2 = '&lt;img src="loggedin.png"&gt;'; $loggedintally = $loggedintally + 1; } else { $loggedninpicture2 = ''; } echo '&lt;div id="hoverfriendstochatwith" onclick="showchat(\'' . $users . '\')"&gt;&lt;table&gt;&lt;tr&gt;&lt;td&gt;'.$image.'&lt;/td&gt;&lt;td&gt;&lt;div style="margin-left:5px;"&gt;'.$users.'&lt;/div&gt;&lt;/td&gt;&lt;td&gt;'.$echonumrowsreadmessagequery.'&lt;/td&gt;&lt;td style="margin-left:5px;"&gt;&lt;div style="margin-bottom:1px;"&gt;'.$loggedninpicture2.'&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/div&gt;'; } echo "&lt;/div&gt;&lt;div id='clicktoenteraconversation2' onclick='hideshowfriendstab()'&gt;Close&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;"; echo "&lt;div id='chatwithafriendhere'&gt;&lt;/div&gt;"; if ($loggedintally &gt; 0) { $loggedintally = '&lt;img src="loggedin.png"&gt; Chat ('.$loggedintally.')'; } else { $loggedintally = '&lt;img src="loggedin.png"&gt; Chat (0)'; } $readmessagequery = mysql_query("SELECT * FROM conversation WHERE yourusername='$username' and readmessages='0'"); $numrowsreadmessagequery = mysql_num_rows($readmessagequery); if ($numrowsreadmessagequery &gt; 0) { echo "&lt;img src='mostviewedpicture.png' style='height:16px; width:30px; float:left; margin-top:1px; margin-left:5px;'/&gt;&lt;div style='font-size:.8em; float:left; margin-left:2px;'&gt;".$loggedintally."&lt;/div&gt;&lt;div id='numberofunreadmessages' style='margin-left:5px; height:14px; margin-top:2px; margin-bottom:2px;'&gt;&lt;div style='margin-left:4px; margin-right:4px; min-width:6px; margin-top:-3px;'&gt;".$numrowsreadmessagequery."&lt;/div&gt;&lt;/div&gt;"; } else { echo "&lt;img src='mostviewedpicture.png' style='height:16px; width:30px; float:left; margin-top:1px; margin-left:5px;'/&gt;&lt;div style='font-size:.8em; float:left; margin-left:2px;'&gt;".$loggedintally."&lt;/div&gt;"; } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:18:48.650", "Id": "13312", "Score": "2", "body": "**Warning** your code seems to be susceptible to sql injection attacks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:19:25.473", "Id": "13313", "Score": "4", "body": "I'd separate the static parts (eg CSS) from your code, and implement caching. An interval of 10 seconds is already generous. You often don't need updates that fast." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:21:50.133", "Id": "13314", "Score": "0", "body": "Where is the flaw in the code that make it susceptible to sql injection? Please point this out as it would be very helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:24:08.763", "Id": "13315", "Score": "0", "body": "@eggo `$username` maybe isn't validated/escaped." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:24:09.927", "Id": "13316", "Score": "0", "body": "For this bit of code, it needs to be updated as frequently as possible without overloading the server." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:27:08.397", "Id": "13317", "Score": "0", "body": "@DanielA.White that is true, other than that, the turn around time of the script may be long since there is an update and sort on the queries that might be eating up additional resources specially when there are not enough indexes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T17:11:51.350", "Id": "14060", "Score": "0", "body": "Please, please use some sort of template system!! Don't mesh together php with html/css/javascript. *cough*Here is my template system https://github.com/AntonioCS/AcsView *cough*" } ]
[ { "body": "<p>If you want to protect your server then your server should be the one dictating the interval.</p>\n\n<p>Since any JavaScript can be intercepted and modified you can't rely on <code>setInterval</code>.</p>\n\n<p>First you need some way to measure load on your server. A simple approach would be to count the number of requests per minute.</p>\n\n<p>Then, before you do any work, have your script 'wait' a while before doing anything. (<code>sleep</code> or <code>usleep</code> in PHP).</p>\n\n<p>If the load goes up, increase the sleep time.</p>\n\n<p>Then, on the client side you will need to account for the increase in request time. So rather than using a <code>setInterval</code> you should start a new timer once the request has been completed.</p>\n\n<pre><code>function call_to_server() {\n $('#clicktoenteraconversation').load('getnewonlinefriends.php', function () {\n setTimeout(call_to_server, 1000 /* 1 second */ );\n });\n}\ncall_to_server();\n</code></pre>\n\n<p>This is the simple example. But if you leave this running for too long JavaScript will complain about nesting depth. You can find solutions for this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:28:07.570", "Id": "8519", "ParentId": "8518", "Score": "0" } }, { "body": "<p>As some other users have suggested in comments, I recommend separating the CSS from what is returned by the PHP script and using caching to reduce the number of queries you need to make.</p>\n\n<p>You say that the more often this is updated the better - with caching your server will be able to respond to many, many times more requests than querying the database every time. It will also be easier to expand to support more users later too.</p>\n\n<p>The best way to implement caching is to split off the queries into functions and apply logic to check if a cachekey exists (probably using memcached for PHP). If it does then return it, else query the database and set it. You will have to be sure that any time data is updated/inserted into the database, though, that the cache is updated to ensure that they remain in sync.</p>\n\n<p>For example:</p>\n\n<pre><code>function get_user_session($UserID)\n{\n $UserSessions = $Cache-&gt;get_value('users_sessions_'.$UserID);\n if(!is_array($UserSessions)) {\n $DB-&gt;query(\"SELECT\n SessionID,\n Browser,\n OperatingSystem,\n IP,\n LastUpdate\n FROM users_sessions\n WHERE UserID='$UserID'\n ORDER BY LastUpdate DESC\");\n $UserSessions = $DB-&gt;to_array('SessionID',MYSQLI_ASSOC);\n $Cache-&gt;cache_value('users_sessions_'.$UserID, $UserSessions, 0);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:58:57.760", "Id": "13318", "Score": "0", "body": "Thanks, it looks like this would solve my problem, except for the fact that I just spent quite a bit of time trying to fit this to the code that I already have an have no idea how to do it..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T09:40:01.680", "Id": "13327", "Score": "0", "body": "In my code I'm using two classes, one for MySQL and another for Memcached. You need to get at least the Memcached class to use it like I have and I do recommend you get a class to interface with MySQL too, as mysql_query() is long deprecated!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:30:01.167", "Id": "8520", "ParentId": "8518", "Score": "1" } } ]
{ "AcceptedAnswerId": "8520", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:17:14.813", "Id": "8518", "Score": "2", "Tags": [ "php", "javascript" ], "Title": "setInterval loading data from server every 10 seconds" }
8518
<p>I want to do insert sort in a linked list without using dummy nodes. </p> <p>This is my code. How can this be improved? Any input is appreciated. </p> <pre><code>public static Node insertSort(Node node){ Node sortedList = null; while(node != null){ Node current = node; node = node.next; Node x; Node previous = null; for(x = sortedList; x != null; x = x.next){ if(current.value &lt; x.value){ break; } previous = x; } if(previous == null){ current.next = sortedList; sortedList = current; } else{ current.next = previous.next; previous.next = current; } } return sortedList; } </code></pre>
[]
[ { "body": "<p>Algorithmically, your implementation seems fine. One improvement would be to initialize the sortedList to the first node right away. This necessitates some error checking up front, which I think is better style anyway.</p>\n\n<p>I would also run a check for the current node being the new sorted head first. That way I can automatically assume that I'm inserting after the search position. That allows elimination of the <code>previous</code> variable.</p>\n\n<p>But this is all stylistic stuff to make the logic flow easier to understand. As I said, I think your implementation functions perfectly well.</p>\n\n<pre><code>public static Node insertNode(Node node) {\n if (node == null)\n return null;\n\n // Make the first node the start of the sorted list.\n Node sortedList = node;\n node = node.next;\n sortedList.next = null;\n\n while(node != null) {\n // Advance the nodes.\n final Node current = node;\n node = node.next;\n\n // Find where current belongs.\n if (current.value &lt; sortedList.value) {\n // Current is new sorted head.\n current.next = sortedList;\n sortedList = current;\n } else {\n // Search list for correct position of current.\n Node search = sortedList;\n while(search.next != null &amp;&amp; current.value &gt; search.next.value)\n search = search.next;\n\n // current goes after search.\n current.next = search.next;\n search.next = current;\n }\n }\n\n return sortedList;\n}\n</code></pre>\n\n<p>See it run in JavaScript: <a href=\"http://jsfiddle.net/2LDGD/2/\" rel=\"nofollow\">http://jsfiddle.net/2LDGD/2/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T03:48:42.247", "Id": "8527", "ParentId": "8521", "Score": "2" } }, { "body": "<p>well sry, i dont have much time to read your code but one of the best ways i used in such problems is to create a \"swap function\", that uses in every sort algorithm, then you can implement every algorithm you want and change the swap function with yours and of course custom traverse commands</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:32:05.100", "Id": "8556", "ParentId": "8521", "Score": "-2" } } ]
{ "AcceptedAnswerId": "8527", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:41:05.847", "Id": "8521", "Score": "7", "Tags": [ "java", "algorithm", "sorting", "insertion-sort" ], "Title": "Insert sort on a linked list" }
8521
<p>Is there a more succinct way to write code like this that has a lot of sharing between branches of the case statement?</p> <p>(This is the main part of my solution to one of the Round 1 problems of the Facebook Hacker Cup 2012. The round is over.)</p> <pre><code>type Memoizable a = a -&gt; a recoveries :: Int -&gt; Memoizable (String -&gt; Int) recoveries m = go where go self ('0':_) = 0 go self [] = 1 go self ss = flip rem 0xfaceb00c $ case analysis ss of HasMany | cValid -&gt; cCase + bCase + aCase | bValid -&gt; bCase + aCase | aValid -&gt; aCase Has2 | bValid -&gt; bCase + aCase | aValid -&gt; aCase Has1 | aValid -&gt; aCase _ | otherwise -&gt; 0 where a = digitToInt (first ss) b = a * 10 + digitToInt (second ss) c = b * 10 + digitToInt (third ss) aValid = a &lt;= m bValid = b &lt;= m cValid = c &lt;= m aCase = self (drop 1 ss) bCase = self (drop 2 ss) cCase = self (drop 3 ss) -- not to be confused with functions of same name from Control.Arrow first (x:_) = x second (_:x:_) = x third (_:_:x:_) = x data Analysis = Empty | Has1 | Has2 | HasMany -- a dumb little function to help with safety and sharing analysis :: [a] -&gt; Analysis analysis [] = Empty analysis [_] = Has1 analysis [_,_] = Has2 analysis _ = HasMany </code></pre>
[]
[ { "body": "<p>Hm, why did you write <code>go</code> as a separate function? It is - as you state - the same as <code>recoveries</code>, why the local definition?</p>\n\n<p>For making it more succinct, I think it's easiest to have an intermediate data structure that carries both pieces of information you seek in the <code>case</code>: Whether there are enough digits and what number the digits so far would form.</p>\n\n<p>The first data structure that comes to mind is a list of numbers - we just need to construct it. In this case, <code>scanl</code> is our friend:</p>\n\n<pre><code>import Data.List (scanl)\nimport Data.Char (digitToInt)\n\ntype Memoizable a = a -&gt; a\n\nrecoveries :: Int -&gt; Memoizable (String -&gt; Int)\nrecoveries _ _ ('0':_) = 0\nrecoveries _ _ [] = 1\nrecoveries m self ss = result `rem` 0xfaceb00c\n where result = case tail (scanl addDigit 0 ss) of\n (_:_:c:_) | c &lt;= m -&gt; aCase+bCase+cCase\n (_:b:_) | b &lt;= m -&gt; aCase+bCase\n (a:_) | a &lt;= m -&gt; aCase\n _ -&gt; 0\n addDigit x c = x*10 + digitToInt c\n aCase = self (drop 1 ss)\n bCase = self (drop 2 ss)\n cCase = self (drop 3 ss)\n</code></pre>\n\n<p>Unless I've made a mistake (can't test), this should do the same as your code, and now we can write everything cleanly using pattern matches and a few guards on the intermediate list.</p>\n\n<p>You could get rid of <code>aCase</code>, <code>bCase</code> and <code>cCase</code> as well if you would <code>zip</code> the result of <code>scanl</code> with <code>tails ss</code>. But while this is more general, I felt it would have made the code harder to understand, so I left it like this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T13:28:35.780", "Id": "8544", "ParentId": "8522", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T21:51:56.973", "Id": "8522", "Score": "5", "Tags": [ "haskell" ], "Title": "Safety, sharing, and laziness" }
8522
<p>Migrating to using prepared statements and would like some feedback on CRUD modules, concerned with syntax (usage and DRY) and speed:</p> <p><strong>START:</strong></p> <pre><code>&lt;?php // This page is for deleting a user record. // This page is accessed through view_users.php. $page_title = 'Delete a User'; include ('includes/header.html'); echo '&lt;h1&gt;Delete a User&lt;/h1&gt;'; // Check for a valid user ID, through GET or POST: if ( (isset($_GET['id'])) &amp;&amp; (is_numeric($_GET['id'])) ) { // From view_users.php $id = $_GET['id']; } elseif ( (isset($_POST['id'])) &amp;&amp; (is_numeric($_POST['id'])) ) { // Form submission. $id = $_POST['id']; } else { // No valid ID, kill the script. echo '&lt;p class="error"&gt;This page has been accessed in error.&lt;/p&gt;'; include ('includes/footer.html'); exit(); } require_once ('../mysqli_connect.php'); // Check if the form has been submitted: if (isset($_POST['submitted'])) { if ($_POST['sure'] == 'Yes') { // Delete the record. // Make the query: $q = "DELETE FROM users WHERE user_id=$id LIMIT 1"; $r = @mysqli_query ($dbc, $q); if (mysqli_affected_rows($dbc) == 1) { // If it ran OK. // Print a message: echo '&lt;p&gt;The user has been deleted.&lt;/p&gt;'; } else { // If the query did not run OK. echo '&lt;p class="error"&gt;The user could not be deleted due to a system error.&lt;/p&gt;'; // Public message. echo '&lt;p&gt;' . mysqli_error($dbc) . '&lt;br /&gt;Query: ' . $q . '&lt;/p&gt;'; // Debugging message. } } else { // No confirmation of deletion. echo '&lt;p&gt;The user has NOT been deleted.&lt;/p&gt;'; } } else { // Show the form. // Retrieve the user's information: $q = "SELECT CONCAT(last_name, ', ', first_name) FROM users WHERE user_id=$id"; $r = @mysqli_query ($dbc, $q); if (mysqli_num_rows($r) == 1) { // Valid user ID, show the form. // Get the user's information: $row = mysqli_fetch_array ($r, MYSQLI_NUM); // Create the form: echo '&lt;form action="delete_user.php" method="post"&gt; &lt;h3&gt;Name: ' . $row[0] . '&lt;/h3&gt; &lt;p&gt;Are you sure you want to delete this user?&lt;br /&gt; &lt;input type="radio" name="sure" value="Yes" /&gt; Yes &lt;input type="radio" name="sure" value="No" checked="checked" /&gt; No&lt;/p&gt; &lt;p&gt;&lt;input type="submit" name="submit" value="Submit" /&gt;&lt;/p&gt; &lt;input type="hidden" name="submitted" value="TRUE" /&gt; &lt;input type="hidden" name="id" value="' . $id . '" /&gt; &lt;/form&gt;'; } else { // Not a valid user ID. echo '&lt;p class="error"&gt;This page has been accessed in error.&lt;/p&gt;'; } } // End of the main submission conditional. mysqli_close($dbc); include ('includes/footer.html'); ?&gt; </code></pre> <p><strong>DELETE: PREPARED STATEMENTS:</strong></p> <pre><code>&lt;?php // This page is for deleting a user record. // This page is accessed through view_users.php. $page_title = 'Delete a User'; include ('includes/header.html'); echo '&lt;h1&gt;Delete a User&lt;/h1&gt;'; // Check for a valid user ID, through GET or POST: if ( (isset($_GET['id'])) &amp;&amp; (is_numeric($_GET['id'])) ) { // From view_users.php $id = $_GET['id']; } elseif ( (isset($_POST['id'])) &amp;&amp; (is_numeric($_POST['id'])) ) { // Form submission. $id = $_POST['id']; } else { // No valid ID, kill the script. echo '&lt;p class="error"&gt;This page has been accessed in error.&lt;/p&gt;'; include ('includes/footer.html'); exit(); } require_once ('../mysqli_connect.php'); // Check if the form has been submitted: if (isset($_POST['submitted'])) { if ($_POST['sure'] == 'Yes') { // Delete the record. // Make the query: $stmt = $dbc-&gt;prepare("DELETE FROM users WHERE user_id=$id LIMIT 1"); $stmt-&gt;bind_param('i', $id); $stmt-&gt;execute(); if ($stmt-&gt;affected_rows == 1) { // If it ran OK. // Print a message: echo '&lt;p&gt;The user has been deleted.&lt;/p&gt;'; } else { // If the query did not run OK. echo '&lt;p class="error"&gt;The user could not be deleted due to a system error.&lt;/p&gt;'; // Public message. echo '&lt;p&gt;' . mysqli_connect_errno() . '&lt;br /&gt;Query: ' . $stmt-&gt;error . '&lt;/p&gt;'; // Debugging message. } } else { // No confirmation of deletion. echo '&lt;p&gt;The user has NOT been deleted.&lt;/p&gt;'; } } else { // Show the form. // Retrieve the user's information: //$query = "SELECT last_name, first_name, FROM users WHERE user_id=$id"; $stmt = $dbc-&gt;prepare("SELECT CONCAT(last_name, ', ', first_name) AS name FROM users WHERE user_id=$id"); $stmt-&gt;execute(); $stmt-&gt;bind_result($name); $stmt-&gt;store_result(); $num = $stmt-&gt;num_rows; if ($stmt-&gt;num_rows == 1) { // Valid user ID, show the form. // Get the user's information: $stmt-&gt;fetch(); //print_r($row); // Create the form: echo '&lt;form action="delete_user.php" method="post"&gt; &lt;h3&gt;Name: ' . $name . '&lt;/h3&gt; &lt;p&gt;Are you sure you want to delete this user?&lt;br /&gt; &lt;input type="radio" name="sure" value="Yes" /&gt; Yes &lt;input type="radio" name="sure" value="No" checked="checked" /&gt; No&lt;/p&gt; &lt;p&gt;&lt;input type="submit" name="submit" value="Submit" /&gt;&lt;/p&gt; &lt;input type="hidden" name="submitted" value="TRUE" /&gt; &lt;input type="hidden" name="id" value="' . $id . '" /&gt; &lt;/form&gt;'; } else { // Not a valid user ID. echo '&lt;p class="error"&gt;This page has been accessed in error.&lt;/p&gt;'; } } // End of the main submission conditional. //mysqli_close($dbc); $dbc-&gt;close(); include ('includes/footer.html'); ?&gt; </code></pre> <p><strong>VIEW: PREPARED STATEMENTS</strong></p> <pre><code>&lt;?php #bd - view_users.php #1 // This script retrieves all the records from the users table. $page_title = 'View the Current Users'; include ('includes/header.html'); // Page header: echo '&lt;h1&gt;Registered Users&lt;/h1&gt;'; require_once ('../mysqli_connect.php'); // Connect to the db. // Make the query: $stmt = $dbc-&gt;prepare("SELECT last_name, first_name, user_id, DATE_FORMAT(registration_date, '%M %d, %Y') AS dr FROM users ORDER BY registration_date ASC"); $stmt-&gt;execute(); $stmt-&gt;bind_result($last_name,$first_name,$user_id, $dr); $stmt-&gt;store_result(); $num = $stmt-&gt;num_rows; if($num &gt; 0){ // Print how many users there are: echo "&lt;p&gt;There are currently $num registered users.&lt;/p&gt;\n"; // Table header. echo '&lt;table align="center" cellspacing="0" cellpadding="5" width="75%"&gt; &lt;tr&gt; &lt;td align="left"&gt;&lt;b&gt;Edit&lt;/b&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;b&gt;Delete&lt;/b&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;b&gt;Last Name&lt;/b&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;b&gt;First Name&lt;/b&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;b&gt;Date Registered&lt;/b&gt;&lt;/td&gt; &lt;/tr&gt; '; while($row = $stmt-&gt;fetch()) : echo '&lt;tr&gt; &lt;td align="left"&gt;&lt;a href="edit_user.php?id=' . $user_id . '"&gt;Edit&lt;/a&gt;&lt;/td&gt; &lt;td align="left"&gt;&lt;a href="delete_user.php?id=' . $user_id .'"&gt;Delete&lt;/a&gt;&lt;/td&gt; &lt;td align="left"&gt;' . $last_name. '&lt;/td&gt; &lt;td align="left"&gt;' . $first_name . '&lt;/td&gt; &lt;td align="left"&gt;' . $dr . '&lt;/td&gt; &lt;/tr&gt;'; endwhile; echo '&lt;/table&gt;'; // Close the table. $stmt-&gt;free_result(); } else { echo '&lt;p class="error"&gt;There are currently no registered users.&lt;/p&gt;'; } $dbc-&gt;close(); include ('includes/footer.html'); ?&gt; </code></pre>
[]
[ { "body": "<p>First, I'd like to say it is good that you are swapping over to use prepared statements. This is definitely the way to go. However, you aren't using them correctly in your code. If you read the <a href=\"http://www.php.net/manual/en/mysqli.prepare.php\" rel=\"nofollow\">documentation on <code>mysqli::prepare()</code></a> you'll notice that the place holder for parameters should be a <code>?</code> whereas you are using the actual variable you want to put in. While this statement may execute correctly it is <em>not</em> a prepared statement and is prone to SQL Injection. The user input is being inserted directly into the query and you are not gaining the benefit of prepared statements; but since the query is not syntactically wrong when you execute it the query goes through. However, if you check the return value of <code>$stmt-&gt;bind_param</code> it will likely be returning false.</p>\n\n<p>You would need to change your code to fix this and prevent SQL injection attacks:</p>\n\n<pre><code>$stmt = $dbc-&gt;prepare(\"DELETE FROM users WHERE user_id=? LIMIT 1\");\n</code></pre>\n\n<p>Perhaps also adding some more error checking on your database calls would help as well; for example, make sure that your <code>$stmt-&gt;bind_param</code> was successful before attempting to execute the query.</p>\n\n<p>Second, your error checking on whether or not the query succeeded is not accurate. The query may return 0 affected rows but have no error with the actual query itself. Simply, the user_id that you gave wasn't found in the database; this isn't an error per say as nothing was actually <em>wrong</em> with the query. Keeping in line with your already in-place algorithm you would likely need to change it to something like:</p>\n\n<pre><code>$affectedRows = $stmt-&gt;affected_rows;\nif ($affectedRows === 1) { // If it ran OK.\n echo '&lt;p&gt;The user has been deleted.&lt;/p&gt;'; \n} else { // If the query did not run OK.\n if ($affectedRows === 0) {\n echo '&lt;p&gt;The user ID you provided could not be found.&lt;/p&gt;';\n } else {\n echo '&lt;p class=\"error\"&gt;The user could not be deleted due to a system error.&lt;/p&gt;'; // Public message.\n echo '&lt;p&gt;' . mysqli_connect_errno() . '&lt;br /&gt;Query: ' . $stmt-&gt;error . '&lt;/p&gt;'; // Debugging message.\n }\n}\n</code></pre>\n\n<p>Third, you're susceptible to <a href=\"http://en.wikipedia.org/wiki/Cross-site_scripting\" rel=\"nofollow\">XSS</a>. This can be prevented by escaping your data on output in your view.</p>\n\n<pre><code>$user_id = htmlspecialchars($user_id);\n$last_name = htmlspecialchars($last_name);\n$first_name = htmlspecialchars($first_name);\n$dr = htmlspecialchars($dr);\n\necho '&lt;tr&gt;\n &lt;td align=\"left\"&gt;&lt;a href=\"edit_user.php?id=' . $user_id . '\"&gt;Edit&lt;/a&gt;&lt;/td&gt;\n &lt;td align=\"left\"&gt;&lt;a href=\"delete_user.php?id=' . $user_id .'\"&gt;Delete&lt;/a&gt;&lt;/td&gt;\n &lt;td align=\"left\"&gt;' . $last_name. '&lt;/td&gt;\n &lt;td align=\"left\"&gt;' . $first_name . '&lt;/td&gt;\n &lt;td align=\"left\"&gt;' . $dr . '&lt;/td&gt;\n&lt;/tr&gt;';\n</code></pre>\n\n<p>Lastly, I think it might ease the future maintenance if you split your different tasks up into various objects/files. An object/file to gather the data from the database and an object/file to accept that data and plug it into the view template might be a great place to start. Aim for removing any calls to the database connection in the same code that is displaying HTML.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:38:25.263", "Id": "13360", "Score": "0", "body": "This is my first attempt with prepared statements. The delete still works, strange. Love this forum already, will work on your suggestions and post them. Many thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:47:05.970", "Id": "13361", "Score": "0", "body": "@Wasabi Glad to be of assistance. If you decide to make some changes to your code based on suggestions please be sure to post a new question so you'll get the best chance at getting your code reviewed. I also added some more details on why your delete statement is still working." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T06:03:46.740", "Id": "8531", "ParentId": "8525", "Score": "4" } } ]
{ "AcceptedAnswerId": "8531", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T23:35:04.903", "Id": "8525", "Score": "5", "Tags": [ "php", "performance", "php5" ], "Title": "Prepared statements syntax review" }
8525
<p>I'm not the greatest at writing tests yet and I'm starting a new OSS project for learning and as part of it I want to tackle being more effective at writing tests, more specifically quality tests. I think I write a lot of tests that don't bring much value except maintenance pain sometimes.</p> <p>Can I improve these tests?</p> <pre><code>using System; using System.Text; using System.Collections.Generic; using System.Linq; using FakeItEasy; using HaywireMQ.Server.Channel; using HaywireMQ.Server.MessageStore; using Microsoft.VisualStudio.TestTools.UnitTesting; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoFakeItEasy; namespace HaywireMQ.Server.Tests { /// &lt;summary&gt; /// Tests for HaywireServer /// &lt;/summary&gt; [TestClass] public class HaywireServerTests { private IFixture fixture; public HaywireServerTests() { } [TestInitialize] public void Initialize() { fixture = new Fixture().Customize(new AutoFakeItEasyCustomization()); } [TestMethod] public void Should_use_defaults_without_ModuleCatalog() { // Given var target = new HaywireServer(); // When target.Start(); // Then Assert.AreEqual&lt;Type&gt;(target.MessageStore.GetType(), typeof(InMemoryMessageStore)); Assert.AreEqual&lt;Type&gt;(target.MessageChannel.GetType(), typeof(InMemoryMessageChannel)); } [TestMethod] public void Should_use_ModuleCatalog() { // Given var catalog = new ModuleCatalog(); var messageStore = fixture.CreateAnonymous&lt;IMessageStore&gt;(); var messageChannel = fixture.CreateAnonymous&lt;IMessageChannel&gt;(); catalog.MessageStores.Add(messageStore); catalog.MessageChannels.Add(messageChannel); var target = new HaywireServer(catalog); // When target.Start(); // Then Assert.AreEqual&lt;Type&gt;(target.MessageStore.GetType(), messageStore.GetType()); Assert.AreEqual&lt;Type&gt;(target.MessageChannel.GetType(), messageChannel.GetType()); } [TestMethod] public void Should_create_MessageQueue() { // Given var catalog = new ModuleCatalog(); var messageStore = fixture.CreateAnonymous&lt;IMessageStore&gt;(); var messageChannel = fixture.CreateAnonymous&lt;IMessageChannel&gt;(); catalog.MessageStores.Add(messageStore); catalog.MessageChannels.Add(messageChannel); var target = new HaywireServer(catalog); List&lt;string&gt; ids = new List&lt;string&gt;() {"test"}; A.CallTo(() =&gt; messageStore.GetQueues()).Returns(ids); // When target.Start(); // Then A.CallTo(() =&gt; messageStore.GetQueues()).MustHaveHappened(); Assert.AreEqual&lt;int&gt;(target.MessageQueues.Count, 1); Assert.AreEqual&lt;string&gt;(target.MessageQueues[0].Id, "test"); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T06:18:12.253", "Id": "13323", "Score": "2", "body": "One improvement is to use xUnit.net instead of MSTest which integrates with AutoFixture and allows you to parameterize those tests via data theories. Once you have parameterized tests, AutoFixture can take care of the rest supplying the parameter values for you and even Auto-Mock them using FakeItEasy. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T10:07:50.120", "Id": "13329", "Score": "1", "body": "You're probably better at testing than me, but shouldn't there really only be one Assert per test method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T13:12:52.597", "Id": "13333", "Score": "2", "body": "Each test should test only one \"thing\". So having a couple of Asserts in a test is actually fine. For example, it_should_return_empty_string() would be perfectly fine to have Assert.IsNotNull(result) and Assert.Equals(String.Empty, result)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T06:52:38.710", "Id": "85910", "Score": "0", "body": "I would not use MSTest. It's slower than the alternatives and has fewer features." } ]
[ { "body": "<p>I think it's quite well written, would have only two ideas.</p>\n\n<ol>\n<li><p>For the repeating part of the fixture setup (given) I'd consider using a <a href=\"http://xunitpatterns.com/Standard%20Fixture.html\" rel=\"nofollow\">Standard Fixture</a>, probably via a setup helper method.</p></li>\n<li><p>I'd consider splitting the <a href=\"http://xunitpatterns.com/Result%20Verification%20Patterns.html\" rel=\"nofollow\">state and behaviour verification</a> parts of <code>Should_create_MessageQueue()</code> into two separate test methods. The behaviour verification of <code>MustHaveHappened()</code> deals with a different issue than the state verification with the asserts.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T10:28:27.223", "Id": "8539", "ParentId": "8528", "Score": "6" } }, { "body": "<p>Assuming that I've correctly managed to extrapolate the <a href=\"http://xunitpatterns.com/SUT.html\">SUT</a> and friends from the question, I'd reduce the tests to the following. Please note that this focuses only on <a href=\"http://autofixture.codeplex.com/\">AutoFixture</a> mechanics, and not on the general design of neither test nor SUT API.</p>\n\n<p>AFAICT, the following tests state the same as the tests in the OP, but reduced to only the necessary statements. Still, I agree with Nikos Baxevanis that it would be possible to reduce these tests dramatically with <a href=\"http://xunit.codeplex.com/\">xUnit.net</a> instead of MSTest.</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Linq;\nusing FakeItEasy;\nusing FirstAutoFixtureReviewForKellySommers;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing Ploeh.AutoFixture;\nusing Ploeh.AutoFixture.AutoFakeItEasy;\nusing Ploeh.AutoFixture.Kernel;\n\nnamespace HaywireMQ.Server.Tests\n{\n /// &lt;summary&gt;\n /// Tests for HaywireServer\n /// &lt;/summary&gt;\n [TestClass]\n public class HaywireServerTests\n {\n [TestMethod]\n public void Should_use_defaults_without_ModuleCatalog()\n {\n // Given\n var fixture = new Fixture().Customize(new TestConventions());\n\n // When\n var target = fixture.CreateAnonymous&lt;HaywireServer&gt;();\n\n // Then\n Assert.IsInstanceOfType(target.MessageStore, typeof(InMemoryMessageStore));\n Assert.IsInstanceOfType(target.MessageChannel, typeof(InMemoryMessageChannel));\n }\n\n [TestMethod]\n public void Should_use_ModuleCatalog()\n {\n // Given\n var fixture = new Fixture().Customize(new TestConventions());\n\n var catalog = fixture.Freeze&lt;ModuleCatalog&gt;();\n fixture.AddManyTo(catalog.MessageStores, 1);\n fixture.AddManyTo(catalog.MessageChannels, 1);\n\n // When\n var target = fixture.CreateAnonymous&lt;HaywireServer&gt;();\n\n // Then\n Assert.AreEqual(catalog.MessageStores.Single(), target.MessageStore);\n Assert.AreEqual(catalog.MessageChannels.Single(), target.MessageChannel);\n }\n\n [TestMethod]\n public void Should_create_MessageQueue()\n {\n // Given\n var fixture = new Fixture().Customize(new TestConventions());\n\n var catalog = fixture.Freeze&lt;ModuleCatalog&gt;();\n fixture.AddManyTo(catalog.MessageStores, 1);\n\n List&lt;string&gt; ids = fixture.CreateMany&lt;string&gt;(1).ToList();\n A.CallTo(() =&gt; catalog.MessageStores.Single().GetQueues()).Returns(ids);\n\n var target = fixture.CreateAnonymous&lt;HaywireServer&gt;();\n\n // When\n target.Start();\n\n // Then\n A.CallTo(() =&gt; catalog.MessageStores.Single().GetQueues()).MustHaveHappened();\n Assert.AreEqual(1, target.MessageQueues.Count);\n Assert.AreEqual(ids.First(), target.MessageQueues[0].Id);\n }\n\n private class TestConventions : CompositeCustomization\n {\n public TestConventions()\n : base(\n new AutoFakeItEasyCustomization(),\n new GreedyHaywireServerCustomization())\n {\n }\n }\n\n private class GreedyHaywireServerCustomization : ICustomization\n {\n public void Customize(IFixture fixture)\n {\n fixture.Customize&lt;HaywireServer&gt;(c =&gt;\n c.FromFactory(new MethodInvoker(new GreedyConstructorQuery())));\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T21:27:05.320", "Id": "13387", "Score": "1", "body": "Curious why you removed the `TestInitialize` method in favor of setting up the fixture in each test? I'm generally also of the opinion that too much DRY-aware refactoring makes tests less expressive, but would have thought that something like this that is purely infrastructural is a good candidate for moving out of the way of the actual meat of the test case (particularly since you aren't really increasing the information locality, since the important part is in TestConventions anyways)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T21:39:07.077", "Id": "13388", "Score": "0", "body": "I have an (irrational or subjective) dislike of Implicit Setup because I feel that the lack of proximity between a [TestInitialize] method and the last test cases in a (larger) test file makes it too hard to understand what's going on at a glance. I prefer each test case to be self-contained." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T04:18:35.407", "Id": "13405", "Score": "0", "body": "@MarkSeemann I find that harder to read because there's more AutoFixture than what I'd call regular use of the code involved. To someone new to using AutoFixture I'm not sure what Freeze() or GreedyConstructorQuery does.\n\nWhat does CreateAnonymous() do? I thought it created the fake but now it looks to be the concrete type.\n\nSUT was meant to be what I named \"target\" just to clarify.\n\nAlso was adding to the catalog left out on purpose? Reason I ask is in Start() exceptions occur if no MessageChannel or MessageStore is detected in the catalog.\n\nThese questions probably due to misunderstanding :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T05:53:20.903", "Id": "13406", "Score": "2", "body": "AutoFixture is a DSL. Tests will be harder to read until you understand the language - as with all other DSLs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T05:54:11.607", "Id": "13407", "Score": "0", "body": "CreateAnonymous creates the type you ask for. If you ask for a concrete type, you get back a concrete type. If you ask for an interface, you get back a fake, courtesy of the FakeItEasy customization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T05:57:43.817", "Id": "13408", "Score": "0", "body": "I left out adding to the catalog because it seemed to add no value. Remember that I've never seen the SUT - I extrapolated from your tests. Nothing in these tests indicated that Start might throw exceptions if no MessageChannel or MessageStore was detected. If that's the case, there should be a test case stating exactly that, and nothing else." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T14:32:35.837", "Id": "13422", "Score": "0", "body": "@MarkSeemann Just to make sure I understand correctly. I should put the catalog back in those tests since it's required for Start() and then write a new test that tests for the exception case? What does Freeze() do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T16:26:43.690", "Id": "13447", "Score": "1", "body": "Yes, or better yet: improve the design in order to get rid of the Temporal Coupling." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T16:27:24.267", "Id": "13448", "Score": "0", "body": "Freeze: http://blog.ploeh.dk/2010/03/17/AutoFixtureFreeze.aspx" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T21:18:01.627", "Id": "8570", "ParentId": "8528", "Score": "8" } }, { "body": "<p>A couple of points that I can see:</p>\n\n<p>In Should_use_ModuleCatalog, </p>\n\n<ul>\n<li>I see that the test is around the HaywireServer since the assert\nis after the action on target. However, the asserts are on properties\nof ModuleCatalog. I would prefer this test to be a catalog's test\nrather than a target's test. </li>\n<li>What does this testcase ensure? It\ntells me that the properties are set with the appropriate types. I\nwouldn't test this out explicitly unless there are branching\nworkflows that could set different types based on context. </li>\n<li>Catalog seems to have a List of MessageStore, however when catalog is\ninjected into the target, the target seems to have just one\nMessageStore - Is there a logic around this? If so I would test that\nout.</li>\n</ul>\n\n<p>Something that I noted (not related to the testing aspect):\nthis line:</p>\n\n<pre><code>catalog.MessageStores.Add(messageStore);\n</code></pre>\n\n<p>tells me that Catalog has a List (or a similar collection) - which isn't necessarily something to be published as a contract to consumers.\nI would prefer something like:</p>\n\n<pre><code>catalog.AddMessageStore(messageStore)\n</code></pre>\n\n<p>so that I am free to refactor ModuleCatalog to use any internal mechanism of holding this. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T06:23:33.800", "Id": "8581", "ParentId": "8528", "Score": "3" } } ]
{ "AcceptedAnswerId": "8570", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T05:49:22.553", "Id": "8528", "Score": "11", "Tags": [ "c#", ".net", "unit-testing" ], "Title": "Can these unit tests be improved?" }
8528
<p>I've got this all working, but it seems to be quite long-winded, and I thought I'd post here and see if I'm doing it wrong...</p> <p>I have a M:M relationship between an Installer and a MasterInstance. The classes (code-first) look like:</p> <pre><code>public class MasterInstance { .. rest of fields here .. public virtual ICollection&lt;Installer&gt; PermittedInstallers { get; set; } } public class Installer { .. rest of fields here .. public virtual ICollection&lt;MasterInstance&gt; PermittedMasterInstances { get; set; } } </code></pre> <p>I want to be able to edit these in my Installer view, using a multi-list box. So, I create a ViewModel for what I need:</p> <pre><code>public class InstallerViewModel { public Installer Installer { get; set; } public List&lt;MasterInstance&gt; PermittedMasterInstances { get; set; } public int[] SelectedMasterInstances { get; set; } } </code></pre> <p>And then I place this in my view like so so that I can select the instances for my installer:</p> <pre><code>&lt;div class="editor-field"&gt; @Html.ListBoxFor(model =&gt; model.SelectedMasterInstances,(Model.PermittedMasterInstances).Select(option =&gt; new SelectListItem { Text = option.Name, Value = option.MasterInstanceId.ToString() })) &lt;/div&gt; </code></pre> <p>In the controller, for the edit action, I need to set this view model up:</p> <pre><code>var installer = context.Installers.Include(i =&gt; i.PermittedMasterInstances).Single(x =&gt; x.InstallerId == installerId); InstallerViewModel model = new InstallerViewModel { Installer = installer, PermittedMasterInstances = context.MasterInstances.ToList(), SelectedMasterInstances = installer.PermittedMasterInstances.Select(i =&gt; i.MasterInstanceId).ToArray() }; return View(model); </code></pre> <p>Finally, on the post of the edit, I need to delete any relationships that are no longer there and add the new ones:</p> <pre><code>// Grab the model from the viewmodel and attach to the context var installer = installerModel.Installer; context.Installers.Attach(installer); // Load the related records (dont know why Lazy Loading wouldn't kick in here) context.Entry(installer).Collection(i =&gt; i.PermittedMasterInstances).Load(); // Iterate and delete existing relationships var instancesToDelete = installer.PermittedMasterInstances.Where(mi =&gt; !installerModel.SelectedMasterInstances.Contains(i.MasterInstanceId)).ToList(); instancesToDelete.ForEach(mi =&gt; installer.PermittedMasterInstances.Remove(mi)); // Now loop through an int[] and add those new relations, WITHOUT the pain of fetching them from the DB foreach (var permittedMasterInstanceId in installerModel.SelectedMasterInstances) { if (!installer.PermittedMasterInstances.Any(pmi =&gt; pmi.MasterInstanceId == permittedMasterInstanceId)) { var masterInstance = new MasterInstance {MasterInstanceId = permittedMasterInstanceId}; context.MasterInstances.Attach(masterInstance); installer.PermittedMasterInstances.Add(masterInstance); } } // We're done - save and finish. context.Entry&lt;Installer&gt;(installer).State = EntityState.Modified; context.SaveChanges(); </code></pre> <p>So this works... But, it seemed like a lot of effort, is this the right/best way to achieve it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T21:42:46.077", "Id": "14137", "Score": "0", "body": "This is exactly how ive approached this problem in the past, its a bit ugly but ive never fund a better way" } ]
[ { "body": "<p>I know this is an old question, but I think the problem is timeless. Many to many associations (i.e. without junction class) in Entity Framework are always independent associations, so you can only establish or remove them by manipulating object collections, not primitive key values. Inefficiency is inherent to the implementation. </p>\n\n<p>But it is not prohibited to have a second context that only contains junction tables.</p>\n\n<p>You could create a context that contains the <code>MasterInstanceInstaller</code> junction table and use this to update the associations in the most efficient way you can get using EF:</p>\n\n<pre><code>var installer = installerModel.Installer;\n\nvar junctions = context.MasterInstanceInstallers\n .Where(x =&gt; x.InstallerId == installer.InstallerId)\n .ToList();\n\n// Delete deselected instances.\nforeach(var mi in junctions\n .Where(x =&gt; !installerModel.SelectedMasterInstances\n .Contains(x.MasterInstanceId)))\n{\n context.MasterInstanceInstallers.Remove(mi);\n}\n\n// Add newly selected instances.\nforeach(int instanceId in installerModel.SelectedMasterInstances\n .Except(junctions.Select(j =&gt; j.MasterInstanceId)))\n}\n context.MasterInstanceInstallers.Add(new MasterInstanceInstaller\n {\n InstallerId = installer.InstallerId,\n MasterInstanceId = instanceId\n }\n );\n}\ncontext.SaveChanges();\n</code></pre>\n\n<p>Now, if necessary you can populate the updated many to many association through the main context.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T21:17:13.517", "Id": "45441", "ParentId": "8537", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T08:47:44.777", "Id": "8537", "Score": "11", "Tags": [ "c#", "mvc", "entity-framework", "asp.net-mvc-3" ], "Title": "Efficient way to deal with maintaining Many:Many relationships in EF Code-First" }
8537
<p>When I want to make some quick tests for my UITableViewControllers, I usually create an NSArray that holds some dummy data. I would like to know if I'm doing anything wrong here:</p> <p>First in <code>MasterViewController.h</code>:</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @class DetailViewController; @interface MasterViewController : UITableViewController @property (nonatomic, retain) NSArray *dataSourceArray; @end </code></pre> <p>and then in <code>MasterViewController.m</code>:</p> <pre><code>#import "MasterViewController.h" @implementation MasterViewController @synthesize dataSourceArray = _dataSourceArray; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { self.title = NSLocalizedString(@"Master", @"Master"); _dataSourceArray = [[NSArray alloc] initWithObjects:@"obj 1", @"obj 2", @"obj 3", nil]; } return self; } - (void)dealloc { [_dataSourceArray release]; [super dealloc]; } </code></pre> <p>So, the real question, as long as I'm <strong>not</strong> assigning <code>_dataSourceArray</code> to something else, I'm safe in terms of memory management here, right?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T13:28:21.353", "Id": "24026", "Score": "0", "body": "I agree, the code looks good to me." } ]
[ { "body": "<p>Yes. Everything seems correct here. </p>\n\n<p>Like you mention yourself: make sure you use <code>self.dataSourceArray</code> to assign new values, and the synthesized setter will take care of memory management.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T10:55:58.327", "Id": "8540", "ParentId": "8538", "Score": "1" } } ]
{ "AcceptedAnswerId": "8540", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T09:11:21.803", "Id": "8538", "Score": "2", "Tags": [ "objective-c", "memory-management" ], "Title": "Am I using my data source array correctly?" }
8538
<p>I'm putting together some classes as a model for some information (that I'm currently pulling from a website).</p> <p>The classes are implemented in C# - because in the current version of F# there are no autoimplemented properties. The logic to fill these classes from the website is going to be writen in F#. (Because I like F#, and it works nice for webscraping.)</p> <p>So since I'm working functionally (I seems to always work functionally there days even in C#). I don't want these objects to be mutable. Setting mutable fields is ugly in F# (and for good reason, mutable objects are evil).</p> <p>So all there data fields have only private setters but this makes my constructors long. I planned to be using named arguments in them anyway, but still 5 arguments is a lot. And I don't think F# supports object property initialisers anyway.</p> <pre><code>public class PopularitySplitClassOptionSet : IClassOptionsSet { public PopularitySplitClassOptionSet (string description, IEnumerable&lt;ClassOption&gt; popularClasses, IEnumerable&lt;ClassOption&gt; unpopularClasses, int reqPreferences, int minUnpopularPreferences) { PopularClasses = popularClasses; UnpopularClasses = unpopularClasses; RequiredPrefereces = reqPreferences; MinUnpopularPrefereces = minUnpopularPreferences; } public IEnumerable&lt;ClassOption&gt; Classes { get { return PopularClasses.Concat(UnpopularClasses); } } public int RequiredPrefereces { get; private set; } public int MinUnpopularPrefereces { get; private set; } public int MaxPopularPrefereces { get { return RequiredPrefereces - MinUnpopularPrefereces; } } public IEnumerable&lt;ClassOption&gt; PopularClasses { get; private set; } public IEnumerable&lt;ClassOption&gt; UnpopularClasses { get; private set; } } </code></pre> <p>Edit: Is this good practice? Am I thinking this right?</p> <p>Also: I wonder if:</p> <pre><code>public readonly int RequiredPrefereces { get; private set; } </code></pre> <p>would be better? Or is that not actually a thing you can do?</p> <p>Related questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/2249980/c-immutability-and-public-readonly-fields">C#, immutability and public readonly fields</a></li> <li><a href="https://stackoverflow.com/questions/6239373/how-to-avoid-too-many-parameters-problem-in-api-design/6240359#6240359">How to avoid “too many parameters” problem in API design?</a></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T13:36:48.800", "Id": "13334", "Score": "0", "body": "So what's the question you would like answered?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T13:39:41.117", "Id": "13335", "Score": "1", "body": "This is Code Review.SE. I thought the question was implict.\nIs this good practice>" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T14:12:45.743", "Id": "13339", "Score": "1", "body": "@Oxinabox `But this makes my constructors long.` I wouldn't say half a dozen lines is long; but even if it is, so what?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T14:41:56.557", "Id": "13340", "Score": "1", "body": "@Oxinabox There are still many different aspects of code that can be reviewed. In order to make a question-answer format viable, targetted questions are needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:26:38.737", "Id": "13414", "Score": "0", "body": "By my constuctors long, i mean: \"Makes my constructors take lots of parameters\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-05T06:20:01.947", "Id": "13567", "Score": "0", "body": "I'm thinking it may have been the bigger mistake to implement these in C# rather than using F# records." } ]
[ { "body": "<p>This is what I program when I want \"immutable\" classes in C#. You do have an access leak right now though, in that <code>PopularClasses</code> and <code>UnpopularClasses</code> both set and get the underlying object, allowing modification of that object, thus making the class immutable. (This is a bigger problem for set than get, as get would require figuring out which collection type is actually being held. Set you already know because you set it.)</p>\n\n<pre><code>List&lt;string&gt; popularClasses = new List&lt;string&gt;;\npopularClasses.add(\"hello\");\n\npscos = new PopularitySplitClassOptionSet(..., popularClasses, ...);\npopularClasses.add(\"sup\"); // This is now added to pscos.\n\nList&lt;string&gt; getAlsoLeaks = (List&lt;string&gt;)(pscos.PopularClasses);\ngetAlsoLeaks.add(\"yo\"); // This is also added.\n</code></pre>\n\n<p>You will need to copy on get and set to avoid this. Usually I use <a href=\"http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx\" rel=\"nofollow\"><code>LinkedList&lt;T&gt;</code></a> for this purpose, unless I will need random access, in which case I use <a href=\"http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx\" rel=\"nofollow\"><code>List&lt;T&gt;</code></a>. Since you're only currently using <code>IEnumerable&lt;T&gt;</code>, I'm assuming that random access isn't an issue and using <code>LinkedList&lt;T&gt;</code>.</p>\n\n<pre><code>private LinkedList&lt;ClassOption&gt; popularClasses;\npublic IEnumerable&lt;ClassOption&gt; PopularClasses\n{\n get\n {\n foreach (ClassOption classOption in list.popularClasses)\n yield return classOption;\n // OR:\n // return new LinkedList&lt;ClassOption&gt;(this.popularClasses);\n }\n set\n {\n this.popularClasses = new LinkedList&lt;ClassOption&gt;(value);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:37:43.357", "Id": "13415", "Score": "0", "body": "Huh, normally I remember the posibility if casing back to the original type.\nI forgot this time, because I planned on filling them with F# types (which are immutable, except array), in particular i planned on filling them with straight Seq (which is an alias for IEnumerable), but of course, the mutable Array implements Seq." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T05:51:28.323", "Id": "13468", "Score": "0", "body": "@Oxinabox I'll have to apologize for not being too familiar with F#'s types. If you're going to plug in immutable things, then obviously you won't need to worry about it in your class. Just be sure to comment such!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T15:18:49.723", "Id": "13480", "Score": "0", "body": "No you're right. Microsoft.FSharp.Collections.SeqModule.ReadOnly(Seq) exists for just that purpose.\nwhy doucment, when i can enforce?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T14:40:12.017", "Id": "8545", "ParentId": "8543", "Score": "2" } }, { "body": "<p>Here's a take where the collection objects are passed back as read-only to the caller and the member variables are completely immutable:</p>\n\n<pre><code>public sealed class PopularitySplitClassOptionSet : IClassOptionsSet\n{\n private readonly string description;\n\n private readonly IEnumerable&lt;ClassOption&gt; popularClasses;\n\n private readonly IEnumerable&lt;ClassOption&gt; unpopularClasses;\n\n private readonly int requiredPrefereces;\n\n private readonly int minUnpopularPrefereces;\n\n private readonly IEnumerable&lt;ClassOption&gt; classes;\n\n private readonly int maxPopularPrefereces;\n\n public PopularitySplitClassOptionSet(\n string description,\n IEnumerable&lt;ClassOption&gt; popularClasses,\n IEnumerable&lt;ClassOption&gt; unpopularClasses,\n int reqPreferences,\n int minUnpopularPreferences)\n {\n if (description == null)\n {\n throw new ArgumentNullException(\"description\");\n }\n\n if (popularClasses == null)\n {\n throw new ArgumentNullException(\"popularClasses\");\n }\n\n if (unpopularClasses == null)\n {\n throw new ArgumentNullException(\"unpopularClasses\");\n }\n\n if (minUnpopularPreferences &gt; reqPreferences)\n {\n throw new ArgumentOutOfRangeException(\n \"minUnpopularPreferences\",\n minUnpopularPreferences,\n \"The minimum number of unpopular preferences may not exceed the number of required preferences.\");\n }\n\n this.description = description;\n this.popularClasses = popularClasses.ToList().AsReadOnly();\n this.unpopularClasses = unpopularClasses.ToList().AsReadOnly();\n this.requiredPrefereces = reqPreferences;\n this.minUnpopularPrefereces = minUnpopularPreferences;\n\n this.classes = this.popularClasses.Concat(this.unpopularClasses).ToList().AsReadOnly();\n this.maxPopularPrefereces = this.requiredPrefereces - this.minUnpopularPrefereces;\n }\n\n public string Description\n {\n get\n {\n return this.description;\n }\n }\n\n public IEnumerable&lt;ClassOption&gt; Classes\n {\n get\n {\n return this.classes;\n }\n }\n\n public int RequiredPrefereces\n {\n get\n {\n return this.requiredPrefereces;\n }\n }\n\n public int MinUnpopularPrefereces\n {\n get\n {\n return this.minUnpopularPrefereces;\n }\n }\n\n public int MaxPopularPrefereces\n {\n get\n {\n return this.maxPopularPrefereces;\n }\n }\n\n public IEnumerable&lt;ClassOption&gt; PopularClasses\n {\n get\n {\n return this.popularClasses;\n }\n }\n\n public IEnumerable&lt;ClassOption&gt; UnpopularClasses\n {\n get\n {\n return this.unpopularClasses;\n }\n }\n}\n</code></pre>\n\n<p>I think a five or six line constructor is completely acceptable. In fact, my revision includes some sanity checks on the parameters. The second revision does the calculations in the constructor since the values are immutable (no need to do those concats and subtraction in the properties).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:58:42.640", "Id": "13364", "Score": "0", "body": "+1. I always forget about that wraskly `AsReadOnly` method! Also, this is what my constructors usually look like too, as far as error checking goes. You get used to it after a while; it stops looking \"long\" and starts looking \"right\" instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:41:00.543", "Id": "13416", "Score": "0", "body": "Why are you calculating these things in the constructor?\nIEnumereable.Concat and subtraction are O(1) operations. Ie they are basically free.\nIt would seem clearer to have them in the properties" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:44:52.783", "Id": "13417", "Score": "0", "body": "Also Is this a reasonable way to make my IEnumerable's Readonly:\n`Microsoft.FSharp.Collections.SeqModule.ReadOnly(classes)`\nhttp://msdn.microsoft.com/en-us/library/ee340408.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T13:17:00.713", "Id": "13420", "Score": "0", "body": "@Oxinaboxas to your first question - because they're immutable and invariant. Let the calculation be done and no more. To your second question, I'm afraid I've never seen that method before as I'm not big into F#, sorry." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:05:18.753", "Id": "8548", "ParentId": "8543", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T13:20:56.820", "Id": "8543", "Score": "4", "Tags": [ "c#", "f#", "immutability", "properties" ], "Title": "Immutable pure data classes with public setters on properties" }
8543
<p>What is the best practices to pass data from presentation to application layer?</p> <p>Currently I have something like this:</p> <p><strong>in presentation layer:</strong></p> <p>the controller:</p> <pre><code>public class ProductController : Controller { private readonly IProductService _productService; public ProductController(IProductService productService) { _productService = productService; } public ActionResult ProductCreateAction(ProductCreateViewModel vm) { _productService.CreateProduct(vm); return Json(new { Ok = true }); } } </code></pre> <p>and the view model:</p> <pre><code>public class ProductCreateViewModel : ICreateProductCommand { public string Name { get; set; } public int Price { get; set; } } </code></pre> <p><strong>in application layer:</strong></p> <pre><code>public class ProductService : IProductService { public void Create(ICreateProductCommand command) { var product = new Product(command.Name, command.Price); //... add to repositoey and call SaveChanges ... } } public interface ICreateProductCommand { string Name { get; set; } int Price { get; set; } } </code></pre> <p>(using <code>FluentValidation</code> here)</p> <pre><code>public class CreateProductCommandValidator : AbstractValidator&lt;ICreateProductCommand&gt; { public CreateProductCommandValidator() { RuleFor(x =&gt; x.Name) .NotEmpty(); RuleFor(x =&gt; x.Price) .NotEmpty(); } } </code></pre> <ol> <li>Is it ok to continue using this approach or there are better practices?</li> <li>Is it better to have one save action in controller or separate create/update actions?</li> </ol> <p>i.e.:</p> <pre><code>public ActionResult Save(SomeViewModel vm) { if(vm.Id.HasValue) { //update } else { //create } } </code></pre> <p>vs.</p> <pre><code>public ActionResult Create(SomeViewModel vm) { //create } public ActionResult Update(SomeViewModel vm) { //update } </code></pre>
[]
[ { "body": "<p>Overall, your code is very good, there is not much to review..</p>\n\n<p>In your ViewModel, you might want to use <code>DataAnnotations</code> to do client (using jquery unobstrusive script)/server validation ex : </p>\n\n<pre><code>public class ProductCreateViewModel : ICreateProductCommand\n{\n [Required]\n public string Name { get; set; }\n\n [Required]\n public int Price { get; set; }\n}\n\npublic ActionResult ProductCreateAction(ProductCreateViewModel vm)\n{\n if(ModelState.IsValid) //Server validation of the data annotations.\n {\n _productService.CreateProduct(vm);\n return Json(new { Ok = true });\n }\n}\n</code></pre>\n\n<p>To answer your second question, I believe it is better to use two separated actions to separate the use cases of when you will use Create vs. Update. Plus one day you might have different roles for adding and updating (it's a little hardcore but it could happen), you would want your actions to be marked with different authentication attributes (If you use MVC membership)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-21T14:24:00.573", "Id": "60720", "ParentId": "8549", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:10:51.187", "Id": "8549", "Score": "8", "Tags": [ "c#", "mvc", "asp.net-mvc-3" ], "Title": "Is this appropriate way to pass data from presentation to application layer?" }
8549
<p>I use the following code to populate my HTML with JSON. The problem is that I'm afraid this code will be inefficient if the number of records that I get from the service call are large (200 or more).</p> <p>Are there ways I can change my code to make sure this won't be an issue? Or is my code fine as it stands?</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script&gt; var jsonObj = { "products": [ { "ImageName": "product1.png", "Description": "Yummy choco" }, { "ImageName": "product2.png", "Description": "candy villa" }, { "ImageName": "product3.png", "Description": "vanilla icecream" } ], } $(document).ready(function() { for(var key = 0; key &lt; jsonObj.products.length - 1; key++) { var domStructure ='\ &lt;tr&gt;\ &lt;td&gt;\ &lt;img src="' + jsonObj.products[key].ImageName + '"&gt;\ &lt;/td&gt;\ &lt;td&gt;' + jsonObj.products[key].Description + '&lt;/td&gt;\ &lt;/tr&gt;'; $('#tableProducts').find('tbody').append(domStructure); } }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;table id="tableProducts"&gt;&lt;tbody&gt;&lt;/tbody&gt;&lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Just one suggestion, </p>\n\n<p>Select tbody before loop. Currently you are selecting it again and again in loop.</p>\n\n<p>Also, you should use,</p>\n\n<pre><code> $('#tableProducts').find('tbody').append(domStructure);\n</code></pre>\n\n<p><code>children()</code> search for direct descendants while <code>find()</code> looks for all descendants.</p>\n\n<p>But surprisingly, jsperf.com suggests, </p>\n\n<p><code>$('#tableProducts').find('tbody')</code> is faster than <code>$('#tableProducts tbody')</code> and <code>$('#tableProducts').children('tbody')</code>. <code>$('#tableProducts tbody')</code> and <code>$('#tableProducts').children('tbody')</code> are almost same.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T08:28:39.663", "Id": "13346", "Score": "0", "body": "valid point Jashwant. Will incorporate this change. Thanks for your time :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T07:32:44.003", "Id": "8552", "ParentId": "8550", "Score": "2" } }, { "body": "<p>You are using google jquery library, why you don't use it like this:</p>\n\n<pre><code> &lt;script src=\"http://www.google.com/jsapi\" type=\"text/javascript\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\"&gt;\n google.load(\"jquery\", \"1.7.1\");\n //google.load(\"jqueryui\", \"1.7.3\");\n &lt;/script&gt; \n</code></pre>\n\n<p>This is more dynamic and you can change the version of what you need.</p>\n\n<p>I think this is an improvement you could make.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T07:51:31.840", "Id": "13348", "Score": "1", "body": "Is it the answer to this question ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T12:46:36.407", "Id": "13349", "Score": "0", "body": "Just a sugestion if you want to improve your code and like to use google jquery library" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T07:33:40.067", "Id": "8553", "ParentId": "8550", "Score": "0" } }, { "body": "<p>don't even really need jQuery for this task</p>\n\n<p>here's one way to rework this script:</p>\n\n<p><a href=\"http://jsfiddle.net/pxfunc/paR7S/\" rel=\"nofollow\">example jsfiddle</a></p>\n\n<pre><code>var domStructure = \"\";\n jsonObj = {\n \"products\": [\n {\n \"ImageName\": \"product1.png\",\n \"Description\": \"Yummy choco\"\n },\n {\n \"ImageName\": \"product2.png\",\n \"Description\": \"candy villa\"\n },\n {\n \"ImageName\": \"product3.png\",\n \"Description\": \"vanilla icecream\"\n }],\n};\n\nfunction getTableRow(img, desc) {\n return '\\\n &lt;tr&gt;\\\n &lt;td&gt;\\\n &lt;img src=\"' + img + '\"&gt;\\\n &lt;/td&gt;\\\n &lt;td&gt;' + desc + '&lt;/td&gt;\\\n &lt;/tr&gt;';\n}\n\nfor(var key in jsonObj.products) {\n domStructure += getTableRow(jsonObj.products[key].ImageName, jsonObj.products[key].Description);\n}\n\ndocument.getElementById('tableProducts').getElementsByTagName('tbody')[0].innerHTML = domStructure;\n</code></pre>\n\n<p>or if you keep jQuery method <strike>to set the table row markup use <code>$('#tableProducts tbody')</code> instead of <code>$('#tableProducts').find('tbody')</code>, no need to have jQuery fetch the first element then find the second vs letting it works it magic on one selector.</strike> it's about the same speed on the various selectors according to this <a href=\"http://jsperf.com/jquery-tbody-selector\" rel=\"nofollow\">jsperf</a>.</p>\n\n<p>Tests the following html setters:</p>\n\n<ol>\n<li><code>$('#tableProducts tbody').html(domStructure);</code></li>\n<li><code>$('#tableProducts').find('tbody').html(domStructure);</code></li>\n<li><code>$('#tableProducts').children('tbody').html(domStructure);</code></li>\n<li><code>document.getElementById('tableProducts').getElementsByTagName('tbody')[0].innerHTML = domStructure;</code></li>\n</ol>\n\n<p>in <a href=\"http://www.browserscope.org/user/tests/table/agt1YS1wcm9maWxlcnINCxIEVGVzdBi_0qANDA\" rel=\"nofollow\">the results</a> the pure JS method jumps ahead on Firefox 9.0.1 and Safari 5.1.2</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T08:48:57.147", "Id": "13350", "Score": "0", "body": "jspeft suggests, $('#tableProducts').find('tbody') is faster than $('#tableProducts tbody') and $('#tableProducts').children('tbody'). $('#tableProducts tbody') and $('#tableProducts').children('tbody') are almost same." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T09:46:35.897", "Id": "13351", "Score": "0", "body": "thanks for your help Mdmullinax. I am using jquery for other implementations on my project.\n\nis it fine to use the core javascript methodology only for this functionality??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T15:34:55.067", "Id": "13352", "Score": "0", "body": "sure you can always use the pure javascript methodology, and you'll generally see a performance increase when you do but it can lead to additional development time and testing vs jQuery. However, if you're already using jQuery it may be more maintainable code if it's all consistently in jQuery." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T15:35:48.703", "Id": "13353", "Score": "0", "body": "@Jashwant updated my answer with jsperf link" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T15:48:29.773", "Id": "13354", "Score": "0", "body": "yeap, there is no match for pure javascript :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T07:37:13.760", "Id": "8554", "ParentId": "8550", "Score": "3" } }, { "body": "<p>Even though your code may be doing proper output. What you did is not ideal way to doing this. \nIdeally, you should iterate the Json object and generate the HTML content. This is most optimized way.</p>\n\n<p>Smart jQuery programmer code like this :)</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n$(document).ready(function(){ \n var jsonObj = {\n \"products\": [\n {\n \"ImageName\": \"product1.png\",\n \"Description\": \"Yummy choco\"\n },\n {\n \"ImageName\": \"product2.png\",\n \"Description\": \"candy villa\"\n },\n {\n \"ImageName\": \"product3.png\",\n \"Description\": \"vanilla icecream\"\n }\n ]\n };\n\n var htmlContent=\"\";\n $.each(jsonObj[\"products\"],function(key,val){ \n htmlContent+=(\"&lt;tr&gt;&lt;td&gt;\"+val[\"ImageName\"]+\"&lt;/td&gt;&lt;td&gt;\"+val[\"Description\"]+\"&lt;/td&gt;&lt;/tr&gt;\"); \n }); \n $('#tableProducts').find('tbody').append(htmlContent);\n});\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;table id=\"tableProducts\"&gt;&lt;tbody&gt;&lt;/tbody&gt;&lt;/table&gt;\n&lt;/body&gt;\n&lt;/html&gt; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T09:35:27.067", "Id": "13355", "Score": "0", "body": "this is what i was looking for ... you are a smart programmer Umesh. Thanks a lot dude !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T09:58:39.967", "Id": "13356", "Score": "0", "body": "@Umesh... want one more suggestion like rather putting the <tr><td> tags, can i dynamically create the markup? will it effect the performance of my code? please suggest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T11:22:30.350", "Id": "13357", "Score": "0", "body": "is there any possibility to create the markup dynamically means creating '<tr><td>' on the fly ????" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T04:46:34.523", "Id": "13358", "Score": "0", "body": "It's possible. In current case, it will be of no use. We are just generating the code to put inside the table. It can be done in any ways." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T07:49:28.580", "Id": "8555", "ParentId": "8550", "Score": "2" } } ]
{ "AcceptedAnswerId": "8554", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T06:30:53.620", "Id": "8550", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Optimizing javascript/jquery code for HTML creation with JSON" }
8550
<p>I have existing code that handles a tarball and would like to use that to process a directory, so I thought it would be reasonable to pack the directory up in a temporary file. I ended up writing:</p> <pre><code>class temp_tarball( object ): def __init__( self, path ): self.tmp = tempfile.NamedTemporaryFile() self.tarfile = tarfile.open( None, 'w:', self.tmp ) self.tarfile.add( path, '.' ) self.tarfile.close() self.tmp.flush() self.tarfile = tarfile.open( self.tmp.name, 'r:' ) def __del__( self ): self.tarfile.close() self.tmp.close() </code></pre> <p>I am looking for a cleaner way to reopen the tarfile with mode 'r'.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:47:55.030", "Id": "13363", "Score": "0", "body": "What's your concern with it now?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T16:21:28.297", "Id": "13367", "Score": "0", "body": "@winston I don't like using the NamedTemporaryFile, and would prefer to use tempfile.TemporaryFile. I don't really have a specific complaint; it just smells a bit funny as it is." } ]
[ { "body": "<p>You could try:</p>\n\n<pre><code>def __init__(self, path):\n self.tmp = tempfile.TemporaryFile()\n self.tarfile = tarfile.open( fileobj=self.tmp, mode='w:' )\n self.tarfile.add( path, '.' )\n self.tarfile.close()\n self.tmp.flush()\n self.tmp.seek(0)\n self.tarfile = tarfile.open( fileobj=self.tmp, mode='r:' )\n</code></pre>\n\n<p>tarfile() will take a fileobj in the constructor instead of a name, so as long as you don't close it, and instead just seek() to 0 when you want to re-read it, you should be good.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T13:49:08.297", "Id": "10491", "ParentId": "8557", "Score": "2" } } ]
{ "AcceptedAnswerId": "10491", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:32:27.797", "Id": "8557", "Score": "3", "Tags": [ "python" ], "Title": "Using temporary file as backing object for a tarfile" }
8557
<p>First of all, I apologize for the length of this but I'm trying to show the data I'm working with and that I attempted to figure it out on my own.</p> <p>I'm building a social site for musicians. I would like to take the whole list of songs from the database and rank each one based on its relevancy to the logged in user. One reason for this is that I'd like there to always be 10 songs recommended, even if the user signed up 45 seconds ago. </p> <p>The factors I'm using are:</p> <ul> <li>The band members of songs (all would be members of the site, might have all quit the song)</li> <li>The logged in user's member connections (may be none)</li> <li>The most recent update in the song (will at least be the day the song was "created")</li> <li>The (sub)genre of the song (will always be set)</li> <li>The (sub)genre of the user (will always be set)</li> </ul> <p>The (sub)genres belong to more general genres, so I figure I can either weight a song higher if the logged in user and the song's (sub)genre are the same, or a little less higher if they at least belong to the same general genre.</p> <p>I'm not sure if I should be aiming for an Apriori or Bayesian algorithm... It seems to be somewhere in between. I have a couple of lines borrowed from explanations of the Hacker News algorithm that I've tweaked. I'm not quite sure how to put the final results together to get my ranking.</p> <p>Here's the code I've written so far (for all intents and purposes, <em>a studio is a song</em>). I know queries in loops like this are never a good idea, but I've done it this way because there's some memcaching schemes I use and this will probably also be batched:</p> <pre><code>function studio_relevance($user_id, $user_genre) { global $cxn; //MySQL connection $query = "SELECT * FROM studio WHERE project_status='active'"; $result = mysqli_query($cxn, $query) or die($query.': '.mysqli_error($cxn)); $data = array(); while ($studio = mysqli_fetch_object($result)) { //Find similarities in social connections and band $query_b = "SELECT * FROM band WHERE studio_id=".$studio-&gt;studio_id; $result_b = mysqli_query($cxn, $query_b) or die($query_b.': '.mysqli_error($cxn)); $the_band = array(); while ($people = mysqli_fetch_array($result_b, MYSQLI_ASSOC)) { $the_band[] = $people['user_id']; } $studio_band_count = count($the_band); $query = "SELECT * FROM idols WHERE friend_id=".$user_id; $result_b = mysqli_query($cxn, $query_b) or die($query_b.': '.mysqli_error($cxn)); $idol = array(); while ($people = mysqli_fetch_array($result_b, MYSQLI_ASSOC)) { $idol[] = $people['artist_id']; } $same_band = array_intersect($the_band, $idol); $same_band_count = count($same_band); ######## $similar_band = $same_band_count / $studio_band_count; ######## //Find the most recent activity $query_b = "SELECT * FROM studio_feed WHERE studio_id=".$studio-&gt;studio_id." ORDER BY feed_id DESC LIMIT 1"; $result_b = mysqli_query($cxn, $query_b) or die($query_b.': '.mysqli_error($cxn)); $tab = mysqli_fetch_object($result_b); $time_diff = strtotime('now') - strtotime($tab-&gt;timestamp); $hours = $time_diff / 3600; ######## $last_activity = pow(($hours+2), 1.8); ######## //Compare genres $genre_weight = 1; if ($studio-&gt;songGenre == $user_genre) { $genre_weight = 3; } else { $query_b = "SELECT * FROM genres"; $result_b = mysqli_query($cxn, $query_b) or die($query_b.': '.mysqli_error($cxn)); $genres = array(); $user_genre_cat = 0; while ($genre = mysqli_fetch_object($result_b)) { $genres[$genre-&gt;genre_cat][] = $genre-&gt;genre_id; if ($genre-&gt;genre_id == $user_genre) { $user_genre_cat = $genre-&gt;genre_cat; } } if (in_array($studio-&gt;songGenre, $genres[$celeb_cat])) { $genre_weight = 2; } } //Find final result //$final = $similar_band + $last_activity + $genre_weight; //$hours / pow(($similar_band+2), $genre_weight); } return $data; } </code></pre> <p>Any suggestions would be greatly appreciated! Am I on the right track or going about this all wrong?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T16:04:26.823", "Id": "13366", "Score": "0", "body": "What is `$cxn`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T16:22:38.700", "Id": "13368", "Score": "0", "body": "It's the MySQL database connection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T16:26:27.963", "Id": "13369", "Score": "0", "body": "I'm assuming it was created with `mysqli_connect()` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T16:29:28.173", "Id": "13370", "Score": "0", "body": "Correct! It was created in a master config file and all queries not returned by memcache use it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T08:37:38.937", "Id": "13412", "Score": "0", "body": "Long functions are usually a code smell. They indicate you're trying to do too much in one go where the problem you're trying to solve can be further subdivided (and therefore bits of it reused, the bits in isolation understood better, etc). A good rule of thumb is you should be able to fit an entire function on screen in your IDE without scrolling." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T17:04:47.510", "Id": "13451", "Score": "0", "body": "All the queries inside the function were in separate functions, but I mocked this up to show all the data. I was really just trying to find out how to do the weighted average/apriori/Bayesian math!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T20:38:50.770", "Id": "15269", "Score": "0", "body": "If you want to use a learning algorithm, then I think you're not really asking for a review. Do you know about [Cross Validated](http://stats.stackexchange.com/)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T14:57:55.220", "Id": "15486", "Score": "0", "body": "No, but thank you for pointing it out. I tried the math.stackexchange.com site as well." } ]
[ { "body": "<p>Your function is way too long. This is a lot going on in one function and very likely has some good candidates for smaller, single-purpose functions to be abstracted out of it. This is very likely the first thing that I would work on, it would make the flow of your function a little better and would likely make your function a lot easier to read.</p>\n\n<p>I also noticed that you are highly susceptible to <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow\">SQL injection</a> attacks. You should be, at the very least, escaping the user input before you put it into the database and would be even better if you decided to use prepared statements. I put in a code example below that details how you would go about changing one of your queries to use prepared statements.</p>\n\n<hr>\n\n<p>We'll be swapping over to using <a href=\"http://en.wikipedia.org/wiki/Prepared_statement\" rel=\"nofollow\">prepared statements</a> so you need to make sure that you have the <a href=\"http://www.php.net/manual/en/book.mysqlnd.php\" rel=\"nofollow\">mysqlnd extension</a> properly installed.</p>\n\n<pre><code>function getPreparedStatement($sql, array $parameters = array()) {\n global $cxn;\n\n if (!is_string($sql)) {\n trigger_error('The SQL query passed must be in the form of a string.', E_USER_WARNING);\n return false;\n }\n\n $stmt = mysqli_prepare($cxn, $sql);\n if (!$stmt) {\n trigger_error(mysqli_error($cxn), E_USER_WARNING);\n return false;\n }\n\n // we are subtracting 1 from this because the parameters passed should include the \n // 'xxx' string denoting data type\n $numPassedParameters = count($parameters) - 1;\n $stmtParamCount = mysqli_stmt_param_count($stmt);\n\n if ($stmtParamCount !== $numPassedParameters) {\n trigger_error('The number of parameters passed must match the number of parameters in the statement.', E_USER_WARNING);\n return false; \n }\n\n if ($stmtParamCount &gt; 0) {\n $dataTypes = array_shift($parameters);\n $refArray = array();\n $refArray[] = $cxn;\n $refArray[] = $datatypes;\n // we are doing this because mysqli_stmt_bind_param is expecting a reference\n foreach ($parameters as $key =&gt; $value) {\n $refArray[] =&amp; $parameters[$key];\n }\n\n return call_user_func_array('mysqli_stmt_bind_param', $refArray));\n } else {\n return $stmt;\n }\n\n}\n</code></pre>\n\n<p>So, as an example of using this new function to get a prepared statement:</p>\n\n<pre><code>$query_b = \"SELECT user_id FROM band WHERE studio_id=?\";\n$query_b_parameters = array('i', $studio-&gt;studio_id); // assume this int change 'i' to 's' if a string\n$stmt_b = getPreparedStatement($query_b, $query_b_parameters);\n$result_b = mysqli_stmt_execute($cxn, $stmt_b);\nif (!$result_b) {\n trigger_error(mysqli_error($cxn));\n return false;\n}\n\n$the_band = array();\nwhile ($people = mysqli_fetch_array($result_b, MYSQLI_ASSOC)) {\n $the_band[] = $people['user_id'];\n}\n</code></pre>\n\n<p>So, now you're using prepared statements for this query and it is not as susceptible to SQL injection. Also, notice that I explicitly defined that I only want <code>user_id</code> from the query and not all the things. You should be able to figure out from there how to replace the other SQL queries with prepared statements.</p>\n\n<hr>\n\n<p>Some other things that I've noticed:</p>\n\n<ul>\n<li>Under <code>$query</code> you have <code>$result_b</code> again and are requerying <code>$query_b</code>. Likely you meant to just send <code>$query</code></li>\n<li>Not necessarily an error but the <code>*</code> in SQL statements. If you aren't really getting all the data try to explicitly state what you want.</li>\n<li>Try to find a way to abstract getting the results from a query in the form of an array or an object into a couple functions that take a <code>mysqli_stmt</code> and returns the appropriate data type for the result.</li>\n<li>Try to abstract out the business logic of comparing genres and finding the most recent activity into different functions so that your main function here simply controls the order in which queries get executed and then passes the appropriate queries off to functions that get the right data.</li>\n</ul>\n\n<p>There's some things that could be done to make the function more maintainable and duplication but I think the priority right now is swapping over to prepared statements and getting rid of your SQL Injection vulnerability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T18:12:14.583", "Id": "13373", "Score": "0", "body": "Thank you for your help. I really appreciate it. I should probably just point out first that I do have functions for a lot of those queries, I just replaced the functions with some of the actual code to show what was going on. I also am working on data that has already been cleaned with trim, strip_tags, and mysqli_escape_string, or that is coming directly from the database. \n\nI posted this here hoping to get some help more on getting to the final, weighted result rather than the actual code itself. I was a bit rudely told my post was too long on StackOverflow and to come over here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T14:56:00.727", "Id": "15485", "Score": "0", "body": "I will accept it, but I need to state it does not address my original post. I was looking for help with algorithms. My code was completely pseudocode. I clearly stated that my example was showing the data I was working with. I had merged the contents of several functions for demonstration. Luckily, I figured out a solution for recommendation ranking elsewhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T04:51:13.703", "Id": "15648", "Score": "0", "body": "@grandcameo Ultimately a code review is just that...a review of the code presented. Any specific performance issues are completely conceptual. What you posted *is not* psuedocode, it looks much more like a full-blown implementation. That being said, if you feel my review didn't adequately answer your question then please do not accept it :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T18:01:40.370", "Id": "8566", "ParentId": "8559", "Score": "2" } } ]
{ "AcceptedAnswerId": "8566", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:46:59.053", "Id": "8559", "Score": "3", "Tags": [ "php", "algorithm" ], "Title": "Personalized, weighted recommendations - Rank all content with PHP" }
8559
<p>Some time ago I wrote a small routine to run some quick n' dirty queries (and with that I mean it is not used for large queries) against an Oracle DB, but also wanted to do it a bit easier to parse errors.</p> <pre><code># Executes the query # # Will execute a query contained in the variable named # in the parameter $4 and store the result in the variable # named in $5. # In case of errors (even SQL related) the function should # exit with status 1, making it possible to "if execQuery". # # @param $1 = User # $2 = Pasword # $3 = Tns Alias # $4 = Name of the variable containing the query # $5 = Name of the variable to hold the result # # @return query execution status function execQuery { typeset eSQLU=$1 typeset eSQLP=$2 typeset eSQLS=$3 typeset etQUERY=$4 eval typeset eQUERY=\$$etQUERY typeset eQRES=$5 logMessageFile "DEBUG" "Query: $eQUERY" typeset res=$(sqlplus -s $eSQLU/$eSQLP@$eSQLS &lt;&lt;EOF set echo off newpage 0 space 0 pagesize 0 feed off head off verify off lines 999 WHENEVER SQLERROR EXIT 1 $eQUERY exit; EOF ) [[ $? -gt 0 ]] &amp;&amp; return 1 || eval "$eQRES=\"$res\"" } </code></pre> <p>The idea of this function is that later I could do something like:</p> <pre><code>query="select sysdate from dual;" if execQuery $RAID_APP_PI_USR $RAID_APP_PI_PWD $RAID_APP_PI_SID query result ; then echo $result logMessageFile "INFO" "Inserts into XX successful." else logMessageFile "ERROR" "Error insertando XXX." fi </code></pre> <p>It kinda works. A properly written query will do it fine, and the result variable is all correctly evaluated and all. The problem are the errors. If the query in that example was something like <code>select * potato potato;</code>, It'd still not yield the correct return value thus missing the error test.</p> <p>I'm not particularly good with SQL*Plus nor ksh and am probably just missing something obvious. Could someone lend me a hand here?</p>
[]
[ { "body": "<p>It seems like you might find this clause helpful:</p>\n\n<pre><code>WHENEVER SQLERROR EXIT SQL.SQLCODE\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-07T17:51:24.013", "Id": "40108", "Score": "0", "body": "That was actually what I did. Didn't even remember I had this question. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T21:40:30.183", "Id": "25708", "ParentId": "8563", "Score": "2" } } ]
{ "AcceptedAnswerId": "25708", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T16:44:35.527", "Id": "8563", "Score": "3", "Tags": [ "sql", "oracle", "ksh" ], "Title": "Parsing Oracle errors with a ksh function" }
8563
<p>I'm a zeromq newb and have implemented the REQ/RES Lazy Pirate pattern with C#. It's essentially a port from the C example given in the documentation. It's harnessed by tests, and seems to be work to my expectations. I'm interested to know if I'm understanding the pattern correctly, or if I can improve the API. If anyone knows of a pre-existing solution, I'd love to know too. Any advice would be great. </p> <pre><code>using System; using System.Text; using ZMQ; namespace zeromq.net { public class LazyPirateClient : ReqRes { private readonly string _address; private readonly long _timeOut; private readonly int _retries; private bool _responseReceived; private int _attempt; public LazyPirateClient(string address, long timeOut, int retries) { _address = address; _timeOut = timeOut; _retries = retries; } public override void Send(Func&lt;byte[]&gt; byteProvider) { _responseReceived = false; using (var context = new Context(1)) { _attempt = 0; do { using (var requester = context.Socket(SocketType.REQ)) { _attempt++; requester.Connect(_address); requester.Send(byteProvider(), SendRecvOpt.NOBLOCK); var item = requester.CreatePollItem(IOMultiPlex.POLLIN); item.PollInHandler += item_PollInHandler; context.Poll(new[] { item }, _timeOut); requester.Linger = 0; } } while (_attempt &lt; _retries &amp;&amp; !_responseReceived); if (!_responseReceived) throw new PermenantFailException(_attempt); } } private void item_PollInHandler(Socket socket, IOMultiPlex revents) { _responseReceived = true; var bytes = socket.Recv(SendRecvOpt.NOBLOCK); OnReceived(new ResponseReceivedEventArgs(bytes, _attempt)); } } public abstract class ReqRes { public abstract void Send(Func&lt;byte[]&gt; byteProvider); public delegate void ResponseReceived(object sender, ResponseReceivedEventArgs e); public event ResponseReceived ReceivedHandler; public void OnReceived(ResponseReceivedEventArgs e) { var handler = ReceivedHandler; if (handler != null) handler(this, e); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-06T13:59:57.853", "Id": "13618", "Score": "0", "body": "Minor improvement, in c# class properties use `PascalCase`. So you would have `Address`, `Timeout`, `ResponseReceived`, etc. You also have a typo in `PermanentFailException`." } ]
[ { "body": "<p>It seems zeromq will release sent data itself. With GC supported in C#, this feature is useless. The <code>byteProvider</code> parameter seems inappropriate, so why not just use <code>IEnumerable&lt;byte&gt;</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-07T16:22:00.257", "Id": "13689", "Score": "0", "body": "The motivation for a byteProvider is if you need to regenerate a message on each attempt. For example, if you need to regenerate a timestamp, or id in the message. There is a version (not shown here) that has an overload for IEnumerable<byte> such that:\n\n\n public override void Send(IEnumerable<byte> bytes) {\n Send(() => bytes);\n }\n\nUsing the byteProvider is not the vanilla case, but is there in case you need it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T03:43:53.737", "Id": "13724", "Score": "0", "body": "The send operation is asynchronous in zeromq, so when send() return, it doesn't mean the data has been sent. I didn't find asynchronous action in your send() method, do you provide another SendAsync()? And if the operation is asynchronous, then, use func<byte[]> as parameter is not proper - the send action will be executed on another thread any other time, if you invoke the func<byte[]> that time, you should have to guarantee the resources referenced in func<byte[]> are still available." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T03:43:59.573", "Id": "13725", "Score": "0", "body": "One thing I have met just like what you done, and in the delegate I referenced an autowaitevent, the program crashed sometime - The autowaitevent might be disposed when I call it in asynchronously delegate. In order to enhance the stability of program, I suggest IEnumerable<byte>." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-07T03:22:06.927", "Id": "8727", "ParentId": "8564", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T17:11:11.543", "Id": "8564", "Score": "5", "Tags": [ "c#", "zeromq" ], "Title": "Lazy Pirate Request Response pattern using zeromq and C#/.NET bindings" }
8564
<p>This is a question regarding design of a service or business logic layer that returns or exposes messages meaningful to the user.</p> <p><code>RegisterUser</code> method that takes a user. What should it return? Should it always return</p> <ul> <li>a Service Information object?</li> <li>a newly created user?</li> <li>a boolean, and based on the result, you can interrogate this service's error messages?</li> </ul> <p></p> <pre><code>public bool RegisterUser(User user) { if (String.IsNullOrEmpty(user.EmailAddress) || !user.EmailAddress.IsValidEmailAddress()) { AddMessage(new Message { Description = "Invalid Email Address", Success = false }); } if (String.IsNullOrEmpty(user.Password)) { AddMessage(new Message { Description = "Password is Required", Success = false }); } return Messages.Count == 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-21T17:55:24.650", "Id": "73036", "Score": "0", "body": "This question appears to be off-topic because it is about design and not a code review." } ]
[ { "body": "<p>The problem with returning a message like this is that you are \"hard coding\" the messages in the registration method. If you want to add localization (i.e. return a message in the users language as determined by the culture setting of the client) to the application later it will be much harder. A cleaner approach would be to use custom exceptions and exception handling. For example, if the an invalid email address is entered then a <code>InvalidEmailException</code> would be thrown by the <code>RegisterUser</code> method. The part of the application that calls the <code>RegisterUser</code> method would determine what to present to the user for this type of exception or to percolate it up higher in the application for handling. This is a cleaner separation of concerns of handling exceptions in the application from what is presented to the user. This also promotes reuse because different users of the method may want to handle it differently.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T18:20:45.343", "Id": "13374", "Score": "0", "body": "although I am happy with your solution, I personally think that throwing exceptions is bad practise and exceptions should only be thrown in exceptional cases. It's not exceptional that a user might enter an incorrect email address." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T18:21:07.853", "Id": "13375", "Score": "0", "body": "I however concur with your localization issue. Thank you for that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T18:42:06.220", "Id": "13381", "Score": "1", "body": "I guess we agree to disagree then. Google InvalidPasswordException and see how many libraries use exception handling for authentication processing. Using exceptions for these scenarios is not a bad practice at all for the reasons I spell out in my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T03:23:39.920", "Id": "13402", "Score": "0", "body": "Kevin, thanks once again for the answer, much appreciated, it seems to be the most common solution to this kind of problem" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T18:17:17.577", "Id": "8567", "ParentId": "8565", "Score": "2" } } ]
{ "AcceptedAnswerId": "8567", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T17:13:25.037", "Id": "8565", "Score": "1", "Tags": [ "c#" ], "Title": "Designing a service/business logic layer that returns useful/consistent messages" }
8565
<p>Here's what I have at the moment. Any ideas for improving on this?</p> <pre><code>public static Snapshot[] GetSnapshots() { var arrayedSnapshot = new { Id = Enumerable.Range(1, 9), ScenarioTimeInSeconds = new[] { 0, 0, 0, 60, 60, 60, 120, 120, 120 }, BearingInDegrees = new[] { 0, 120, 220, 0, 120, 220, 0, 120, 220}, RangeInNauticalMiles = new[] { 0, 1, 1, 0, 1, 1, 0, 1, 1 }, CourseInDegrees = new[] { 90, 90, 90, 90, 90, 180, 90, 90, 90 }, SpeedInKnots = Enumerable.Repeat(7, 9), XCoordinate = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, YCoordinate = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; return arrayedSnapshot.Id .Select((td, index) =&gt; new Snapshot { Id = arrayedSnapshot.Id ElementAt(index), ScenarioTimeInSeconds = arrayedSnapshot.ScenarioTimeInSeconds.ElementAt(index), BearingInDegrees = arrayedSnapshot.BearingInDegrees.ElementAt(index), RangeInNauticalMiles = arrayedSnapshot.RangeInNauticalMiles.ElementAt(index), CourseInDegrees = arrayedSnapshot.CourseInDegrees.ElementAt(index), SpeedInKnots = arrayedSnapshot.SpeedInKnots.ElementAt(index), XCoordinate = arrayedSnapshot.XCoordinate.ElementAt(index), YCoordinate = arrayedSnapshot.YCoordinate.ElementAt(index), }) .ToArray(); } </code></pre> <p><strong>Edit</strong></p> <p>Here is a new version based on Anton Golov's answer:</p> <pre><code>public static IEnumerable&lt;Snapshot&gt; GetSnapshots() { for (var i = 0; i &lt; 9; i++) { yield return new Snapshot { Id = i + 1, ScenarioTimeInSeconds = new[] { 0, 0, 0, 60, 60, 60, 120, 120, 120 }[i], BearingInDegrees = new[] { 0, 120, 220, 0, 120, 220, 0, 120, 220 }[i], RangeInNauticalMiles = new[] { 0, 1, 1, 0, 1, 1, 0, 1, 1 }[i], CourseInDegrees = new[] { 90, 90, 90, 90, 90, 180, 90, 90, 90 }[i], SpeedInKnots = new[] { 7, 7, 7, 7, 7, 7, 7, 7, 7 }[i], XCoordinate = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }[i], YCoordinate = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }[i] }; } } </code></pre> <p>This seems a lot more elegant than my original.</p>
[]
[ { "body": "<p>As far as I can see, most of your data is fairly predictable. What about:</p>\n\n<pre><code>for (int i = 0; i &lt; 9; ++i)\n{\n int scenarioTimeInSeconds = 60*(i/3); // Intentional loss of fractional part\n int bearingInDegrees = (i % 3) * 120; // It's now 0, 120, 240\n int rangeInNauticalMiles = (i % 3 == 0) ? 0 : 1;\n int courseInDegrees = (i == 5) ? 180 : 90;\n yield return new Snapshot\n {\n Id = i + 1,\n ScenarioTimeInSeconds = scenarioTimeInSeconds,\n BearingInDegrees = bearingInDegrees,\n RangeInNauticalMiles = rangeInNauticalMiles,\n CourseInDegrees = courseInDegrees,\n SpeedInKnots = 7,\n XCoordinate = 0,\n YCoordinate = 0,\n };\n}\n</code></pre>\n\n<p>This already seems more readable to me. Now you can split the logic that makes the values for the various local <code>int</code>s off into separate functions and document each one. In order to do it this way, you do have to have <code>GetSnapshots</code> return an <code>IEnumerable&lt;Snapshot&gt;</code>, but that makes sense anyway -- and if you really want them as an array, just call <code>ToArray()</code> on it outside the function (i.e. <code>GetSnapshots().ToArray()</code>).</p>\n\n<p>Even if you'd rather not do that, you should still change numbers that are used multiple times (in your case: 60, 90, 120, 180, 220) into named constants, unless they're entirely unrelated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T02:23:42.220", "Id": "13399", "Score": "0", "body": "+1, thanks. Great idea using `yield` (although I think it needs to be `yield return new Snapshot...`). I think I still prefer typing the lists out, though, because it's helpful for me to see the actual numbers in order when writing tests. See my edit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T02:36:07.093", "Id": "13400", "Score": "0", "body": "@DanM: Indeed, too much Python for me. To be honest, I find your original version to be cleaner than the new one, as it's not entirely clear what's happening. I would use `operator[]` instead of `ElementAt` if possible (surely there's some way to keep those variables arrays?), but if you insist on keeping those lists, I'm not sure how much can be done about it. (You can still use yield with `foreach` over `arrayedSnapshot.Id`, though, which may improve matters a little -- that LINQ query is really ugly, in my opinion.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T03:10:33.987", "Id": "13401", "Score": "0", "body": "I see your point, but the advantages of less typing and being able to quickly see the progression of values for each property are pretty compelling to me. I think once you get the hang of how the indexing works, it wouldn't be too hard to decipher, but I don't know. Anyway, thanks for your help." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T00:39:41.203", "Id": "8575", "ParentId": "8569", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T20:32:07.527", "Id": "8569", "Score": "4", "Tags": [ "c#" ], "Title": "Seeking a quick and dirty way to populate a list of entities for testing purposes" }
8569
<p>I know there is a lot of libraries with this built in <code>$.get()</code> etc... but as for writing this in pure JavaScript how does this look?</p> <pre><code>var get_request; ajaxRequest(function() { var activexmodes, i, _i, _len, _ref, _results; activexmodes = ['Msxm12.XMLHTTP', 'Microsoft.XMLHTTP']; if (window.ActiveXObject) { _ref = activexmodes.length; _results = []; for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) { i = _ref[_i]; try { _results.push(new ActiveXObject(activexmodes[i])); } catch (_error) {} } return _results; } else if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else { return false; } }); get_request = new ajaxRequest(); </code></pre>
[]
[ { "body": "<p>There are a couple issues with this code:</p>\n\n<ol>\n<li><p>You don't define a function in Javascript with <code>ajaxRequest(function() { ... });</code> What you're doing there is calling function <code>ajaxRequest</code> and passing an anonymous function into it as the only parameter. It will throw a JS error as it is now, because <code>ajaxRequest</code> isn't defined.</p>\n\n<p>To define an <code>ajaxRequest</code> function, you would do either <code>function ajaxRequest() { ... }</code> or <code>var ajaxRequest = function() { ... };</code>.</p></li>\n<li><p>This code snippet:</p>\n\n<pre><code>activexmodes = ['Msxm12.XMLHTTP', 'Microsoft.XMLHTTP'];\n_ref = activexmodes.length;\n\nfor (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {\n i = _ref[_i];\n</code></pre>\n\n<p>will also throw a JS error because you're treating <code>_ref</code> like an <code>Array</code> when it's actually a <code>Number</code>. I'm guessing you meant to use <code>activexmodes</code> instead. <code>_ref</code> is completely unnecessary.</p></li>\n<li><p>Why do you declare all your variables at the very top of the function? It's bad practice because declaring your variables when you first need them tells anyone who reads your code that \"this is the first time I'm using this variable.\" If you declare them all at the top, anyone else who reads it has to search through to make sure it's not used or modified anywhere else. (In this case it's harmless, but in larger functions it can become and issue.)</p></li>\n<li><p>To use the function, you should call it directly instead of using <code>new</code>:</p>\n\n<pre><code>var get_request = ajaxRequest(); // probably should be named getX(),\n // like getAJAXRequest()\n</code></pre></li>\n<li><p>I would be careful about returning <code>false</code> from the function. If that's a known return value and you're going to check for it everywhere you use it, then that's okay. But if you forget to support that rare case, the user will get some cryptic JS error somewhere down the line when you try to call <code>get_request.open()</code> or some other function.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T20:15:39.227", "Id": "8636", "ParentId": "8571", "Score": "3" } } ]
{ "AcceptedAnswerId": "8636", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T21:56:08.917", "Id": "8571", "Score": "2", "Tags": [ "javascript", "ajax" ], "Title": "AJAX call in JavaScript" }
8571
<p>I'm working on a jQuery plugin for a client. Instead of finding one that was already out there I wanted to practice writing plugins since I hadn't in awhile. This plugin grabs all the images in a UL, creates a overlay for the page, and puts them in a image zoomer that gets opened when a user clicks on a thumbnail image that is also generated by the plugin. </p> <p>You can see that I have some issues deciding where to put functions, some are inside the plugin function, others are inside the IIFE but outside of the plugin. I'd also like to know if there are any best practices or optimizations that I can put into this code. I'm aware of a few small bugs with the animation as well. </p> <p>I tried to put a working copy of this on jsfiddle or jsbin but the popup doesn't render properly. <a href="http://jsfiddle.net/bittersweetryan/sEXMY/" rel="nofollow">http://jsfiddle.net/bittersweetryan/sEXMY/</a> There is a working copy on the github repo though, just download the zip and open index.html from here <a href="https://github.com/bittersweetryan/YADI" rel="nofollow">https://github.com/bittersweetryan/YADI</a></p> <pre><code>(function( $, undefined ){ $.fn.imagezoom = function(base, options){ var $this = $(this), defaults = { width : 700, height : 500, previewHeight: 50, previewDivWidth: 200, thumbsWidth: 0, imagePath: 'images' }, $stageDiv = createDiv(), $pictureFrame = null, $overlay = getOverlay(), $preview = null, arrowsLoaded = false, $thumbs = null; if(typeof options === 'object'){ options = $.extend({},defaults,options); } else{ options = defaults; } //cache variables that point to the zoom elements $pictureFrame = getPictureFrame(options); $preview = getPreview(options); $thumbs = getThumbs(); $("body").append($stageDiv); //if no images were found in the li passed in return if($this.find('li&gt;img').length === 0){ $.error("No images were found under the root element."); } //remove the ul that has the images from the DOM $this.remove(); //loop through images and process each one $this.find('li&gt;img').each(processImage); $pictureFrame.prepend($thumbs); var close_left = parseInt($pictureFrame.css("left"),10) + options.width; var close_top = parseInt($pictureFrame.css("top"),10) - 10; //add the close link $pictureFrame.find("#iz_close &gt; a").click(function(){ $pictureFrame.animate({height:0},function(){ $(this).animate({width:0},function(){ $pictureFrame.hide(); $overlay.fadeOut(); }); }); }).end().find("#iz_close").css({"left": close_left , "top": close_top}). hide(); //hide the objects $pictureFrame.hide(); $overlay.hide(); $pictureFrame.width(0).height(0); $preview.append(getLink()); base.append($preview); $("body").append($pictureFrame).append($overlay); //inner functions, these use vars nested in the plugin function processImage(){ var $span = $('&lt;span&gt;&lt;/span&gt;'), $thumb = $(this), $newImg = $thumb.clone().height(options.height - 100), $previewImg = $thumb.clone().height(options.previewHeight); $thumb.mouseover(function(){ $thumb.css("cursor","pointer"); }); $thumb.height(100); $thumb.click(function(){ $("#iz_main").find("img").remove().end().append($newImg); }); $previewImg.click(function(){ show($overlay,$pictureFrame,options); }). hover(function(){ $(this).css({"cursor" : "pointer"}); }); $span.append($thumb); $preview.append($previewImg); var $stagingImage = $thumb.clone(); $stagingImage.load(function(){ options.thumbsWidth += $(this).get(0).clientWidth; //add the arrows if(options.thumbsWidth &gt; options.width &amp;&amp; !arrowsLoaded){ $rightArrow = createArrow('right'); $leftArrow = createArrow('left'); $pictureFrame.append($rightArrow).append($leftArrow); $pictureFrame.find(".arrow").bind("mouseover", function(){ if($(this).hasClass("right_arrow")){ scrollRight($thumbs); } else{ scrollLeft($thumbs); } }); arrowsLoaded = true; } }); $stageDiv.append($stagingImage); $thumbs.append($span); } function scrollRight($target){ return scroll($target,'right'); } function scrollLeft($target){ return scroll($target,'left'); } function scroll($target, direction){ var scrollAmount = 0; var currentPos = parseInt($target.css("right"),10); if(direction === 'left' &amp;&amp; (isNaN(currentPos) || currentPos &lt;= 0)){ console.log(currentPos); return false; } else if(direction === 'right' &amp;&amp; currentPos + options.width &gt; options.thumbsWidth){ return false; } if(isNaN(currentPos)){ scrollAmount = (direction === 'right') ? 100 : -100; } else{ scrollAmount = (direction === 'right') ? currentPos + 100 : currentPos - 100; } $target.stop().animate({"right": scrollAmount},{ "duration": 200, "easing": "linear" }); var to = setTimeout(function(){ scroll($target,direction); },200); } function getLink(){ var $link = $('&lt;div&gt;&lt;a href="#"&gt;Detailed Images&lt;/a&gt;&lt;/div&gt;'); $link.click(function(){ show($overlay,$pictureFrame,options); }); return $link; } return $this; }; function createArrow(direction){ return $('&lt;div class="arrow ' + direction + '_arrow"&gt;&amp;nbsp;&lt;/div&gt;'); } function show($overlay,$pictureFrame,options){ $overlay.fadeIn('slow',function(){ $pictureFrame.height(0); $pictureFrame.find("#iz_main &gt; img").remove(); $pictureFrame.find("#iz_thumbs &gt; span").find("img").eq(0).click(); $pictureFrame.find("#iz_thumbs").width(options.thumbsWidth); $pictureFrame.show(); $pictureFrame.animate({width: options.width},function(){ $pictureFrame.animate({height: options.height},function(){ $pictureFrame.find("#iz_thumbs").slideDown('slow',function(){ $pictureFrame.find("#iz_close").show(); }); }); }); }); } function getOverlay(){ return $('&lt;div class="zoom_overlay" id="iz_overlay"&gt;&amp;nbsp;&lt;/div&gt;'); } function getPreview(argument){ return $('&lt;div class="zoom_preview"&gt;&lt;/div&gt;'); } function getPictureFrame(options){ var $pictureFrame = $('&lt;div class="zoom_pictureFrame" id="iz_pictureFrame"&gt;&lt;div class="zoom_close" id="iz_close"&gt;&lt;a href="#"&gt;&lt;img src="' + options.imagePath + '/close.png"&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="zoom_main" id="iz_main"&gt;&lt;/div&gt;&lt;/div&gt;'), height = $(window).height(), width = $(document).width(); $pictureFrame.css({ 'left' : width/2 - (options.width/2), 'top' : height/2 - (options.height/2) }). width(options.width); return $pictureFrame; } function getThumbs(){ return $('&lt;div class="zoom_thumbs" id="iz_thumbs"&gt;&lt;/div&gt;'); } function createDiv(){ return $('&lt;div id="staging"&gt;&lt;/div&gt;').appendTo("body"); } })(jQuery); </code></pre>
[]
[ { "body": "<p><strong>Little Stuff</strong></p>\n\n<ul>\n<li>One line functions that are only used once such as <code>scrollLeft</code> and <code>scrollRight</code> should get inlined.</li>\n<li>Functions that create divs like <code>getThumbs</code> could be called <code>createThumbs</code> instead</li>\n<li>To your point, there is no good reason to have any functions outside of <code>$.fn.imagezoom = function(base, options){</code></li>\n<li>There are quite a few references to <code>10</code> and <code>100</code> and <code>200</code>, these numbers should be replaced with properly named constants</li>\n<li>You could bind the <code>mouseover</code> of the arrows straight to <code>$rightArrow</code> and <code>$leftArrow</code> instead of using <code>find(\".arrow\")</code> and checking the class.</li>\n</ul>\n\n<p><strong>Bigger picture</strong></p>\n\n<p>I think you need functions that group the following functionalities:</p>\n\n<ul>\n<li>Creation and setting up of <code>thumb</code> </li>\n<li>Creation and setting up of <code>pictureFrame</code> </li>\n<li>Creation and setting up of <code>overlay</code> </li>\n<li>Creation and setting up of <code>preview</code> </li>\n</ul>\n\n<p><strong>JsHint</strong></p>\n\n<ul>\n<li><code>$rightArrow</code> and <code>$leftArrow</code> are set without <code>var</code></li>\n<li><code>getPreview</code> does not use <code>argument</code> ( <code>argument</code> is not a terribly descriptive name btw)</li>\n<li>There is no need to capture the value of <code>setTimeout</code> into <code>var to</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:16:38.527", "Id": "40263", "ParentId": "8573", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T00:15:36.647", "Id": "8573", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "jQuery Plugin for Detailed images" }
8573
<p>This works but feels like alot of code for what it accomplishes. I feel like I'm maybe missing something obvious.</p> <pre><code>// When current month is same as target month, then return the current day of the month. // Else return the number of days in the target month. static int DefaultDaysToSynch() { var now = DateTime.Now; int result = now.Day; int month = Properties.Settings.Default.StatsMonth; int year = Properties.Settings.Default.StatsYear; if (!((year == now.Year) &amp;&amp; (month == now.Month))) { result = DateTime.DaysInMonth(year, month); } return result; } </code></pre>
[]
[ { "body": "<p>It is hard to improve on Jesse's answer (there are only so many ways to write this method), but I will add my alternative, which is a matter of style. I personally tend to not use <code>var</code> in place of any of the built-in types listed here: <a href=\"http://msdn.microsoft.com/en-us/library/ms228360(v=vs.90).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms228360(v=vs.90).aspx</a> it does not save me any more space than writing \"don't\" instead of \"do not\".</p>\n\n<p>I also do not like it when the lines get too long, particularly ones that involve the ternary operator, so here is my version (assuming <code>public</code> modifier):</p>\n\n<pre><code>public static int DefaultDaysToSynch()\n{\n int month = Properties.Settings.Default.StatsMonth;\n int year = Properties.Settings.Default.StatsYear;\n var now = DateTime.Now;\n bool isTargetMonth = (year == now.Year) &amp;&amp; (month == now.Month);\n return isTargetMonth ? now.Day : DateTime.DaysInMonth(year, month);\n}\n</code></pre>\n\n<p>In general I highly recommend runnign StyleCop and listening to it, except for the line <code>bool isTargetMonth = (year == now.Year) &amp;&amp; (month == now.Month);</code> - keep those parenthesis.\nBtw, I am pretty sure that the C# compiler can handle that <code>bool</code> variable efficiently. The descriptive variable name also reduces (though maybe not completely) the need for a comment.</p>\n\n<p>The comment would have to pass the StyleCop's standard if I wrote it out, but I am too lazy, sorry. There is not much to write really, because it does not take any arguments.</p>\n\n<p>I am not a huge fan of the input values being read directly from settings - it makes this function harder to test, it makes it less \"functional\" as in functional style, it also allows for bad input (such as year -2598, month # 455) to go unnoticed. I would rather pass both values into the function like so:</p>\n\n<pre><code>public static int DefaultDaysToSynch(int targetYear, int targetMonth)\n{\n CheckYear(targetYear);\n CheckMonth(targetMonth);\n var now = DateTime.Now;\n bool isTargetMonth = (targetYear == now.Year) &amp;&amp; (targetMonth == now.Month);\n return isTargetMonth ? now.Day : DateTime.DaysInMonth(year, month);\n}\n\n// You will need to catch this at the right place.\n// This is lengthy, I know, but makes a decent exception message.\nprivate static CheckMonth(int monthNumber)\n{\n if (monthNumber &gt;= 1 &amp;&amp; monthNumber &lt;= 12)\n {\n return;\n }\n\n string exceptionMessage = String.Format(\n \"Month number must be between 1 and 12 but it was {0}.\",\n monthNumber);\n\n throw new ArgumentOutOfRangeException(\n paramName: \"monthNumber\",\n actualValue: monthNumber,\n message: exceptionMessage);\n}\n\n// Similar implementation for CheckYear\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-07T04:06:23.467", "Id": "8728", "ParentId": "8578", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T04:19:39.913", "Id": "8578", "Score": "3", "Tags": [ "c#", "datetime" ], "Title": "Long calendar related function" }
8578
<pre><code>Image&lt;Bgr, Byte&gt; frame = _capture.QueryFrame(); Image&lt;Gray, Byte&gt; grayFrame = frame.Convert&lt;Gray, Byte&gt;(); grayFrame._EqualizeHist(); MCvAvgComp[][] facesDetected = grayFrame.DetectHaarCascade(_faces, 1.1, 1, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.FIND_BIGGEST_OBJECT, new Size(20, 20)); if (facesDetected[0].Length == 1) { MCvAvgComp face = facesDetected[0][0]; #region Search ROI based on Face Metric Estimation - Int32 yCoordStartSearchEyes = face.rect.Top + (face.rect.Height * 3 / 11); Point startingPointSearchEyes = new Point(face.rect.X, yCoordStartSearchEyes); Size searchEyesAreaSize = new Size(face.rect.Width, (face.rect.Height * 3 / 11)); Rectangle possibleROI_eyes = new Rectangle(startingPointSearchEyes, searchEyesAreaSize); #endregion int widthNav = (frame.Width / 10 * 2); int heightNav = (frame.Height / 10 * 2); Rectangle nav = new Rectangle(new Point(frame.Width / 2 - widthNav / 2, frame.Height / 2 - heightNav / 2), new Size(widthNav, heightNav)); frame.Draw(nav, new Bgr(Color.Lavender), 3); Point cursor = new Point(face.rect.X + searchEyesAreaSize.Width / 2, yCoordStartSearchEyes + searchEyesAreaSize.Height / 2); grayFrame.ROI = possibleROI_eyes; MCvAvgComp[][] eyesDetected = grayFrame.DetectHaarCascade(_eyes, 1.15, 3, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20)); grayFrame.ROI = Rectangle.Empty; if (eyesDetected[0].Length != 0) { frame.Draw(face.rect, new Bgr(Color.Yellow), 1); foreach (MCvAvgComp eye in eyesDetected[0]) { Rectangle eyeRect = eye.rect; eyeRect.Offset(possibleROI_eyes.X, possibleROI_eyes.Y); grayFrame.ROI = eyeRect; frame.Draw(eyeRect, new Bgr(Color.DarkSeaGreen), 2); frame.Draw(possibleROI_eyes, new Bgr(Color.DeepPink), 2); if (nav.Left &lt; cursor.X &amp;&amp; cursor.X &lt; (nav.Left + nav.Width) &amp;&amp; nav.Top &lt; cursor.Y &amp;&amp; cursor.Y &lt; nav.Top + nav.Height) { LineSegment2D CursorDraw = new LineSegment2D(cursor, new Point(cursor.X, cursor.Y + 1)); frame.Draw(CursorDraw, new Bgr(Color.White), 3); int xCoord = (frame.Width * (cursor.X - nav.Left)) / nav.Width; int yCoord = (frame.Height * (cursor.Y - nav.Top)) / nav.Height; Cursor.Position = new Point(xCoord, yCoord); } } } imageBoxFrame.Image = frame; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T12:15:24.893", "Id": "21206", "Score": "0", "body": "You could using bit-shifting instead of division by 2 / 2^x, though the compiler may do this optimisation anyway." } ]
[ { "body": "<p>I think your code is already quite good. My guess is that the calls to DetectHaarCascade are the majority of the time. Can you run a profiler on it? The <a href=\"http://eqatec.com/Profiler/\" rel=\"nofollow\">Equatec profiler</a> is free. As for the lower loop you could preallocate your colors (although I assume they're structs). Also, I don't see where possibleROI_eyes changes, so do you really need to draw that every time through the loop? Or is it drawing at the cursor position?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T04:19:05.573", "Id": "13108", "ParentId": "8580", "Score": "7" } } ]
{ "AcceptedAnswerId": "13108", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T04:51:14.757", "Id": "8580", "Score": "3", "Tags": [ "c#", ".net", "performance" ], "Title": "How do I make this C# code more efficient, in terms of FPS and time complexity?" }
8580
<p>I am developing a small compiler like tool. In the process, I wrote a <code>Class&lt;?&gt;</code> wrapper, <code>JavaClass</code>:</p> <pre><code>public class JavaClass { ... public List&lt;GenericEntry&gt; getAllGenericEntries() { return GenericEntriesFinder.getAllGenericEntries(this); } } </code></pre> <p>I've at first written the bellow shown code inside <code>JavaClass</code>, but I soon found it too big to mantain in <code>JavaClass</code>, that is already getting fat. I basically will only want to ever use <code>getAllGenericEntries()</code>, so all the other methods are basically implementation details.</p> <pre><code>public class GenericEntriesFinder { public static List&lt;GenericEntry&gt; getAllGenericEntries(JavaClass javaClass) { List&lt;GenericEntry&gt; result = new ArrayList&lt;GenericEntry&gt;(); result.addAll(getClassGenericEntries(javaClass)); result.addAll(getInterfaceGenericEntries(javaClass)); return result; } private static List&lt;GenericEntry&gt; getClassGenericEntries(JavaClass javaClass) { IJavaType genericSuperClass = javaClass.getGenericSuperclass(); JavaClass superClass = javaClass.getSuperClass(); return getGenericEntries(javaClass, Arrays.asList(genericSuperClass), Arrays.asList(superClass)); } private static List&lt;GenericEntry&gt; getInterfaceGenericEntries(JavaClass javaClass) { List&lt;IJavaType&gt; genericInterfaces = javaClass.getGenericInterfaces(); List&lt;JavaClass&gt; nonGenericInterfaces = javaClass.getInterfaces(); return getGenericEntries(javaClass, genericInterfaces, nonGenericInterfaces); } private static List&lt;GenericEntry&gt; getGenericEntries(JavaClass javaClass, List&lt;IJavaType&gt; generic, List&lt;JavaClass&gt; nonGeneric) { List&lt;GenericEntry&gt; result = new ArrayList&lt;GenericEntry&gt;(); for (int i = 0; i &lt; generic.size(); ++i) { IJavaType javaType = generic.get(i); JavaClass className = nonGeneric.get(i); if (javaType.isParameterizedType()) { List&lt;JavaTypeVariable&gt; typeVariables = className.getTypeParameters(); for (int y = 0; y &lt; typeVariables.size(); ++y) { ParameterizedType parameterizedType = javaType.getAsParameterizedType(); IJavaType parameter = JavaFactory.createJavaType(parameterizedType.getActualTypeArguments()[y]); result.add(new GenericEntry(typeVariables.get(y), parameter)); } } } return result; } } </code></pre> <p>My question is in how to organize this. I see several alternatives:</p> <ol> <li>I could put everything in <code>JavaClass</code> (doesn't seem that great of an idea).</li> <li>I could put <code>getAllGenericEntries()</code> in <code>JavaClass</code>, that delegates all the work to <code>GenericEntriesFinder.getAllGenericEntries()</code>. This seems to be nice as the client of <code>JavaClass</code> can use the method as long as he has a <code>JavaClass</code> in his hand.</li> <li>I could put all this logic in a separate class(<code>GenericEntriesFinder</code>, for instance). If I ever wanted to use this logic, I'd use <code>GenericEntriesFinder</code> and pass to <code>getAllGenericEntries</code>() a <code>JavaClass</code> instance. The client has the burden to know there actually exists an <code>GenericEntriesFinder</code> class, which is not that big of an issue, as I'm the only programmer, but still..</li> </ol> <p>If I am not mistaken these are the 3 main possibilities. For possibilities 2 and 3 there is still the question of whether to consider <code>GenericEntriesFinder</code>'s methods as static or instance methods. I know in a pure OO scenario one should look and strive for using instance methods, but as I've come to find, when writing a compiler everything tends to turn into a heap of functions(that is, as a sequence of transformations of data), and it's hard a lot of the time to try to model this in a OO way (data plus operations on data).</p> <p>Plus, on <code>2.</code>, would I decide on using instance methods on <code>GenericEntriesFinder</code>, should I pass its instance in <code>JavaClass</code>'s constructor? I don't particularly like this option, as if I start adding more and more methods to JavaClass, I will eventually have to pass it several classes like <code>GenericEntriesFinder</code> as constructor arguments. Passing classes by constructor argument may seem like a unit-testing plus but it actually will make gain nothing, as I'll be unit-testing <code>GenericEntriesFinder</code>.</p> <p>A big point in here is that this logic is going to be unit-tested.</p>
[]
[ { "body": "<blockquote>\n <p>I know in a pure OO scenario one should look and strive for using instance methods, but as I've come to find, when writing a compiler everything tends to turn into a heap of functions [...]</p>\n</blockquote>\n\n<p>Object orientation is appropriate for a large set of projects, but as you've discovered, it's not ideal for everything. You shouldn't try to force things into an OO paradigm if it's going to make things overly difficult or introduce needless complexity.</p>\n\n<p>I think the code you posted is fine. All you're really trying to do is have a <code>getAllGenericEntries()</code> method within <code>JavaClass</code> without having its implementation create extra noise in the class definition, and I think option #2 (with <code>static</code> methods) is the best way to do that.</p>\n\n<p>Really, I think this is something that IDEs should handle. The pattern you used, where a method implementation is split into several methods (which are <em>only</em> used by that one parent method), should be taken into account when displaying a class definition. Any <code>private</code> methods that are only used by one method could probably be hidden from the class definition entirely, and only accessed via that one method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T02:08:00.150", "Id": "8641", "ParentId": "8582", "Score": "0" } }, { "body": "<p>The problem with splitting this class out is that it's far too interested in the details of JavaClass. It spends half of its time pulling data out of JavaClass. It spends the other half of its time pulling data of out ParameterizedType. It doesn't really have any interesting data or behavior of its own. In it's heart, its still part of JavaClass. So it's not a great split.</p>\n\n<p>But there are things we can do about that:</p>\n\n<pre><code> IJavaType javaType = generic.get(i);\n JavaClass className = nonGeneric.get(i);\n</code></pre>\n\n<p><code>IJavaType</code> presumably wraps <code>java.lang.reflect.Type</code>. In the case that its a generic type, its the subinterface <code>ParameterizedType</code>. <code>ParameterizedType</code> has a method <code>getRawType()</code> which will return the actual class being parameterized. In this case, that's whatever <code>className</code> refers to. Point being, <code>javaType</code> knows what class it is, so there's no need for the <code>nonGeneric</code> list. I think they code will be significantly streamlined as a result.</p>\n\n<pre><code>public static List&lt;GenericEntry&gt; getAllGenericEntries(JavaClass javaClass) {\n List&lt;GenericEntry&gt; result = new ArrayList&lt;GenericEntry&gt;();\n result.addAll(getClassGenericEntries(javaClass));\n result.addAll(getInterfaceGenericEntries(javaClass));\n return result;\n}\n\nprivate static List&lt;GenericEntry&gt; getClassGenericEntries(JavaClass javaClass) {\n IJavaType genericSuperClass = javaClass.getGenericSuperclass();\n JavaClass superClass = javaClass.getSuperClass();\n\n return getGenericEntries(javaClass, Arrays.asList(genericSuperClass), Arrays.asList(superClass));\n}\n\nprivate static List&lt;GenericEntry&gt; getInterfaceGenericEntries(JavaClass javaClass) {\n List&lt;IJavaType&gt; genericInterfaces = javaClass.getGenericInterfaces();\n List&lt;JavaClass&gt; nonGenericInterfaces = javaClass.getInterfaces();\n\n return getGenericEntries(javaClass, genericInterfaces, nonGenericInterfaces);\n}\n</code></pre>\n\n<p>About half of this class is concerned with making sure that we handle both interfaces and superclasses. Instead, how about a function like</p>\n\n<pre><code>List&lt;IJavaType&gt; getBases()\n{\n List&lt;IJavaType&gt; bases = new ArrayList&lt;IJavaType&gt;();\n bases.add( getGenericSuperclass() );\n bases.addAll( getGenericInterfaces() );\n return bases;\n}\n</code></pre>\n\n<p>I'm gonna guess you may find other uses for this, and so it probably makes sense to go inside your JavaClass.</p>\n\n<pre><code> if (javaType.isParameterizedType()) {\n List&lt;JavaTypeVariable&gt; typeVariables = className.getTypeParameters();\n\n for (int y = 0; y &lt; typeVariables.size(); ++y) {\n ParameterizedType parameterizedType = javaType.getAsParameterizedType();\n IJavaType parameter = JavaFactory.createJavaType(parameterizedType.getActualTypeArguments()[y]);\n\n result.add(new GenericEntry(typeVariables.get(y), parameter));\n }\n }\n</code></pre>\n\n<p>This piece of code is far too interested in the internals of the parameterized type. That's a big hint that it should move into a function inside your wrapper of ParameterizedType.</p>\n\n<p>If you follow my advice, I think you'll have a function something like</p>\n\n<pre><code>List&lt;GenericEntry&gt; getBaseGenericEntries()\n{\n List&lt;GenericEntry&gt; entries = new ArrayList&lt;GenericEntry&gt;();\n for(IJavaType type: getBases() )\n {\n entries.addAll( type.getGenericEntries() );\n }\n return entries;\n}\n</code></pre>\n\n<p>Of course, this no longer makes sense to put into its own class. It'll do just fine as a member of JavaClass.</p>\n\n<blockquote>\n <p>I've at first\n written the bellow shown code inside JavaClass, but I soon found it\n too big to mantain in JavaClass, that is already getting fat.</p>\n</blockquote>\n\n<p>One of the trickier parts of OOP is deciding how to break up fat classes. Trying to extract <code>getAllGenericEntries</code> wasn't really a good split. It really fit as part of JavaClass so trying to pull it out doesn't really work that well. So if you want to trim the fat, you need to look elsewhere.</p>\n\n<p>I'd look for implementation details. This is stuff which the user of the class isn't aware of but is somehow supporting the interface. Often that can be extracted into some sort of supporting class. Another place to look is whether there are different subsets of functionality used by different pieces of code. If half of JavaClass is used by ModuleA and the other half is used by ModuleB with little to no overlap, then splitting the class can work really well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T05:42:15.107", "Id": "13504", "Score": "0", "body": "_It really fit as part of JavaClass so trying to pull it out doesn't really work that well. So if you want to trim the fat, you need to look elsewhere._\n\n\nBut what if there was nowhere else to trim? What do you do if the implementation really is too large, and adds too much noise to your class definition?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T05:48:58.330", "Id": "13505", "Score": "0", "body": "@seand, you'll see that I did in fact suggest pulling specific pieces of the implementation out into the other classes. I'm all for pulling large implementations out of the class. But you've gotta be careful about how you split them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T05:53:30.570", "Id": "13506", "Score": "0", "body": "I was referring to the case where you _can't_ pull pieces of the implementation out. For instance, when you aren't manipulating your own classes, but instead some third party library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T06:09:52.547", "Id": "13508", "Score": "0", "body": "@seand, I can always pull pieces of the implementation out. I can always define more classes and put code into them. So I really have no idea what you are getting at." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T06:16:49.963", "Id": "13509", "Score": "0", "body": "I was trying to make my answer sound less dumb." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T16:50:51.707", "Id": "13524", "Score": "0", "body": "@seand, your answer is not dumb." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T05:20:49.330", "Id": "8645", "ParentId": "8582", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T08:41:13.393", "Id": "8582", "Score": "1", "Tags": [ "java", "unit-testing" ], "Title": "Question on where to put code logic" }
8582
<p>I use this function in my wordpress site to add genres to an album: What is it that makes this code so bulky? Is it have for the server or it just looks like?</p> <pre><code>/** * Creates a genere. If one already exists it will return an error * @author Junaid Qadir Baloch &lt;shekhanzai.baloch@gmail.com&gt; * @global type $wpdb * @param type $genreName * @param bool $returnFalse Return False if genre already exists insted of * returning setatus and message. Defaults to FALSE * @return type */ function createGenre($genreName, $returnFalse = FALSE) { $funtionName = __FUNCTION__; global $wpdb; $genreName = trim($genreName); if (empty($genreName)) { $status = ReturnValue::STATUS_ERROR; $value = ""; $message = 'Genere name cannot be empty'; return ReturnValue::doReturn($funtionName, $status, $value, $message); } elseif (!is_string($genreName)) { $status = ReturnValue::STATUS_ERROR; $value = ""; $message = 'Genere name must be a text string'; return ReturnValue::doReturn($funtionName, $status, $value, $message); } $genreName = ucwords($genreName); $genreSlug = text2Slug($genreName); $query = "SELECT COUNT (*) as count FROM `genres` WHERE `name`='" . $genreName . "' AND `slug`='" . $genreSlug . "' "; $result = $wpdb-&gt;get_results($query); if ($result[0]-&gt;count &lt;= 0) { $formData = array( 'name' =&gt; $genreName, 'slug' =&gt; $genreSlug ); $result = $wpdb-&gt;insert('genres', $formData); if ($result) { $status = ReturnValue::STATUS_SUCCESS; $value = ""; $message = 'Genere ' . $genreName . ' has been created.'; return ReturnValue::doReturn($funtionName, $status, $value, $message); } else { $status = ReturnValue::STATUS_ERROR; $value = ""; $message = 'Failed to create a genere as ' . $genreName . '.'; return ReturnValue::doReturn($funtionName, $status, $value, $message); } } else { if ($returnFalse) { return FALSE; } $status = ReturnValue::STATUS_ERROR; $value = ""; $message = 'Genere ' . $genreName . ' already exists.'; return ReturnValue::doReturn($funtionName, $status, $value, $message); } } </code></pre> <p>This a static class to handle return values. It provides a unified way for other functions to return values.</p> <pre><code>/** * ReturnValue is an helper class to handle * return values, status codes and messages * returned from different functions * * @author JQ */ class ReturnValue { const STATUS_SUCCESS = "SUCCESS"; const STATUS_FAIL = "FAILED"; const STATUS_OK = "OK"; const STATUS_ERROR = "ERROR"; public static function doReturn($funtionName, $status = NULL, $value = NULL, $message = NULL) { if ($status == NULL) { $status = self::STATUS_FAIL; } $return = array( action =&gt; $funtionName, status =&gt; $status, message =&gt; $message, returnValue =&gt; $value ); return (object) $return; } } </code></pre>
[]
[ { "body": "<p>Remove global (this shouldn't need to be explained).</p>\n\n<p>Your code depends on the class ReturnValue with method doReturn. This is a tight coupling that makes it hard to test your code. For your code to be reused you must also include the ReturnValue. This is almost ok, when it is only 1 extra file, but it gets out of hand very quickly. </p>\n\n<p>Your code has also become bloated by the error code handling. Consider rewriting this with exceptions:</p>\n\n<pre><code>/**\n * Creates a genere. If one already exists it will return an error\n *\n * @param type $wpdb Wordpress database?\n * @param type $genreName What is this?\n * @return type \n */\nfunction createGenre($wpdb, $genreName) {\n if (empty($genreName) || !is_string($genreName))\n {\n throw new InvalidArgumentException(\n // Choose either __METHOD__ or __FUNCTION__ depending if this is OO.\n __METHOD__ . ' genreName must be a non-empty string');\n }\n\n $genreName = ucwords($genreName);\n $genreSlug = text2Slug($genreName);\n $query = \"SELECT COUNT (*) as count FROM `genres` WHERE `name`='\" .\n $genreName . \"' AND `slug`='\" . $genreSlug . \"' \";\n $result = $wpdb-&gt;get_results($query);\n if ($result[0]-&gt;count &gt; 0) {\n throw new RuntimeException(__METHOD__ . ' genre already exists.');\n }\n\n $formData = array(\n 'name' =&gt; $genreName,\n 'slug' =&gt; $genreSlug\n );\n\n $result = $wpdb-&gt;insert('genres', $formData);\n\n if (!$result) {\n throw new RuntimeException(\n __METHOD__ . ' failed to create genre: ' . $genreName);\n }\n}\n</code></pre>\n\n<p>The code is a lot shorter and flatter (which makes it easier to test and maintain. Arrow code is harder to debug, maintain and test - <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">see here</a>.</p>\n\n<p>Here is the usage with exceptions:</p>\n\n<pre><code>try\n{\n $genreName = 'slimy ';\n createGenre($wpdb, trim($genreName));\n\n return array('action' =&gt; 'createGenre',\n 'message' =&gt; 'Genre ' . $genreName . ' has been created.',\n 'returnValue' =&gt; '', // If needed even.\n 'status' =&gt; 'SUCCESS');\n}\ncatch (Exception $e)\n{\n return array('action' =&gt; 'createGenre',\n 'message' =&gt; $e-&gt;getMessage(),\n 'returnValue' =&gt; '', // If needed even.\n 'status' =&gt; 'ERROR',\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T13:16:35.330", "Id": "8584", "ParentId": "8583", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T10:36:03.063", "Id": "8583", "Score": "2", "Tags": [ "php", "optimization", "exception-handling" ], "Title": "How can I improve CreateGenre() function?" }
8583
<p>I have written a class who is responsible for both enumerating primes and testing the primality of a number.</p> <p>Here is the code :</p> <pre><code>public static class Primes { private static ulong g_MaxTested; private static ulong g_MaxFound; private static readonly HashSet&lt;ulong&gt; g_KnownPrimes; static Primes() { // All primes below 1000 (http://en.wikipedia.org/wiki/Primes) g_KnownPrimes = new HashSet&lt;ulong&gt;() { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 }; g_MaxTested = 997; g_MaxFound = 997; } private static void EnsureExploredUpTo(ulong upperBound) { if (upperBound &lt;= g_MaxTested) return; for (g_MaxTested += 2; g_MaxTested &lt;= upperBound; g_MaxTested += 2) { if (TestPrimality(g_MaxTested)) { g_KnownPrimes.Add(g_MaxTested); g_MaxFound = g_MaxTested; } } } private static bool TestPrimality(ulong value) { if (value == 1) return false; var sqrt = (ulong)Math.Sqrt(value); return !g_KnownPrimes .TakeWhile(x =&gt; x &lt;= sqrt) .Any(x =&gt; value % x == 0); } public static bool IsPrime(ulong value) { if (value == 1) return false; EnsureExploredUpTo(value); return g_KnownPrimes.Contains(value); } public static IEnumerable&lt;ulong&gt; GetPrimes(ulong upperBound = ulong.MaxValue) { // First return all known primes : foreach (var prime in g_KnownPrimes) { if (prime &gt; upperBound) yield break; yield return prime; } // then, if required, continue exploring : for (g_MaxTested += 2; g_MaxTested &lt;= upperBound; g_MaxTested += 2) { if (TestPrimality(g_MaxTested)) { g_KnownPrimes.Add(g_MaxTested); g_MaxFound = g_MaxTested; yield return g_MaxTested; // yield the result for immediate use } } } } </code></pre> <p>Key concepts :</p> <ul> <li>The idea of the class is to maintain a "cursor" of explored number, and a list of known primes.</li> <li>The known primes (<code>g_KnownPrimes</code>) allows me to test a number like using a sieve (as a non prime number is always a multiple of another prime (<code>TestPrimality</code> method).</li> <li>When I want to test a number outside the explored number range, I explorer from the last tested to the number to test (<code>EnsureExploreredUpTo</code> method)</li> <li>When I want to enumerate all primes, I start to yield known primes, then use the same logic than <code>EnsureExplorerdUpTo</code>, but with yielding each prime found.</li> </ul> <p>I have validated my code using these tests :</p> <pre><code> [TestMethod()] public void GetPrimesTest() { var primes = Primes.GetPrimes(); var enumerator = primes.GetEnumerator(); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(enumerator.Current, 2UL); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(enumerator.Current, 3UL); do { Assert.IsTrue(enumerator.MoveNext()); } while (enumerator.Current &lt; 997); // Last prime below 1000 Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(enumerator.Current, 1009UL); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(enumerator.Current, 1013UL); } [TestMethod()] public void _1IsNotPrimeTest() { Assert.IsFalse(Primes.IsPrime(1)); } [TestMethod()] public void _2IsPrimeTest() { Assert.IsTrue(Primes.IsPrime(2)); } [TestMethod()] public void _3IsPrimeTest() { Assert.IsTrue(Primes.IsPrime(3)); } [TestMethod()] public void _42IsNotPrimeTest() { Assert.IsFalse(Primes.IsPrime(42)); } [TestMethod()] public void _2001IsNotPrimeTest() { Assert.IsFalse(Primes.IsPrime(2001)); } </code></pre> <p>So my question are :</p> <ul> <li>Is this approach valid ? I've googled a bit but without finding better algorithms.</li> <li>I use the <code>HashSet&lt;ulong&gt;</code> class, as it seems to be the more efficient list for my case. Am I right ?</li> <li>I know this class is not thread safe at all. Can I "simply" make it thread-safe ? (maybe this should be a dedicated question on [so].</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T01:22:06.500", "Id": "62789", "Score": "0", "body": "Why not port this clever python code to your language? http://onlamp.com/pub/a/python/excerpt/pythonckbk_chap1/index1.html?page=2" } ]
[ { "body": "<p>How large are the numbers that you will be testing for primality? If you have an upper bound then it might be better to use a sieve of Eratosthenes to find all the primes up to <code>sqrt(upperBound)</code>. That way you don't need to keep checking whether you need to extend your explored range.</p>\n\n<p>In answer to your questions:</p>\n\n<p>1) Your approach seems valid. However, it might pay off to extend your explored range by more than 2 at a time using a sieve approach, e.g. start off with 1000 primes and then if you need more explore up to 10,000, then 100,000. Sieve's are quick and you'll avoid division.</p>\n\n<p>2) A hash set seems reasonable. Another viable approach (for small g_MaxTested) is a BitArray. This becomes less appealing as g_MaxTested gets larger because the primes become more spread out.</p>\n\n<p>3) A simple approach is to make each public method <code>lock</code> a locker object. This means only one thread can interact with your class at once.</p>\n\n<p>If you want me to write some code to explain my points let me know.</p>\n\n<p><strong>Update</strong></p>\n\n<p>How about initialising the class with all the primes less than 10^7 (664,579 according to wikipedia), then if you get a number:</p>\n\n<ul>\n<li>&lt; 10^7 do a simple membership check</li>\n<li>between 10^7 and (10^7)^2 see if any of your primes divide into it</li>\n<li>> 10^14 check whether any of your primes divide into it, if not see if any of the odd numbers in the range 10^7 to sqrt(number) divide it.</li>\n</ul>\n\n<p>It is probably best to store the primes as uint rather than ulong to save on memory.</p>\n\n<p>Also 10^7 is arbitrary and you should change this to suit your space / time requirements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T15:54:27.957", "Id": "13432", "Score": "0", "body": "actually, upperbound will be most of time below 10^7, but the class is part of an utility library so it have to works well for any ulong value. 1. I understand your point of view, but doesn't your approach requires to maintain an array of bool, with the length of all integers ? 2. don't see how to replace the hashset with a bitarray. Can you explain this point ? 3. I know the lock object. I was actually thinking about a more subtle (and complex) behavior. Having the possibility of a worker thread for exploration, and several \"readers\", locked only if requested number is below explored" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T08:36:49.397", "Id": "13472", "Score": "0", "body": "I've added an approach that works well for numbers that aren't too large and will be threadsafe (without the need for locks)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T08:44:57.387", "Id": "13473", "Score": "0", "body": "Also, do you really need to work with ulongs? storing all the primes up to ulong.MaxValue will require a **lot** of memory." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T15:30:59.670", "Id": "8592", "ParentId": "8585", "Score": "1" } }, { "body": "<p>This is a valid sieve but the HashSet MAY not be as fast as an Array or ArrayList. These will preserve the order of the elements, so you could implement a quick membership check with a binary search. They would likely be faster to iterate over in general -- they should especially speed up iteration for testing the primality of a sequence of odd numbers. In 33% of the cases, the testing would not get past <code>x % 3</code>. Doing these tests in HashSet order wastes lots of time checking against higher primes in the HashSet that rarely change the outcome. Listing primes in a HashSet order that may change as the set of primes grows seems slightly less useful than listing in increasing order.</p>\n\n<p>BTW, testing odd numbers for <code>x % 2</code> is a waste of time, especially if that's going to be the first test -- you might want to consider pulling 2 out of your primes list and handling it separately only when you have to.</p>\n\n<p>But you should definitely <em>benchmark</em> either of these suggestions on a mix of input sequences with typical numbers of input values, maximum input values, and tendencies to raise the high water value early vs. late in the sequence.</p>\n\n<p>One last note: <code>g_MaxFound</code> doesn't cost much and is nice for diagnostic purposes, but it's not actually used in the implementation. I usually mark non-critical variables like this with special names or at least comments to avoid confusion with the operational values.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T15:40:47.377", "Id": "13431", "Score": "0", "body": "SortedSet has ln(n) for .Contains so would avoid implementing your own binary search. http://msdn.microsoft.com/en-us/library/dd412070.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T23:09:59.630", "Id": "13463", "Score": "0", "body": "@Joey Good point. It'd be interesting to benchmark ArrayList w/ a homegrown binary search vs. SortedSet at different scales for this special case of always inserting a new max element and never removing elements." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T15:33:05.437", "Id": "8593", "ParentId": "8585", "Score": "3" } }, { "body": "<p>Some notes about the tests:</p>\n\n<ol>\n<li><p>The first the method has a smell: <a href=\"http://xunitpatterns.com/Conditional%20Test%20Logic.html\" rel=\"nofollow\">Conditional Test Logic</a>. I'd extract out the <code>do-while</code> loop to an <code>enumeratePrimesBelow(ulong upperLimit)</code> method. It would improve readability a lot.</p></li>\n<li><pre><code>Assert.IsFalse(Primes.IsPrime(1));\n</code></pre>\n\n<p>I'd create a <a href=\"http://xunitpatterns.com/Custom%20Assertion.html\" rel=\"nofollow\">custom assertion method</a> for that:</p>\n\n<pre><code>public void AssertIsNotPrime(ulong value) {\n Assert.IsFalse(Primes.IsPrime(value));\n}\n</code></pre>\n\n<p>It would make the tests easier to read.</p></li>\n<li><p><code>_1IsNotPrimeTest</code>, <code>_2IsPrimeTest</code>, <code>_3IsPrimeTest</code>, <code>_42IsNotPrimeTest</code> etc. should be a <a href=\"http://xunitpatterns.com/Parameterized%20Test.html\" rel=\"nofollow\">parameterized test</a>. I don't know whether C# unit testing frameworks supports it or not.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T14:29:39.597", "Id": "13477", "Score": "0", "body": "Thanks for this feedback. You are right, I can make my code more readable. For your 3rd item, unfortunately MS OOB test framework does not provides parameterized test. This is not a big issue as I also use Pex which helps find and generate test cases." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T10:38:27.607", "Id": "8618", "ParentId": "8585", "Score": "1" } } ]
{ "AcceptedAnswerId": "8593", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T13:22:07.583", "Id": "8585", "Score": "4", "Tags": [ "c#", "primes" ], "Title": "Finding and testing primality" }
8585