body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I just finished rewriting my Router class. Any input would be much appreciated.</p> <p>The class routes URLs based on a <code>site.com/class/method/param/param/etc</code> syntax.</p> <p>One thing I've done differently is created a mechanism for basic templates to be loaded directly without the need for a controller. I often find pages such as <code>/about/</code> do not require additional methodology, and setting up really basic controllers just seems like a waste of time. Therefore, I have created a check for templates such as <code>_about.php</code> in the views folder, with the underscore denoting that it can be loaded directly.</p> <p>The class also currently assumes an error class or template.</p> <pre><code>class Router{ public static function getPath($uri = null){ // set default uri $uri = is_null($uri) ? $_SERVER['REQUEST_URI'] : $uri; // remove possible query string $uri = preg_replace('/\?(.*)/', '', $uri); return explode('/',trim($uri,'/')); } public static function getQuery($uri = null){ // set default uri $uri = is_null($uri) ? $_SERVER['REQUEST_URI'] : $uri; // get query string $query = substr($uri, strpos($uri,'?') + 1); // parse into array $q = array(); parse_str($query,$q); return $q; } public static function follow($uri = null){ $path = self::getPath($uri); // get controller and method, or set defaults of root and index $controller = ($path[0] == "") ? 'root' : $path[0]; $method = ((count($path) &gt; 1) &amp;&amp; ($path[1] != "")) ? $path[1] : null; // see if controller is a static page, only possible if no method specified if(is_null($method) &amp;&amp; file_exists(APPLICATION_DIR . '/views/_' . $controller . '.php')){ include APPLICATION_DIR . '/views/_' . $controller . '.php'; } else if(file_exists(APPLICATION_DIR . '/controllers/' . $controller . '.php')){ // see if controller exists // load controller class include_once APPLICATION_DIR . '/controllers/' . $controller . '.php'; // if method is empty or doesn't exist, it defaults to "index" if(is_null($method) || !method_exists($controller,$method)) { $method = "index"; } if(method_exists($controller, $method)){ $c = new $controller(); $c-&gt;$method(); } else{ self::follow('e404'); } } else{ self::follow('e404'); } } } </code></pre>
[]
[ { "body": "<p>This is really good, there are only a few things I would point out.</p>\n\n<p>Why are you using <code>is_null()</code>? All this does is check for a null value. It would be equivalent to doing <code>! $uri</code>, except that would have the added benefit of checking for FALSE. Check out <code>filter_var()</code> if your PHP version is >= 5.2. I find myself suggesting this function all the time, I should macro it or something...</p>\n\n<pre><code>$uri = filter_var($uri, FILTER_VALIDATE_URL) ?: $_SERVER['REQUEST_URI'];\n</code></pre>\n\n<p>You could also use the <code>FILTER_SANITIZE_URL</code> flag. I did not add it myself, because I am horrible with regex, and have no idea what you are doing there. If you wish to add it, separate it from the other flag with a bitwise \"Or\" operator <code>|</code>.</p>\n\n<p>Instead of retyping those long file names, you should make them variables. It saves time and effort, and removes one more place for an error to occur. So...</p>\n\n<pre><code> $controller = ($path[0] == \"\") ? 'root' : $path[0];\n $method = ((count($path) &gt; 1) &amp;&amp; ($path[1] != \"\")) ? $path[1] : null;\n\n $view_file = APPLICATION_DIR . '/view/_' . $controller . '.php';\n $controller_file = APPLICATION_DIR . '/controllers/' . $controller . '.php';\n</code></pre>\n\n<p>You should not depend on your calling application to provide functionality. <code>APPLICATION_DIR</code> came from no where, you should declare it locally, or at least provide some check to ensure it is set. Failing this, you should at the very least, comment your code to tell where that constant is supposed to come from.</p>\n\n<p>Why did you default <code>$method</code> to <code>null</code> if you are just going to default it to 'index' later? You haven't used it for anything before you changed it to index, so I find it rather confusing... When you initially set it, just set the default to index.</p>\n\n<p>Also, what happens if 'e404' somehow gets deleted or moved? You will be stuck in a continuous loop. I would just manually set a 404 page or somehow ensure that this code does not get stuck.</p>\n\n<p>Good Luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T06:33:48.520", "Id": "18145", "Score": "0", "body": "Thanks! The router is actually part of a small framework I am developing. I will make sure to make notes on constants. Good call on the \"index\" default value and the use of is_null. My first thought with is_null was to allow for \"0\" values, but that doesn't really make a difference in this usage. I also agree with the e404 issue. The possible infinite loop was one of my main concerns. However, I like the ability to have either a class or a simple template, so I will probably just add an additional check at the end to see if the controller is already e404 and if so output a simple die message." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T02:32:32.870", "Id": "11298", "ParentId": "11286", "Score": "2" } }, { "body": "<p>This is not OOP.</p>\n\n<p>Observe how your class contains only static functions. There are no class properties. This can be written equivalently:</p>\n\n<pre><code>namespace Router;\n\nfunction getPath($uri = null){\n // Same implementation (I have just cut it out for readability).\n}\n\nfunction getQuery($uri = null){\n // Same implementation.\n}\n\nfunction follow($uri = null){\n // Same implementation.\n}\n</code></pre>\n\n<p>Usage from anywhere can be compared (First your code):</p>\n\n<pre><code>Router::getPath($uri);\nRouter::getQuery($uri);\nRouter::follow($uri);\n</code></pre>\n\n<p>Then the equivalent:</p>\n\n<pre><code>Router\\getPath($uri);\nRouter\\getQuery($uri);\nRouter\\follow($uri);\n</code></pre>\n\n<p>Note how no object is required to be used (that is a good hint that its not OO).</p>\n\n<p>The following question would be worth reading:</p>\n\n<p><a href=\"https://codereview.stackexchange.com/q/11004/7585\">User class design</a></p>\n\n<p>I have an answer to that question which covers in more detail some of the problems with using <code>static</code> in OOP.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T13:57:17.540", "Id": "18151", "Score": "0", "body": "You are correct, I was not paying attention. Actually, to be perfectly honest, I just didn't know, I'm quite new to OOP myself, so I'll be taking a look at that answer myself :) +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T14:46:48.507", "Id": "18158", "Score": "0", "body": "Thanks for the input. My intention with the title was that the router was for an OOP architecture, loading classes and methods. I probably should have been clearer. I haven't really used namespaces before but understand the concept. I'll look into it more. Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T13:28:27.753", "Id": "18245", "Score": "0", "body": "MVC is an architecture that can be implemented using Object Oriented, Procedural, Functional and I'm guessing Logical paradigms. Splitting your way of thinking at this point of the problem does not make sense to me. Why not have an OO router in an OO system?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T01:28:18.573", "Id": "18311", "Score": "0", "body": "I can see your point, but then I'd be required to instantiate an object every time I wanted to use the router. I can see where benefits could come in if I ever want more complex methods, but at the present time I'm looking at a one step process instead of a two. At least until PHP 5.4 is more readily available." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T10:51:15.823", "Id": "11302", "ParentId": "11286", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-28T21:22:12.367", "Id": "11286", "Score": "4", "Tags": [ "php", "object-oriented", "mvc", "url-routing" ], "Title": "Object Oriented PHP Url Router" }
11286
<p>I am relatively new to jQuery and this is one of the first attempts to use it. Tell me if I am using it wrong:</p> <p>This is the main code that toggles everything:</p> <pre><code>$(function(){ $("#tree li").hide();//collapse everything by default $("#tree span").click(function(){ $(this).toggleClass("uncollapsed");//toggle "V" and "&gt;" $(this).parent().find("&gt;li").toggle("fast");//display and hide }); }); </code></pre> <p>I am only interested to get reviews on the JS above, however, I will post the the HTML and CSS to give some background.</p> <p>HTML:</p> <pre><code>&lt;ul id="tree"&gt; &lt;span&gt;(click to toggle)&lt;/span&gt; &lt;li&gt;1&lt;/li&gt; &lt;li&gt;2&lt;/li&gt; &lt;li&gt; &lt;ul&gt; &lt;span&gt;(click to toggle)&lt;/span&gt; &lt;li&gt;3&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>CSS:</p> <pre><code>#tree ul,#tree li,#tree span{ list-style:none; padding:0; margin:0; } #tree li,#tree span{ padding:5px 0 5px 20px; } #tree span{ cursor:pointer; background:url('collapsed.png') no-repeat 0 50%; } #tree span.uncollapsed{ background-image:url('uncollapsed.png'); } </code></pre>
[]
[ { "body": "<p>That is not valid html.</p>\n\n<p>The only thing you can put inside a <code>&lt;ul&gt;</code> tag is <code>&lt;li&gt;</code> tags.</p>\n\n<p>With that in mind, this would be much better (change the selector as necessary):</p>\n\n<pre><code>$(\"#tree span\").click(function () {\n $(this).toggleClass(\"uncollapsed\").next().toggle(\"fast\");\n});\n</code></pre>\n\n<p>Otherwise, you should change the click method to:</p>\n\n<pre><code>$(\"#tree span\").click(function () {\n $(this).toggleClass(\"uncollapsed\").parent().children(\"li\").toggle(\"fast\");\n});\n</code></pre>\n\n<p>Reasons:</p>\n\n<ul>\n<li>you don't need to use $() over again to recreate $(this)</li>\n<li><code>.find(\"&gt;li\")</code> is a less efficient version of <code>.children(\"li\")</code></li>\n</ul>\n\n<p>Better yet, if you can change the html to:</p>\n\n<pre><code>&lt;span class='hasChildren'&gt;\n (click to toggle)\n &lt;ul id=\"tree\"&gt;\n &lt;li&gt;1&lt;/li&gt;\n &lt;li&gt;2&lt;/li&gt;\n &lt;li class='hasChildren'&gt;\n (click to toggle)\n &lt;ul&gt;\n &lt;li&gt;3&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n&lt;/span&gt;\n</code></pre>\n\n<p>Then the click event to:</p>\n\n<pre><code>$(\".hasChildren\").click(function (e) {\n $(this).toggleClass(\"collapsed\");\n return false;\n});\n</code></pre>\n\n<p>And in css, style accordingly (you could even animate the class if you wished). Note however that this would be a change in the way the list worked (play around with <code>&lt;a&gt;</code> tags in the list and clicking in different parts to see the difference).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T02:18:34.873", "Id": "11297", "ParentId": "11289", "Score": "1" } } ]
{ "AcceptedAnswerId": "11297", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-28T23:52:33.850", "Id": "11289", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Collapsable Tree" }
11289
<p>I'm creating a <a href="https://github.com/kentcdodds/Java-Helper" rel="nofollow">Java Helper Library</a> with helpful static methods. I find myself needing to call <code>...getResource(...)</code> or <code>...getResourceAsStream(...)</code> in several instances and I'm wondering what's the best practice for this. It seems to be working fine when I say: <code>Helper.class.getResource(...)</code>, but I'm wondering whether that will bite me in the future.</p> <p>I have a few alternatives I'm thinking of. Below is an example of when I need to use this and the alternatives I have thought of:</p> <p><strong>Alternative 1</strong> (what I would prefer for the sake of users):</p> <pre><code>/** * Takes the given resource and returns that as a string. * * @param location of the file * @return the file as a string * @throws IOException */ public static String resourceToString(String location) throws IOException { InputStream is = IOHelper.class.getResourceAsStream(location); InputStreamReader r = new InputStreamReader(is); return readerToString(r); } </code></pre> <p><strong>Alternative 2:</strong></p> <pre><code>/** * Takes the given resource (based on the given class) and returns that as a string. * * @param location of the file * @param c class to get the resource from * @return the file as a string * @throws IOException */ public static String resourceToString(String location, Class c) throws IOException { InputStream is = c.getResourceAsStream(location); InputStreamReader r = new InputStreamReader(is); return readerToString(r); } </code></pre> <p><strong>Alternative 3</strong> (should I just have the user give me the resource?):</p> <pre><code>/** * Takes the given InputStream and returns that as a string. * * @param is the InputStream of the File to read * @return the file as a string * @throws IOException */ public static String resourceToString(InputStream is) throws IOException { InputStreamReader r = new InputStreamReader(is); return readerToString(r); } </code></pre>
[]
[ { "body": "<p>I would prefer the second one. The others will bite if the library runs inside an OSGi container.</p>\n\n<p>Furthermore, I would</p>\n\n<ol>\n<li>pass <code>UTF-8</code> character encoding to the constructor of the <code>InputStreamReader</code>. Otherwise it will use the system encoding which vary from system to system. (Or let the user to set it with a third method parameter.)</li>\n<li>use longer variable names. <code>is</code>, <code>r</code>, <code>c</code> are not too easy to read. I would call them <code>resourceStream</code>, <code>clazz</code> and <code>resourceReader</code>. It does not force readers to decode them.</li>\n<li>reverse the order of <code>String location, Class c</code> parameters. It would be in the same order as the first line use them (<code>c.getResourceAsStream(location)</code>). I don't know if there is a rule of thumb for this, but it looks more natural to me. (Any pointers are welcome.)</li>\n<li>remove the <code>* @throws IOException</code> javadoc line. It is meaningless in this form.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T01:34:52.833", "Id": "11294", "ParentId": "11290", "Score": "3" } } ]
{ "AcceptedAnswerId": "11294", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T00:04:02.870", "Id": "11290", "Score": "3", "Tags": [ "java", "comparative-review" ], "Title": "Which class is best to call .getResource on?" }
11290
<p>I'm not sure whether I should be throwing exceptions in the below model code (and rescuing in the controller - rescues not implemented below) or returning <code>nil</code> (in both or one of the exception cases). Also, should the model method be <code>identify</code>, or is <code>identify</code> proper?</p> <p>My line of thinking is if the title is not set when identify is called, something is wrong or it is being used incorrectly. Regarding the second exception, if there are no results, then the movie in question can not be scraped, thus making all operations later (which depend on the scraped data) useless. </p> <p>I guess this comes down to return nil vs throw exception - I have been reading quite a few arguments on this subject and to me it seems proper to throw in both cases, thoughts? Perhaps i'm missing a "rails way" of doing this too? I'm fairly new to Rails. If it matters, I am using Rails 3.2.</p> <h3>Movie model</h3> <pre><code>validates :title, :presence =&gt; true def identify raise "No Title" if self.title.nil? search_content = Nokogiri::HTML open("http://akas.imdb.com/find?q=#{CGI::escape(self.title)};s=tt") top_result = search_content.xpath("//div[@id='main']/p[1]/b/a").first raise "No Results" if top_result.nil? self.title = top_result.content self.imdb_id = top_result["href"].split("/")[2][2..-1].to_i end def populate_data identify if self.imdb_id.nil? # ...scrape imdb and save content to model attributes... end </code></pre> <h3>MovieController</h3> <pre><code>def create @movie = Movie.new :title =&gt; params[:movie][:title] @movie.populate_data if @movie.save # ...the usual set flash, else recover kinda thing... </code></pre>
[]
[ { "body": "<blockquote>\n <p>should the model method be identify! or is identify proper?</p>\n</blockquote>\n\n<p>You should only end the method name with a bang (!) if the method modifies the object it is called on. Furthermore, only if there is also another method of the same name without the bang which does not modify the object. So no, you should not use a bang in your method name.</p>\n\n<blockquote>\n <p>return nil vs throw exception</p>\n</blockquote>\n\n<p>I would take a cue from either ActiveRecord#find or #find_by_*. The first will throw an exception when given an ID that doesn't exist. The later will return nil. Think of it as entering a URL in your browser as opposed to doing a Google search. With the first, it's expected that you know the exact URL, with the later, it's not and you should get some sort of result or lack of result. According to what you say, you should be going with throwing exceptions.</p>\n\n<p>However, I would rethink how you're doing things. I would do this with initialize instead of having to explicitly call populate_data.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T19:52:41.337", "Id": "11373", "ParentId": "11293", "Score": "1" } } ]
{ "AcceptedAnswerId": "11373", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T01:29:50.797", "Id": "11293", "Score": "2", "Tags": [ "beginner", "ruby", "ruby-on-rails", "exception" ], "Title": "Stylistic exception and bang usage" }
11293
<p>My code is below. List anything that looks wrong, anything that could be improved. This is an update from <a href="https://codereview.stackexchange.com/questions/11282/any-suggestions">this question</a>. I know, my old code was a complete mess.</p> <p>New Code:</p> <pre><code>import math class ChangeableRange: """With this type of range object, one can edit the start, stop, and step for the range, as well as easily retrieving the values in the range """ def __init__(self, maximum, start=0, step=1): """Sets the maximum, start, and step""" try: self.maximum = math.ceil(maximum) self.start = math.ceil(start) self.step = math.ceil(step) except TypeError: return "Error, attributes must be of type int or float" def __iter__(self): """Iterates over the range""" return iter(range(self.start, self.maximum, self.step)) def __str__(self): """Returns a string representation of the CRange""" return "CRange object with Max: {0}, Min: {1}, and Step: {2}".format(self.maximum, self.start, self.step) def __len__(self): """Returns the number of values in the range""" return len(range(self.start, self.maximum, self.step)) def to_dict(self): """Returns a dictionary representation of the maximum, minimum, and step""" return {"Max": self.maximum, "Min": self.start, "Step": self.step} def change_range(self, attr, option, x): """Provides options to change attributes of the range""" if option == "add" and attr == "maximum": try: self.maximum += x except TypeError: print("Error, you cannot add", x, "to the maximum, a float or integer is required") elif option == "sub" and attr == "maximum": try: self.maximum -=x except TypeError: print("Error, you cannot subtract", x, "from the maximum, a float or integer is required") elif option == "mult" and attr == "maximum": try: if self.maximum &lt;= 0: raise Exception self.maximum *= x except TypeError: print("Error, you cannot multiply the maximum by", x, "a float or integer is required") except Exception: print("Error, the maximum cannot be less than or equal to zero") elif option == "div" and attr == "maximum": try: self.maximum /= x if self.maximum &lt;= 0: raise SyntaxError except TypeError: print("Error, you cannot divide the maximum by", x, "a float or integer is required") except Exception: print("Error, the maximum cannot be less than or equal to zero") elif option == "add" and attr == "start": try: self.start += x except TypeError: print("Error, you cannot add", x, "to the start, a float or integer is required") elif option == "sub" and attr == "start": try: self.start -=x except TypeError: print("Error, you cannot subtract", x, "from the start, a float or integer is required") elif option == "mult" and attr == "start": try: if self.start &lt;= 0: raise SyntaxError self.start *= x except TypeError: print("Error, you cannot multiply the start by", x, "a float or integer is required") except Exception: print("Error, the start cannot be less than or equal to zero") elif option == "div" and attr == "start": try: self.start /= x if self.start &lt;= 0: raise SyntaxErros except TypeError: print("Error, you cannot divide the start by", x, "a float or integer is required") except Exception: print("Error, the start cannot be less than or equal to zero") elif option == "add" and attr == "step": try: self.step += x except TypeError: print("Error, you cannot add", x, "to the step, a float or integer is required") elif option == "sub" and attr == "step": try: self.step -= x except TypeError: print("Error, you cannot subtract", x, "from the start, a float or integer is required") elif option == "mult" and attr == "step": try: if self.step &lt;= 0: raise SyntaxError self.step *= x except TypeError: print("Error, you cannot multiply the step by", x, "a float or integer is required") except Exception: print("Error, the step cannot be less than or equal to zero") elif option == "div" and attr == "step": try: self.step /= x if self.step &lt;= 0: raise SyntaxError except TypeError: print("Error, you cannot divide the step by", x, "a float or integer is required") except Exception: print("Error, the step cannot be less than or equal to zero") self.start = math.ceil(self.start) self.step = math.ceil(self.step) self.maximum = math.ceil(self.maximum) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T14:18:18.170", "Id": "18153", "Score": "0", "body": "I'd be rather curious to see how you plan to use this code, especially `change_range`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T20:17:02.080", "Id": "18162", "Score": "3", "body": "You really should apply _all_ suggestions that were given to you in your previous questions before coming in and asking about the same code again... a lot still hasn't changed and we're just repeating ourselves now..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T04:35:12.560", "Id": "18168", "Score": "1", "body": "And I repeat, we really need to know how you are going to use this class." } ]
[ { "body": "<p>One thing I believe is missing is checking whether or not the inputs are valid. The step should not be zero, for instance. To simplify maintenance, a single \"setter\" method can be used, so you can call it both from <code>__init__</code> and <code>change_range</code>.</p>\n\n<p>I see you do a few checks in the <code>change_range</code> (for instance if the step is positive), but I see two problems with that: 1) sometimes you do the check <strong>before</strong> adjusting the value, so it can still become invalid (ex.: if you pass <code>\"step\", \"mult\", 0</code>). Using a setter would ensure that anytime the values are set the necessary conditions are met; 2) <code>range</code> support negative steps, as long as <code>maximum</code> is smaller than <code>start</code>. You might want to support that too.</p>\n\n<p>In your <code>__len__</code> method:</p>\n\n<pre><code>def __len__(self):\n \"\"\"Returns the number of values in the range\"\"\"\n return len(range(self.start, self.maximum, self.step))\n</code></pre>\n\n<p>Wouldn't it be more efficient to compute the number of elements, instead of creating the range and checking its length? Like this:</p>\n\n<pre><code>if (self.maximum - self.start) * self.step &lt; 0:\n return 0 # To be consistent with range\nreturn (self.maximum - self.start) // self.step\n</code></pre>\n\n<p>About the <code>change_range</code> function, I see you're supporting several operations (add, sub, mult, div) and applying them to each attribute (maximum, start, step). Instead of doing all the combinations, why don't you separate the concerns? Check type first, choose operation next, apply operation and check the constraints, then set the values:</p>\n\n<pre><code># Check the parameter type\nif not isinstance(x,int) and not isinstance(x,float):\n print(\"Error in parameter\", x, \"a float or integer is required\")\n return\n\n# Choose operation\nif option == 'add':\n delta = lambda x,y: x + y\nelif option == 'sub':\n delta = lambda x,y: x - y\n...\nelse:\n print(\"Error in parameter\", option, \"invalid option\")\n return\n\n# Apply operation to the right attribute\nmaximum = delta(self.maximum,x) if attr == 'maximum' else self.maximum\nstart = delta(self.start,x) if attr == 'start' else self.start\nstep = delta(self.step,x) if attr == 'step' else self.step\n\n# Check the constraints and set the new values\nself.attr_setter(maximum,start,step) # This would be the \"setter\" I mentioned earlier\n</code></pre>\n\n<p>Lastly, one style issue: the <code>range</code> builtin, when receiving a <code>start</code> value, receives it as the first argument. In your code it's the second. That might be confusing to users of your class. I'd suggest inverting them (when needed):</p>\n\n<pre><code>def __init__(self, maximum, start=None, step=1):\n maximum, start = (maximum, 0) if start is None else (start, maximum)\n</code></pre>\n\n<p>(This is not perfect: if you call your constructor with named parameters, it will invert them against your intent; so take this last advice with a grain of salt)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T11:50:18.487", "Id": "11305", "ParentId": "11295", "Score": "2" } }, { "body": "<p><code>range()</code> only accepts integers as input. <code>math.ceil</code> returns floats. You'll have to convert them to ints before calling <code>range()</code></p>\n\n<p>Rather than <code>print</code>-int errors, you should raise custom exceptions. \n Change all of your <code>print(\"blah blahs\")</code> to <code>raise Exception(\"blah blahs\")</code></p>\n\n<p>In <code>__init__</code>, it's unneccesary to use a try...except block as <code>math.ceil</code> already raises an error for incompatible types.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T13:03:58.717", "Id": "11306", "ParentId": "11295", "Score": "2" } }, { "body": "<ul>\n<li>Read pep-8 and apply it</li>\n<li>Use % instead of str.format, it's faster.</li>\n<li><p>this can die with a division by zero: </p>\n\n<p>return int((self.maximum-self.start)/self.step)</p></li>\n<li><p>Use instanceof instead of type().</p></li>\n<li>Don't raise Exception. Use ValueError instead.</li>\n<li>I suggest you make use of assert.</li>\n<li>You don't need to_dict method. Just use obj.__dict__ it will return the same thing.</li>\n<li>Do you really need <strong>iter</strong>? </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T16:46:55.717", "Id": "11350", "ParentId": "11295", "Score": "1" } }, { "body": "<p>I would also suggest that you should inherit your class from <code>object</code> as per the new style class conventions.</p>\n\n<p>eg: <code>class ChangeableRange(object)</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T11:43:01.793", "Id": "37971", "Score": "0", "body": "In Python 3, which the OP is using (note the `print('...')` function rather than `print '...'\n` statement), *all* classes are new-style and specifying `object` explicitly is neither necessary nor encouraged." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-02T11:25:48.033", "Id": "38031", "Score": "0", "body": "Hmm, you are right!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T06:55:47.773", "Id": "24586", "ParentId": "11295", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T01:39:23.703", "Id": "11295", "Score": "4", "Tags": [ "python" ], "Title": "General feedback on ChangeableRange object" }
11295
<p>Suppose we are writing a GUI toolkit in C++ (though this question may also apply to other languages). We have a button class with a member function <code>hide</code>, which hides the button. This member function takes a Boolean parameter <code>animated</code> to control if the button should be hidden with an animation.</p> <pre><code>class Button { public: // Rule of three, etc… void hide(bool animated); }; </code></pre> <p>When invoking this member function, it may not be clear what it does.</p> <pre><code>Button button; button.hide(false); // well, does it hide the button or not? // what does "false" even mean here?! </code></pre> <hr> <p>We could rewrite this using a Boolean enum.</p> <pre><code>class Button { public: // Rule of three, etc… enum Animated : bool { Animate = true, DoNotAnimate = false, }; void hide(Animated animated); }; </code></pre> <p>Now if we call it, everything becomes more clear.</p> <pre><code>Button button; button.hide(Button::DoNotAnimate); </code></pre> <hr> <p>Is this a good thing to do? Does it improve clarity of the code, or is it just overkill and should we use separate documentation (Doxygen-like) for this instead?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-23T18:10:56.833", "Id": "199519", "Score": "0", "body": "I dunno if they are in C++, but a good alternative that does not require a new type to be defined is using a named parameter. `button.hide(animated: false);`, for example. Otherwise it may be a good idea to try to use more general-purpose enums if possible, rather than overly-specific ones, but I would definitely prefer it to the `hide(false)` version. Another possibility is to use two separate named methods, maybe `hideWithAnimation` and `hideNoAnimation` or something." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-01T10:50:45.547", "Id": "331218", "Score": "0", "body": "hide() should hide the button, and take no parameter. If buttons need to know different ways to hide themselves, then maybe they should have state (e.g. setHideAnimationOn()), or have different types (AnimatedButton vs NormalButton), or be called with different methods (hideWithAnimation() vs hide())." } ]
[ { "body": "<p>I think it is always a good idea to improve clarity of the code, and your change does improve clarity indeed.</p>\n\n<p>If this is the only use of that enum, I would consider it too high of a cost to introduce that enumeration though. I came to adopt the Clang practice on that issue</p>\n\n<pre><code>Button button;\nbutton.hide(false /* don't animate */);\n</code></pre>\n\n<p>Doxygen doesn't help on impoving clarity in the calling code, which is the issue here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T14:16:17.827", "Id": "439621", "Score": "0", "body": "What does it cost exactly? Microseconds of compilation time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T20:14:31.250", "Id": "439658", "Score": "2", "body": "@Vla the cost is in terms of cluttering your code with an enum type declarations. 7 years later and with 7 years more programming experience, I'm not too sure anymore of the generality of that assertion, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T19:36:47.817", "Id": "440439", "Score": "0", "body": "Hmm... I'd say the clutter point is valid, but `bool` enums are typically small enough to condense to a single line and still be readable, thus rendering it a non-issue. Commentation is valid if guaranteed to be visible (such as if offline documentation is provided or the source code is available), but typically less readily available from an IDE. Overall, I'd say the cost is outweighed by the benefit." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T09:46:33.567", "Id": "11301", "ParentId": "11300", "Score": "7" } }, { "body": "<p>I think the enum is a very nice solution here. And in a way I disagree with Johannes, even for single-use the enum improves readability and discoverability of the API, and writing it is a negligible effort; and I’d be wary of using comments as in his example, they scream “hack”.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T13:43:25.093", "Id": "19927", "Score": "0", "body": "I think that it's good to be consistent (i.e. either never use Boolean enums or always use them), and I agree about the comments." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T13:23:21.747", "Id": "12385", "ParentId": "11300", "Score": "30" } }, { "body": "<p>If the method does one thing, in this case, hides the button there shouldn't be a parameter at all: <code>void Hide()</code>. Conversely, you can create a method <code>void Show()</code> that only shows the button. You can even have another to check if it is currently visible: <code>bool IsVisible()</code> which just returns the current state of a member <code>bool</code>.</p>\n\n<p>The <code>void Show()</code> and <code>void Hide()</code> methods can delegate their calls to a method that changes the state of the member <code>bool</code>: <code>void Visible(bool is_visible)</code>:</p>\n\n<p>Definition:</p>\n\n<pre><code>class Button {\n public:\n //Other methods...\n void Show();\n void Hide();\n bool IsVisible();\n private: //or protected:, depending on your requirements\n //Other methods...\n void Visible(bool is_visible);\n //Other members...\n bool _visible;\n};\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>void Button::Show() {\n Visible(true);\n}\n\nvoid Button::Hide() {\n Visible(false);\n}\n\nbool Button::IsVisible() {\n return _visible;\n}\n\nvoid Button::Visible(bool is_visible) {\n _visible = is_visible;\n}\n</code></pre>\n\n<p>The <code>void Visible(bool is_visible)</code> member method enforces that only one function has the responsibility to change the <code>_visible</code> member and makes it so there is only one place that needs to change if the requirement changes.</p>\n\n<p>All of these methods make the code a lot cleaner and less ambiguous. Each method also only does exactly one thing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T15:57:12.773", "Id": "19942", "Score": "4", "body": "Is suggest you read the question. *This member function takes a Boolean parameter `animated` to control if the button should be hidden with an animation.*" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T15:55:42.013", "Id": "12390", "ParentId": "11300", "Score": "0" } }, { "body": "<p>In general I'm all for enums over booleans, especially when you have a string of \"flags\" that you need to pass into a function since booleans get... unreasonable at that point.</p>\n\n<p>In this case and similar ones though there's another option; <code>hide()</code> and <code>show()</code> are the \"do this right now\" versions of the functions and <code>animate_hide()</code> and <code>animate_show()</code> do the same work but asynchronously. I bring this up because I suspect that the body of the \"combined\" function would largely be one if/else statement:</p>\n\n<pre><code>void Button::hide(bool animated) // or whatever parameter type is appropriate\n{\n if (animated)\n {\n // do animated work, set up timers and callbacks etc.\n }\n else\n {\n // do immediate work\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T02:29:40.160", "Id": "21091", "ParentId": "11300", "Score": "7" } } ]
{ "AcceptedAnswerId": "12385", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T09:41:24.990", "Id": "11300", "Score": "38", "Tags": [ "c++", "enum" ], "Title": "Boolean enums: improved clarity or just overkill?" }
11300
<p>I have an HTML table representing a database table and a sidebar which holds different anchors ready to perform CRUD operations on click.</p> <p>Because the hrefs in the anchors aren't in general valid for all columns I have written a script which automatically inserts the id of a selected column into the hrefs:</p> <pre><code>/localhost/image/var/edit =&gt; /localhost/image/4/edit </code></pre> <p>The code I have written works but it isn't very clean and smart :( Could somebody take a look and say where I have space of improvement?</p> <pre><code>&lt;script type="text/javascript"&gt; $('table tr').click(function(){ $('.selected').removeClass('selected'); $(this).addClass('selected'); var name = $(this).find('td:nth-child(2)').html(); $('.image_bar ul li a').each(function(){ $(this).attr('href', $(this).attr('href').replace('var', name)); }); }); &lt;/script&gt; </code></pre> <p>How could I improve the <code>td:nth-child(2)</code> selector and the long line modifying the link?</p> <p>EDIT:</p> <pre><code>&lt;aside class="left image_bar"&gt; &lt;ul&gt; {% if image is defined %} &lt;li&gt;&lt;a href="{{ path('AcmeCoreBundle_Image_index')}}"&gt;Bilder verwalten&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{{ path('AcmeCoreBundle_Image_show', { name: image.name }) }}"&gt;Bild betrachten&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{{ path('AcmeCoreBundle_Image_new') }}"&gt;Bild hinzufügen&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{{ path('AcmeCoreBundle_Image_edit', { name: image.name }) }}"&gt;Bild bearbeiten&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{{ path('AcmeCoreBundle_Image_delete', { name: image.name }) }}"&gt;Bild löschen&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li&gt;&lt;a href="{{ path('AcmeCoreBundle_Image_index')}}"&gt;Bilder verwalten&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{{ path('AcmeCoreBundle_Image_show', { name: 'var' }) }}"&gt;Bild betrachten&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{{ path('AcmeCoreBundle_Image_new') }}"&gt;Bild hinzufügen&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{{ path('AcmeCoreBundle_Image_edit', { name: 'var' }) }}"&gt;Bild bearbeiten&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{{ path('AcmeCoreBundle_Image_delete', { name: 'var' }) }}"&gt;Bild löschen&lt;/a&gt;&lt;/li&gt; {% endif %} &lt;/ul&gt; &lt;/aside&gt; </code></pre> <p>As you see when having an available singe object (while editing, showing, deleting) the server side renders the right id/name into the href. Under circumstances when I only have a collection of objects or none object available, jquery has to do the rendering of the right urls. Also some URLs don't require an id (new, index)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T20:43:27.933", "Id": "18163", "Score": "0", "body": "`$('.image_bar ul li a')` selects all elements from document, not from the selected row. Are you sure that it is correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T05:12:15.463", "Id": "18169", "Score": "0", "body": "Yes, I have a sidebar which contains the hrefs to the action urls (new, edit, delete,...). The tables are selected above :)" } ]
[ { "body": "<pre><code>&lt;script type=&quot;text/javascript&quot;&gt;\n$(function () {\n var $lastSelected = $([]);\n $('tr').click(function () { //tr tag is always inside a table\n $lastSelected.removeClass('selected'); //by caching this variable in the closure we don't need to traverse for it again\n $lastSelected = $(this).addClass('selected');\n });\n\n $('.image_bar a').click(function (e) { \n var url = $(this).attr('href').split('var'), //both checks if var is there and prepares for the replacement\n name;\n if ($lastSelected.length === 0) {\n return url.length==1; //any urls that do not have var in them will still work\n }\n\n name = $lastSelected.children().eq(2).html();\n window.location = url.join(name);\n });\n});\n&lt;/script&gt;\n</code></pre>\n<p>Here I am assuming your toolbar is outside of your table.</p>\n<h2>About the changes:</h2>\n<ol>\n<li><code>$(function () {</code> lets you move this script tag elsewhere in your document (perhaps to an external script)</li>\n<li>By caching <code>$lastSelected</code>, fewer DOM traversals need to happen.</li>\n<li>Knowing <code>$lastSelected</code> enables moving the <code>$.fn.each</code> call out of the tr click event by setting name inside of it.</li>\n<li>Since the <code>.each</code> call is no longer in the click event, it can be a click event of its own (no more need to iterate over it).</li>\n<li>Instead of modifying the <code>a</code> tags we can just set window.location since we are now in the event where the user has clicked.</li>\n<li>Finally, if a row is not selected up front, the $lastSelected variable will not provide a valid name. Thus we shouldn't allow the link to be clicked if it contains <code>var</code> (done by the return statement).</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T05:27:10.703", "Id": "18171", "Score": "0", "body": "Hi, I have added the twig-template of the sidebar. So you see how I thought the second part. This is also the reason why I have to use .each(). The ideal would be if I could set a js-compatible variable (at the moment the string 'var') and jQuery only has to insert this one. This would solve many things at once: 1. The user can't request a none existing side when not selected something 2. We would spare the parsing Is there any solution which would come this idea next? Regards, Bodo" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T09:15:33.080", "Id": "18175", "Score": "0", "body": "Nice answer! What's the difference between $(function() {}); and (function() {})()?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T12:47:08.157", "Id": "18188", "Score": "0", "body": "@Cygal: `(function () {}())` is an automatically executing anonymous function. `$(function () {})` is shorthand for `$(document).ready(function () {})` with the benefit that `$(document)` doesn't need to be created." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T12:50:04.047", "Id": "18189", "Score": "0", "body": "@BillBarry I knew about IIFEs but not about that shorthand. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T18:01:20.703", "Id": "18207", "Score": "0", "body": "@BillBarry did you read my update? Any suggestions how I could implement a better placeholder?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T19:03:34.383", "Id": "18213", "Score": "0", "body": "@kyogron: The placeholder is fine, I don't think you need the .each anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T07:18:32.173", "Id": "18243", "Score": "0", "body": "I tried the script and the last part didn't work :(. Another idea would be to set a var in the placeholder the first time and after this only the var has to get changed. Or I set the links from beginning in javascript" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T20:52:16.183", "Id": "11316", "ParentId": "11309", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T15:02:27.357", "Id": "11309", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Column selection and URL modification" }
11309
<p>I'm working on an application that turns a raw camera image into a binary (pure black/white) image and I need this to happen as fast as possible for swift further processing. This is what my code currently looks like:</p> <pre><code>public static boolean[][] createBinaryImage( Bitmap bm ) { int[] pixels = new int[bm.getWidth()*bm.getHeight()]; bm.getPixels( pixels, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight() ); int w = bm.getWidth(); // Calculate overall lightness of image long gLightness = 0; int lLightness; int c; for ( int x = 0; x &lt; bm.getWidth(); x++ ) { for ( int y = 0; y &lt; bm.getHeight(); y++ ) { c = pixels[x+y*w]; lLightness = ((c&amp;0x00FF0000 )&gt;&gt;16) + ((c &amp; 0x0000FF00 )&gt;&gt;8) + (c&amp;0x000000FF); pixels[x+y*w] = lLightness; gLightness += lLightness; } } gLightness /= bm.getWidth() * bm.getHeight(); gLightness = gLightness * 5 / 6; // Extract features boolean[][] binaryImage = new boolean[bm.getWidth()][bm.getHeight()]; for ( int x = 0; x &lt; bm.getWidth(); x++ ) for ( int y = 0; y &lt; bm.getHeight(); y++ ) binaryImage[x][y] = pixels[x+y*w] &lt;= gLightness; return binaryImage; } </code></pre> <p>As you can see, it uses a global threshold to tell apart the black and white pixels. I recently switched from <code>bm.getPixel</code> to <code>bm.getPixels</code> and this yielded a speed improvement of ~33%. Now my question is if there is anything else I can do to speed things up?</p> <p>It currently takes &lt;0.5 seconds to process 558x256 image and this is reasonable for my application, but I wonder if there's room for any other simple optimizations.</p>
[]
[ { "body": "<p>You can get rid of the nested loop, replacing this</p>\n\n<pre><code>for ( int x = 0; x &lt; bm.getWidth(); x++ )\n {\n for ( int y = 0; y &lt; bm.getHeight(); y++ )\n {\n c = pixels[x+y*w];\n lLightness = ((c&amp;0x00FF0000 )&gt;&gt;16) + ((c &amp; 0x0000FF00 )&gt;&gt;8) + (c&amp;0x000000FF);\n pixels[x+y*w] = lLightness;\n gLightness += lLightness;\n }\n }\n</code></pre>\n\n<p>With this:</p>\n\n<pre><code>int size = bm.getWidth()*bm.getHeight();\nfor (int i = 0; i &lt; size; i++) {\n c = pixels[i];\n // etc.\n}\n</code></pre>\n\n<p>It will at least save one <code>x+y*w</code> operation per pixel.</p>\n\n<p>It <em>may</em> be advantageous to calculate size into a separate variable as above, instead of doing it inside the loop, as in <code>for (int i = 0; i &lt; bm.getWidth()*bm.getHeight(); i++)</code>. The condition is checked at each round so you would end up calling the getters at each round, and who knows what's in them? The JIT compiler may be able to optimize this kind of stuff away - and probably will, if the getters are simple \"return class member\" statements - but at least it's not guaranteed.</p>\n\n<p>More substantial improvements can be got by sacrificing perfection. Maybe you needn't take each pixel into account for calculating the threshold? Perhaps count only every <code>10</code>th on each direction? Then you would probably use the nested loop again. Like this:</p>\n\n<pre><code>int width = bm.getWidth();\nint height = bm.getHeight();\n\nfor ( int x = 0; x &lt; width; x+=10; )\n{\n for ( int y = 0; y &lt; height; y+=10; )\n {\n // etc.\n }\n}\n\ngLightness /= (width / 10) * (height / 10);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T13:34:31.013", "Id": "11338", "ParentId": "11312", "Score": "2" } } ]
{ "AcceptedAnswerId": "11338", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T19:16:52.963", "Id": "11312", "Score": "2", "Tags": [ "java", "android" ], "Title": "Fast image binarization on Android" }
11312
<p>A question of organization and best practices with Wordpress templates:</p> <ul> <li>Where should I put my variables? Directly in the template? In a separate file via <code>includes()</code>?</li> <li>Should I place all variables at the top of the template, or is it OK to mix them in with the HTML?</li> <li>Should HTML be included directly in the variable, or is something like this OK?</li> </ul> <pre><code>&lt;?php if($next_show) { ?&gt; &lt;a href="&lt;?php echo $next_show_link; ?&gt;" class="next-show c3"&gt;&lt;?php echo $next_show; ?&gt;&lt;/a&gt; &lt;?php } ?&gt; </code></pre> <p>I'm a PHP novice, so if there's any guidance or pointers regarding anything that can be done more efficiently, any feedback is much appreciated!</p> <pre><code>&lt;?php get_header(); require_once(THEMEASSETS . '/functions/frontend/alfa-nav.php'); $uri = my_url(); $uri = removeqsvar($uri, 'orden'); $genero = get_query_var('genero'); global $query_string; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array(); wp_reset_query(); rewind_posts(); if($genero) { $taxtitle = explode('+',$genero); $taxtitle = implode(' + ', $taxtitle); $genreterm = genre_format($uri); query_posts($query_string.'&amp;orderby=title&amp;order=ASC'); } else { $taxtitle = get_query_var('term'); $args = array( 'post_type' =&gt; 'artistas', 'posts_per_page' =&gt; -1, ); query_posts($args); } $queried_terms = array(); $showcount = 0; if ( $wp_query-&gt;have_posts() ) : while ( $wp_query-&gt;have_posts() ) : $wp_query-&gt;the_post(); $postid = $post-&gt;ID; if( has_term( '', 'alfa', $postid) ) { $terms = get_the_terms( $postid, 'alfa' ); foreach($terms as $term) { $myterm = $term-&gt;slug; if(in_array($myterm, $queried_terms)) {continue;} $queried_terms[] = $myterm; } } $next_show = get_post_meta($postid, '_artistEventTitle', true); if($next_show) {$showcount++;} endwhile; endif; rewind_posts(); wp_reset_query(); ?&gt; &lt;section role="main" class="wrapper"&gt; &lt;div class="inner filter-wrap full-wrap"&gt; &lt;div class="sidebar pr qt btw"&gt; &lt;?php the_widget('Taxonomy_Drill_Down_Widget', array( 'mode' =&gt; 'lists', 'taxonomies' =&gt; array( 'genero', 'alfa') // list of taxonomy names )); ?&gt; &lt;/div&gt; &lt;div class="content single-content"&gt; &lt;?php include('includes/breadcrumbs.php'); ?&gt; &lt;header class="archive-header"&gt; &lt;h1 class="kilo archive-title"&gt;&lt;strong class="section-title"&gt;Artistas:&amp;nbsp;&lt;/strong&gt;&lt;span class="tax-title"&gt;&lt;?php echo ucwords($taxtitle); ?&gt;&lt;b class="count"&gt;&amp;nbsp;(&lt;?php echo $total = $wp_query-&gt;found_posts; ?&gt;)&lt;/b&gt;&lt;/span&gt;&lt;/h1&gt; &lt;/header&gt; &lt;?php bam_artist_alfa($queried_terms, $alfas); ?&gt; &lt;nav class="nav-hor w100 page-nav"&gt; &lt;div class="page-wrap"&gt; &lt;?php global $wp_query; $big = 999999999; // need an unlikely integer echo $pagelinks = paginate_links( array( 'base' =&gt; str_replace( $big, '%#%', get_pagenum_link( $big ) ), 'format' =&gt; '?paged=%#%', 'current' =&gt; max( 1, get_query_var('paged') ), 'total' =&gt; $wp_query-&gt;max_num_pages, 'type' =&gt; 'list', 'prev_text' =&gt; '', 'next_text' =&gt; '' ) ); $showclass = ($showcount == 0 ? 'empty ' : ''); if(isset($_GET['orden']) &amp;&amp; $showcount &gt; 0) { $nombreclass = ' bg1 c2'; $fechaclass = ' bg2 c1 current'; $nombreuri = ' href="'.removeqsvar(my_url(), 'orden').'"'; } else { $nombreclass = ' bg2 c1 current'; $fechaclass = ' bg1 c2'; $nombreuri = ''; } if($showcount == 0 || isset($_GET['orden'])) { $fechaurl = ''; } elseif(!isset($_GET['alfa']) &amp;&amp; !isset($_GET['genero'])) { $fechaurl = ' href="'.$uri.'?orden=fecha"'; } else { $fechaurl = ' href="'.$uri.'&amp;orden=fecha"'; } ?&gt; &lt;/div&gt; &lt;div class="artist-sort caps bo"&gt; &lt;span class="me btn-round btn"&gt;Ordenar por:&lt;/span&gt; &lt;a class="btn btn-round&lt;?php echo $nombreclass; ?&gt;"&lt;?php echo $nombreuri; ?&gt;&gt;Nombre&lt;/a&gt; &lt;a class="&lt;?php echo $showclass; ?&gt;btn btn-round&lt;?php echo $fechaclass; ?&gt;"&lt;?php echo $fechaurl; ?&gt;&gt; Proxima Fecha &lt;/a&gt; &lt;/div&gt; &lt;/nav&gt; &lt;div class="ajax-fade artist-wrap grid-wrap group"&gt; &lt;div class="group"&gt; &lt;?php query_posts($query_string.'&amp;orderby=title&amp;order=ASC&amp;paged='.$paged); if ( $wp_query-&gt;have_posts() ) : while ( $wp_query-&gt;have_posts() ) : $wp_query-&gt;the_post(); $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), "artist-thumb" ); $title = get_the_title(); $link = get_permalink(); $next_show = get_post_meta($post-&gt;ID, '_artistEventTitle', true); $next_show_link = get_post_meta($post-&gt;ID, '_artistEventLink', true); ?&gt; &lt;div class="artist-grid qt fl&lt;?php echo ($next_show ? ' has-date' : ''); ?&gt;"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" class="round-t img"&gt; &lt;?php if($image) { ?&gt; &lt;img src="&lt;?php echo $image[0]; ?&gt;" class="round-t" /&gt; &lt;?php } ?&gt; &lt;/a&gt; &lt;div class="bg2 c1 artist-title round-b bo"&gt; &lt;h1 class="alpha"&gt;&lt;a href="&lt;?php echo $link; ?&gt;"&gt;&lt;?php echo $title; ?&gt;&lt;/a&gt;&lt;/h1&gt; &lt;?php if($next_show) { ?&gt; &lt;a href="&lt;?php echo $next_show_link; ?&gt;" class="next-show c3"&gt;&lt;?php echo $next_show; ?&gt;&lt;/a&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; endif; ?&gt; &lt;/div&gt; &lt;nav class="nav-hor page-nav"&gt; &lt;div class="page-wrap"&gt; &lt;?php echo $pagelinks; ?&gt; &lt;/div&gt; &lt;/nav&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- main --&gt; &lt;/div&gt; &lt;!-- inner --&gt; &lt;/section&gt; &lt;!-- wrapper --&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[]
[ { "body": "<blockquote>\n <p>Where should I put my variables? Directly in the template? In a separate file via includes()?</p>\n</blockquote>\n\n<p>Directly in the template, it makes it easier to find them.</p>\n\n<blockquote>\n <p>Should I place all variables at the top of the template, or is it OK to mix them in with the HTML?</p>\n</blockquote>\n\n<p>Right before where they are used. Again it makes it easier to find them. If you have some variable used several time throughout the template file, then it might make sense to put on top though.</p>\n\n<blockquote>\n <p>Should HTML be included directly in the variable, or is something like this OK?</p>\n</blockquote>\n\n<p>The way you've done it is the right way. Always avoid including HTML in variables if you can.</p>\n\n<p>In my opinion, there's too much code at the top and within your template file. See if you can refactor some of this code into utility functions. You can them put this code in <strong>functions.php</strong>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T11:33:47.610", "Id": "11331", "ParentId": "11314", "Score": "2" } } ]
{ "AcceptedAnswerId": "11331", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T19:35:28.373", "Id": "11314", "Score": "2", "Tags": [ "php" ], "Title": "Organizing a wordpress template with lots of variables" }
11314
<p>I'm trying to learn Python through the excellent online book <a href="http://getpython3.com/diveintopython3/" rel="noreferrer">Dive Into Python 3</a>. I have just finished chapter 2 about data types and felt like trying to write a program on my own.</p> <p>The program takes an integer as input and factorizes it into prime numbers:</p> <pre><code>$ python main.py 6144 6144 -&gt; (2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3) $ python main.py 253789134856 253789134856 -&gt; (2, 2, 2, 523, 60657059) </code></pre> <p>I'd like to know if I could improve it in any way. Or if I've used any bad practice and so on.</p> <pre><code>#!/usr/bin/python import sys import math def prime_factorize(n): factors = [] number = math.fabs(n) while number &gt; 1: factor = get_next_prime_factor(number) factors.append(factor) number /= factor if n &lt; -1: # If we'd check for &lt; 0, -1 would give us trouble factors[0] = -factors[0] return tuple(factors) def get_next_prime_factor(n): if n % 2 == 0: return 2 # Not 'good' [also] checking non-prime numbers I guess? # But the alternative, creating a list of prime numbers, # wouldn't it be more demanding? Process of creating it. for x in range(3, int(math.ceil(math.sqrt(n)) + 1), 2): if n % x == 0: return x return int(n) if __name__ == &quot;__main__&quot;: if len(sys.argv) != 2: print(&quot;Usage: %s &lt;integer&gt;&quot; % sys.argv[0]) exit() try: number = int(sys.argv[1]) except ValueError: print(&quot;'%s' is not an integer!&quot; % sys.argv[1]) else: print(&quot;%d -&gt; %s&quot; % (number, prime_factorize(number))) </code></pre> <p><strong>Edit:</strong></p> <p>@JeffMercado: Interesting link as I haven't encountered this before. And yes, the memoization technique should be easy to implement in my case since it is basically the same as the Fibonacci example.</p> <p>In the Fibonacci example, they have a map (dictionary in Python?) outside the function, but should I do that? Global variables “are bad”? If that's the case, where does it belong? In the function prime_factorize() and I pass the map as an argument? I'm having a hard time deciding things like this, but I guess it gets easier with experience...</p> <p>@WinstonEwert:</p> <blockquote> <p>Prime factorization really only makes sense for integers. So you really use abs not fabs.</p> </blockquote> <p>I couldn't find abs when I ran help(math), only fabs. I thought fabs was my only choice but I just found out that abs doesn't even reside in the math module. Fixed.</p> <blockquote> <p>Tuples are for heterogeneous data. Keep this a list. It is conceptually a list of numbers, and it so it should be stored in a python list not a tuple.</p> </blockquote> <p>You write that tuples are for heterogeneous data. I searched SO and many seems to be of this opinion. However, in <a href="http://getpython3.com/diveintopython3/native-datatypes.html#tuples" rel="noreferrer">the book</a> I'm following, the author gives a few points for using a tuple:</p> <blockquote> <p>Tuples are faster than lists. If you’re defining a constant set of values and all you’re ever going to do with it is iterate through it, use a tuple instead of a list.</p> <p>It makes your code safer if you “write-protect” data that doesn’t need to be changed. Using a tuple instead of a list is like having an implied assert statement that shows this data is constant, and that special thought (and a specific function) is required to override that.</p> </blockquote> <p>That is why a returned a tuple. Is the author's points valid or just not in this case?</p> <blockquote> <p>Your expression, int(math.ceil(math.sqrt(n)) + 1) seems to be more complicated that it needs to be. Couldn't you get by with int(math.sqrt(n) + 1).</p> </blockquote> <p>The upper value of range was unnecessarily complicated. Fixed.</p> <blockquote> <p>Again, why are you trying to support something that isn't an int?</p> </blockquote> <p>I was returning int(n) from get_next_prime_factor(n) since the number that is passed in to the function becomes a float when I divide it (in prime_factorize), so if I return just n from the function, I return a float which gets added to the list 'factors'. When I then print the factors, I get e.g. '11.0' as the last factor for the number 88.</p> <p>Any other way to fix that?</p> <blockquote> <p>I'd pass an exit code to indicate failure</p> </blockquote> <p>Should I just exit(1) or something like that?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T23:11:52.770", "Id": "18165", "Score": "2", "body": "You should definitely create a list of the prime numbers that you've found and keep it as your find more. The higher the numbers you get the more iterations you would have to do unnecessarily. Keyword is, [Dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming). Look at the [Fibonacci Sequence](http://en.wikipedia.org/wiki/Dynamic_programming#Fibonacci_sequence) example as it should be very similar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T22:50:03.427", "Id": "18231", "Score": "0", "body": "@JeffMercado: aka memoization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T02:04:03.170", "Id": "18234", "Score": "0", "body": "In response to your tuple question, you should only use tuples if you are returning a fixed number of values. If it varies, then a list would be more appropriate. The amount of numbers you are returning here varies so you should be using lists." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T01:04:15.000", "Id": "18260", "Score": "0", "body": "If you want to respond to the reviewers, its best to comment on the posts. We aren't notified if you edit your answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T01:26:07.873", "Id": "18262", "Score": "0", "body": "Regarding tuple performance: the question of tuple vs list performance is complicated. It depends on what you are doing. Its not true to simply state that tuples are faster. In this case, you waste a bunch of time converting your list into the tuple. That time is going to be far more significant than anytime you might save by using tuples." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T01:29:45.343", "Id": "18263", "Score": "0", "body": "Regarding tuples being safer: it protects you from accidentally modifying the list when you didn't mean to. But I don't really have a problem with accidentally modifying lists, so I don't see the point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T01:30:34.093", "Id": "18264", "Score": "0", "body": "For division use the `//` operator to do integer division. And use `exit(1)`, yes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T03:18:11.870", "Id": "18266", "Score": "0", "body": "@WinstonEwert: My respone was too big for a comment so I thought it would work by editing my original post. Now I know that it doesn't work. I'll just split my response the next time I need to." } ]
[ { "body": "<pre><code>#!/usr/bin/python\n\nimport sys\nimport math\n\ndef prime_factorize(n):\n factors = []\n number = math.fabs(n)\n</code></pre>\n\n<p>Prime factorization really only makes sense for integers. So you really use abs not fabs.</p>\n\n<pre><code> while number &gt; 1:\n factor = get_next_prime_factor(number)\n factors.append(factor)\n number /= factor\n\n if n &lt; -1: # If we'd check for &lt; 0, -1 would give us trouble\n factors[0] = -factors[0]\n\n return tuple(factors)\n</code></pre>\n\n<p>Tuples are for heterogeneous data. Keep this a list. It is conceptually a list of numbers, and it so it should be stored in a python list not a tuple.</p>\n\n<pre><code>def get_next_prime_factor(n):\n if n % 2 == 0:\n return 2\n\n\n # Not 'good' [also] checking non-prime numbers I guess?\n # But the alternative, creating a list of prime numbers,\n # wouldn't it be more demanding? Process of creating it.\n for x in range(3, int(math.ceil(math.sqrt(n)) + 1), 2):\n</code></pre>\n\n<p>Your expression, <code>int(math.ceil(math.sqrt(n)) + 1)</code> seems to be more complicated that it needs to be. Couldn't you get by with <code>int(math.sqrt(n) + 1)</code>. </p>\n\n<pre><code> if n % x == 0:\n return x\n\n return int(n)\n</code></pre>\n\n<p>Again, why are you trying to support something that isn't an int?</p>\n\n<pre><code>if __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Usage: %s &lt;integer&gt;\" % sys.argv[0])\n exit()\n</code></pre>\n\n<p>I'd pass an exit code to indicate failure</p>\n\n<pre><code> try:\n number = int(sys.argv[1])\n except ValueError:\n print(\"'%s' is not an integer!\" % sys.argv[1])\n else:\n print(\"%d -&gt; %s\" % (number, prime_factorize(number)))\n</code></pre>\n\n<p>Algorithmwise, it will be more efficient to keep a list. They key is to keep information about the primes used between calls. In particular, you want a list that indicates the smallest prime factor for example</p>\n\n<pre><code>factors[9] = 3, factors[15] = 3, factors[42] = 21\n</code></pre>\n\n<p>A simple modification of the Sieve of Eratosthenes should suffice to fill that in. Then easy lookups into the list should tell you exactly which prime is next. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T05:18:28.920", "Id": "18170", "Score": "0", "body": "`int(math.ceil(math.sqrt(n)) + 1)` equates to `int(sqrt(n)) + 2` actually. You're right though, this is unnecessary as there are no prime factors > `sqrt(n)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T05:58:00.393", "Id": "18172", "Score": "1", "body": "Using the Sieve might be problematic since it seems the range of numbers to support is unbounded. It will need to support up to the range of `long` numbers since `253789134856` is well beyond the range of `int`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T22:57:53.337", "Id": "18232", "Score": "0", "body": "@JeffMercado, good point." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T04:20:27.913", "Id": "11320", "ParentId": "11317", "Score": "5" } }, { "body": "<p>It would only make a difference in the case of products of big primes, but you could remember the latest factor found and restart from here (and not from 3):</p>\n\n<pre><code>def prime_factorize(n):\n factors = []\n number = abs(n)\n factor = 2\n\n while number &gt; 1:\n factor = get_next_prime_factor(number, factor)\n factors.append(factor)\n number /= factor\n\n if n &lt; -1: # If we'd check for &lt; 0, -1 would give us trouble\n factors[0] = -factors[0]\n\n return factors\n\n\ndef get_next_prime_factor(n, f):\n if n % 2 == 0:\n return 2\n\n # Not 'good' [also] checking non-prime numbers I guess?\n # But the alternative, creating a list of prime numbers,\n # wouldn't it be more demanding? Process of creating it.\n for x in range(max(f, 3), int(math.sqrt(n) + 1), 2):\n if n % x == 0:\n return x\n\n return n\n</code></pre>\n\n<p>I also agree about the strangeness of handling non integers, the need for an exit code, that a list is better here than tuple, etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T22:06:15.853", "Id": "11359", "ParentId": "11317", "Score": "1" } }, { "body": "<p>You could speed this part up a bit by observing for factor>3, that every factor will be either of the form 6k - 1, or 6k + 1, for integers k >= 1.</p>\n\n<pre><code>def get_next_prime_factor(n, factor):\n if n % 2 == 0:\n return 2\n if n % 3 == 0:\n return 3\n\n for x in range(int(factor/6), int(math.sqrt(n)/6) + 1):\n if n % (6*x-1) == 0:\n return 6*x-1\n\n if n % (6*x+1) == 0:\n return 6*x+1\n\n return int(n)\n</code></pre>\n\n<p>As suggested before, it will also greatly help you to keep track of the last found factor.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T23:36:07.637", "Id": "11378", "ParentId": "11317", "Score": "0" } } ]
{ "AcceptedAnswerId": "11320", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T21:23:06.467", "Id": "11317", "Score": "8", "Tags": [ "python", "primes" ], "Title": "Prime factorization of a number" }
11317
<p>I've just started with coffeescript, and I saw <a href="http://blog.8thlight.com/uncle-bob/2012/04/20/Why-Is-Estimating-So-Hard.html" rel="nofollow">http://blog.8thlight.com/uncle-bob/2012/04/20/Why-Is-Estimating-So-Hard.html</a> which has a little programming problem, so I figured I'd do it in coffeescript (which seemed easy enough to do... )</p> <p>anyways, I ended up with :-</p> <pre><code>lineEndings = ( s, len ) -&gt; words = s.split ' ' line = '' result = '' words.map ( word ) -&gt; if line.length == 0 line = word else if line.length + 1 + word.length &lt;= len line = line + ' ' + word else result = result + line + '\n' line = word result + line getty = "Four score and seven years ago our fathers brought forth upon this continent a new nation, conceived in liberty and dedicated to the proposition that all men are created equal" console.log lineEndings getty, 13 </code></pre> <p>I'm looking for any ways I could make this simpler coffeescript.</p> <p>( I just used nodejs with coffescript installed to test this )</p>
[]
[ { "body": "<p>This is how I would write it.</p>\n\n<pre><code>lineEndings = (s, len) -&gt;\n words = s.split ' '\n line = []\n result = []\n for word in words\n if line.length + 1 + word.length &lt;= len\n line = [line..., word]\n else\n result.push line.join ' '\n line = [word]\n lastLine = line.join ' '\n result.push lastLine if lastLine\n result.join \"\\n\"\n</code></pre>\n\n<p>There's nothing wrong with how you wrote it, though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T13:24:28.480", "Id": "11337", "ParentId": "11318", "Score": "2" } }, { "body": "<ol>\n<li>In your case you should use <code>forEach</code> method or <code>for</code> statement instead of <code>map</code>. <code>map</code> has more specific purpose.</li>\n<li>You could extract more generic method, though it's not necessary.</li>\n</ol>\n\n<p>.</p>\n\n<pre><code>slice_reduce = (xs, slice_predicate, reduce_functor) -&gt;\n reduction = nil\n slices = []\n if xs.length &gt; 0\n for x in xs\n if slice_predicate(reduction, x)\n slices.push(reduction)\n reduction = x\n else\n reduction = reduce_functor(reduction, x)\n slices.push(reduction)\n slices \n\nword_wrap = (s, len) -&gt;\n slice_reduce(s.split(/\\s+/),\n ((r, w) -&gt; r.length + 1 + w.length &lt;= len),\n ((r, w) -&gt; r + ' ' + w)).\n join('\\n')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T20:15:04.310", "Id": "11356", "ParentId": "11318", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T22:24:05.660", "Id": "11318", "Score": "1", "Tags": [ "coffeescript" ], "Title": "Is there any way to make this CoffeScript code simpler / smaller" }
11318
<p>Another stab at the <a href="http://en.wikipedia.org/wiki/Josephus_problem" rel="nofollow" title="Josephus problem">Josephus problem</a>, this time using Actors. <code>N</code> people stand in a circle and every <code>step</code>th person is eliminated until one is remaining. </p> <p>The way I solve it here is to give each actor a reference to their successor, and the actors send their successor a count of places since the last elimination. If an actor is eliminated, it replies with a reference to its successor so that the previous actor now links the one after.</p> <p>I've hardly used Actors before. I'd like general comments, but in particular I'm wondering:</p> <ul> <li>is using Actors appropriate for this problem?</li> <li>are the messages I used sensible?</li> <li>is the wait for reply necessary?</li> <li>how would you do it differently?</li> </ul> <p>btw I'm going to try this with Akka as well - if that will make any major difference to the solution that you know of, please mention!</p> <pre><code>object Josephus_Actors extends App { import actors._ val N = 40 val step = 3 case class Person(id: Int) extends Actor { Self =&gt; // would like to make `next` private[this], but it's then very tricky to set up var next: Person = _ private[this] var alive = true def act { while (alive) { // Messages consist of (count, sender) where count is distance from last man out receive { // last man standing case (_, Self) =&gt; { println("Winner: "+id) sys.exit(0) } // kill self case (x: Int, _) if x == step =&gt; { alive = false reply {next} } // kill next case (x: Int, _) if x == step - 1 =&gt; { // wait until we have received our next value next !? ((step, Self)) match { case a: Person =&gt; next = a case _ =&gt; } next ! (1, Self) } /* pass on message */ case (x: Int, _) =&gt; { next ! (x + 1, Self) } case other =&gt; println(id + " unrecognized message: " + other) } } } } val acts = 1 to N map Person acts foreach { p =&gt; // add reference to successor p.next = p.id match { case N =&gt; acts(0) case x =&gt; acts(x) } p.start() } acts(0) ! (1, null) } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T09:12:55.393", "Id": "18174", "Score": "1", "body": "It's a fun way to model the problem, sure. But it's probably more efficient to simply use a linked list for a naive implementation. Your wikipedia pages shows that the best solution uses dynamic programming and executes in O(n) time. So it's probably not appropriate, but a nice way to learn about actors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T18:37:33.043", "Id": "18211", "Score": "0", "body": "@Cygal this should be O(n) too and acts very much like a linked list. Actors are quite lightweight although prob not so much as a collection node. To me sending messages seems like just an un-typesafe form of method invocation but it may just be that I don't understand them properly yet" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T18:43:41.307", "Id": "18212", "Score": "0", "body": "I think their \"point\" is that they run concurrently in separate threads although that's of little use in this problem" } ]
[ { "body": "<blockquote>\n <p>would like to make <code>next</code> private[this], but it's then very tricky to set up</p>\n</blockquote>\n\n<p>To achieve that, you can define the initial next person as a <code>lazy val</code> field, and then define a <code>var</code> locally in the <code>act</code> method:</p>\n\n<pre><code>case class Person(id: Int) extends Actor { Self =&gt;\n private[this] lazy val initialNext: Person = acts((id + 1) % N)\n ...\n def act {\n var next = initialNext\n</code></pre>\n\n<p>The initialization then simplifies to</p>\n\n<pre><code>val acts = 1 to N map Person\nacts foreach { _.start }\nacts(0) ! (1, null)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-18T16:48:41.080", "Id": "13801", "ParentId": "11322", "Score": "2" } }, { "body": "<p>You use in your solution a synchronous call (<code>!?</code>) which prevents the actor from doing something else while waiting (in this example, this is not a problem). You could easily implement a <em>true</em> asynchronous solution by reacting on persons sent back in case that a person killed itself. The <code>act</code> method then looks as follows:</p>\n\n<pre><code>def act {\n var next = initialNext\n while (alive) {\n receive {\n // last man standing\n case (_, Self) =&gt; println(\"Winner: \"+id); sys.exit(0)\n\n // kill self\n case (`step`, _) =&gt; alive = false; reply {next}\n\n // receive killed \n case p: Person =&gt; next = p; next ! (1, Self)\n\n // pass on message\n case (x: Int, _) =&gt; next ! (x + 1, Self)\n\n case other =&gt; println(id + \" unrecognized message: \" + other)\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-18T17:03:02.003", "Id": "13802", "ParentId": "11322", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T05:57:07.163", "Id": "11322", "Score": "2", "Tags": [ "scala", "actor" ], "Title": "Scala: Josephus problem with Actors" }
11322
<p>I would be happy to hear feedback on my implementation of HttpClient. I am not so strong with error handling so I want to improve. My thought process behind this was that <a href="http://hc.apache.org/httpclient-3.x/exception-handling.html" rel="nofollow"><code>IOException</code>s can be recoverable and should be tried again</a>. Where as client exception isn't. Hope to hear your thoughts.</p> <pre><code>private HttpResponse execute(int httpVerb, boolean authHeader) throws NoInternetConnectionError, IOException, ClientProtocolException { try { Log.i(TAG, "setting header and executing"); switch (httpVerb) { case HTTP_POST: if (authHeader){ httpPost.addHeader(header); } return httpClient.execute(httpPost); case HTTP_PUT: if (authHeader){ httpPut.addHeader(header); } return httpClient.execute(httpPut); case HTTP_GET: if (authHeader){ httpGet.addHeader(header); } return httpClient.execute(httpGet); default: return null; } } catch (IOException e) { InternetChecker internetChecker = new InternetChecker(context); if (internetChecker.isInternetConnected() == false) { throw new NoInternetConnectionError("internet not connected"); } else { numberOfTries ++; if (numberOfTries &gt; 2) { throw new IOException(e.getMessage()); } else { Log.i(TAG, "executing for the " + String.valueOf(numberOfTries) + " time"); return execute(httpVerb, authHeader); } } } finally { numberOfTries = 0; Log.i(TAG, "finally block run"); } } </code></pre>
[]
[ { "body": "<ol>\n<li><p>I would create a common <code>executeRequest</code> method:</p>\n\n<pre><code>private HttpResponse executeRequest(final HttpUriRequest request, \n final String authHeader, final boolean authHeader) {\n if (authHeader){\n request.addHeader(authHeader); \n }\n return httpClient.execute(request);\n}\n</code></pre>\n\n<p>then remove the code duplication from the <code>case</code> branches. </p>\n\n<pre><code>switch (httpVerb) {\n case HTTP_POST:\n return executeRequest(httpPost, authHeader, header);\n case HTTP_PUT:\n return executeRequest(httpPut, authHeader, header);\n case HTTP_GET:\n return executeRequest(httpGet, authHeader, header);\n default:\n return null;\n}\n</code></pre>\n\n<p>Anyway, it doesn't seem too good that you have <code>httpPost</code>, <code>httpGet</code> and <code>httpPut</code> at the same time.</p></li>\n<li><p>Wouldn't it worth to check the result of <code>isInternetConnected()</code> at the beginning of the method? I'm not too familiar with Android development, maybe it's the best to put into the <code>catch</code> block. Anyway, if it is not a slow/costly service I would call at the beginning of the method too.</p></li>\n<li><p>Calling <code>String.valueOf(numberOfTries)</code> seem unnecessary. I could be simply</p>\n\n<pre><code>Log.i(TAG, \"executing for the \" + numberOfTries + \" time\");\n</code></pre></li>\n<li><p>I'd use a loop instead of recursion. Two links on the topic:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/4198289/java-exceptions-and-how-best-to-retry-when-a-connection-is-reset\">Exceptions, and how best to retry when a connection is reset?</a></li>\n<li><a href=\"http://fahdshariff.blogspot.com/2009/08/retrying-operations-in-java.html\" rel=\"nofollow noreferrer\">Retrying Operations in Java</a></li>\n</ul></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T15:32:24.220", "Id": "18198", "Score": "0", "body": "Thanks palacsint. Just a couple of questions if you don't mind. \n\n1. Why is it bad to have all 3 of them at the same time, after all I call the same method (execute) for each\n\n2. The internet connection can be lost at anytime. It could be there at the start when I check then gone once I do the work\n\n3. Didn't know I could put an in in there" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T15:52:33.057", "Id": "18201", "Score": "0", "body": "I have modified my code and its fairly obvious why I shouldn't be using the case. Thanks a lot!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T20:50:35.103", "Id": "18226", "Score": "0", "body": "1. Because two of the three always unnecessary. Post those parts (or the full code) as a new question and I'll check it. I think only one reference with `HttpUriRequest` type would be enough but it's hard to say more without the code.\n2. Check the update please." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T13:43:58.067", "Id": "11343", "ParentId": "11323", "Score": "2" } }, { "body": "<p>In the end there was no need to retry manually httpclient has a retry handler.</p>\n\n<pre><code> HttpRequestRetryHandler retryhandler = new DefaultHttpRequestRetryHandler(6, true);\n\n httpClient.setHttpRequestRetryHandler(retryhandler);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-15T09:35:52.927", "Id": "12612", "ParentId": "11323", "Score": "3" } } ]
{ "AcceptedAnswerId": "11343", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T08:30:05.883", "Id": "11323", "Score": "3", "Tags": [ "java", "android", "recursion", "exception-handling", "error-handling" ], "Title": "HttpClient error handling" }
11323
<p>Is there a way to reduce the number of lines by setting the output variable inside LINQ select statement? How would you do it?</p> <pre><code>public void GetSomeValue(int bonusID, out decimal? maxGiving, out int? isActive) { maxGiving = 0; isActive = 0; try { var con = new BonusModelDataContext(); var a = con.Bonus .Where(c =&gt; c.ID == bonusID) .Select(c =&gt; new { maxGiving = c.maxGiving, isActive = c.isActive }) .SingleOrDefault(); maxGiving = a.maxGiving; isActive = a.isActive; // return iovation; } catch(Exception ex) { //return -1; } } </code></pre>
[]
[ { "body": "<p>No, you can't do that, you can't use <code>out</code> parameters in a lambda.</p>\n\n<p>But even if you could, I don't think it would be a good idea to do so, because it would make the code less readable.</p>\n\n<p>There are also some suspicious practices in your code:</p>\n\n<ol>\n<li>You're using <code>SingleOrDefault()</code>, but you don't check the result for <code>null</code>. If you don't want to check for <code>null</code>, use <code>Single()</code> which will throw an exception if the query returns an empty collection.</li>\n<li>You're catching all exceptions. You should catch only the exceptions you know about. And you certainly shouldn't use something like <code>return -1</code>, it's much better to just let the exception bubble up and catch it somewhere up the call stack. Another option might be catching the exception, wrapping it in some more specific exception and throwing that.</li>\n<li>Why are you setting the output parameters to <code>0</code> by default? They are nullable, so setting them to <code>null</code> makes more sense to me.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T11:33:43.693", "Id": "11330", "ParentId": "11328", "Score": "11" } }, { "body": "<p>svick's observations are spot on, however I suggest you go a bit further in your refactoring.</p>\n<h1>Suggested Refactorings</h1>\n<h2>Naming</h2>\n<ul>\n<li><code>GetSomeValue</code> is not expressive. I changed it to <code>GetBonusDetails</code>, which makes more sense to me, but then again I don't know the rest of your code base - just choose a name that clearly says what the method does.</li>\n<li><code>con</code> is borderline acceptable... for clarity I renamed it to <code>dataContext</code>.</li>\n<li>the name <code>a</code> doesn't tell us anything about what this variable contains. I renamed it to <code>bonus</code>.</li>\n<li>the name <code>isActive</code> is a lie. This <code>int</code> is pretending to be a <code>bool</code>, probably because it <strong>should indeed be boolean</strong>. I don't know for sure, since the range of possible values is not apparent in your code.\n<ul>\n<li>If it only gets assigned the values <code>0</code> and <code>1</code>, change the data type to <code>bool</code>.</li>\n<li>If it can have other values, rename it to <code>activityStatus</code> or something similar.</li>\n</ul>\n</li>\n</ul>\n<p><em>(from now on I will use the corrected names in my explanations and code.)</em></p>\n<h2>Exception Handling</h2>\n<ul>\n<li>I changed <code>SingleOrDefault()</code> to <code>Single()</code> to avoid a possible <code>NullReferenceException</code>.</li>\n<li>I removed your <code>try-catch-statement</code>: swallowing an error can turn into a debugging headache in the future. I believe that in this case you should probably create a custom <code>BonusNotFoundException</code>. You would then catch this exception at a higher level and notify the user.</li>\n</ul>\n<h2>Output Parameters</h2>\n<p>I agree that it would make more sense to initialize the output parameters with <code>null</code> since you made the effort of making them <code>Nullable</code>. But if you take a step back, you realize how ugly the use of <code>out</code> parameters is in this situation. <strong>So I deleted them</strong> and made <code>GetBonusDetails</code> return an instance of a new class designed to hold two pieces of information: <code>maxGiving</code> and <code>isActive</code>. I called it <code>BonusDetails</code>, but I'm sure you can find a much better name for it.</p>\n<h2>LINQ Query</h2>\n<p>I rewrote your query as a <code>query statement</code> because I find the syntax less convoluted. However, using a method chain is also all right if it is more readable for you.</p>\n<h1>End Result</h1>\n<h2><code>GetBonusDetails</code> method</h2>\n<pre><code>public BonusDetails GetBonusDetails(int bonusID)\n{\n var dataContext = new BonusModelDataContext();\n var bonus = from b in dataContext.Bonus\n where b.ID == bonusID\n select new BonusDetails(b.maxGiving, b.isActive);\n return bonus.Single();\n}\n</code></pre>\n<h2><code>BonusDetails</code> class</h2>\n<pre><code>public class BonusDetails\n{\n public int MaxGiving { get; private set; }\n public bool IsActive { get; private set; }\n\n public BonusDetails(int maxGiving, bool isActive)\n {\n MaxGiving = maxGiving;\n IsActive = isActive;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T08:25:49.500", "Id": "18271", "Score": "2", "body": "Very good advices here (but for LINQ I prefer the method chain way:P), but I recommend you to use `using` statement for _dataContext_ object in `var dataContext = new BonusModelDataContext();` (+1)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T19:57:06.340", "Id": "11355", "ParentId": "11328", "Score": "11" } }, { "body": "<p>Working on codesparkle's answer, I think this might be better still:</p>\n\n<pre><code>public BonusDetails GetBonusDetails(int bonusID)\n{\n var dataContext = new BonusModelDataContext();\n var bonus = dataContext.Bonus.First(b =&gt;b.ID == bonusID);\n return new BonusDetails(bonus.maxGiving, bonus.isActive);\n}\n</code></pre>\n\n<p>Assuming <code>.ID</code> is unique (if not then <code>.Single(Func&lt;T,bool&gt;)</code> so you get the exception for more than one element). In both cases you should probably catch the internal exceptions and throw your own in its place to hide the implementation details (or specify in the method documentation that it will throw these internal exceptions, but I would think of that as bad practice).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T08:53:24.563", "Id": "18273", "Score": "0", "body": "nice one, you have my +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T17:56:53.623", "Id": "76082", "Score": "0", "body": "I would use `Single` even if `ID` was unique, because it makes the intent clearer. And it's also safer (what if `ID` stops being unique?)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T19:28:23.440", "Id": "11372", "ParentId": "11328", "Score": "2" } } ]
{ "AcceptedAnswerId": "11330", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T11:07:40.777", "Id": "11328", "Score": "4", "Tags": [ "c#", "linq" ], "Title": "Setting output parameter inside LINQ select" }
11328
<p>I have been working on a Backbone.js application, and I am starting to think I am making a huge mistake.</p> <p>I never fully understand garbage collecting, and how exactly some closures prevent it. I just try to keep as organized as possible.</p> <p>I just read an article that states that JavaScript variables that are not declared using the <code>var</code> keyword will not be removed from memory.</p> <p>Now in my application I create everything inside an object called <code>once</code>. I clean this object every time I move to another page. I clean out the whole object, and remove all the elements and events associated to it.</p> <p>Note: I am talking here about a single page backbone.js application. With changing pages I mean changing from one route to another using <code>Backbone.History.navigate</code>.</p> <p>Am I making good use of the <code>once</code> Object inside the <code>App</code> object? Will all be gone when I change routes?</p> <pre><code>//////////////////////////////////// // // Main Object for my application // - once : One time models/views/etc // - move : Called before I move to a // new route // - clean: Called after I moved to // the new route // - close: Used internal by `clean` // ///////////////////////////////////// App = { once: {}, move: function(){ this.olds = this.once; this.once = {}; }, clean: function(){ for(var Obj in this.olds){ if(this.olds[Obj].models){ this.olds[Obj].forEach(function(model){ this.close(model); }, this); } this.close(this.olds[Obj]); } delete this.olds; }, close: function(Obj){ if(typeof(Obj.onClose) !== 'undefined'){ Obj.onClose(); } if(typeof(Obj.off) !== 'undefined'){ Obj.off(); } if(typeof(Obj.remove) !== 'undefined'){ Obj.remove(); } } } /////////////////////////////////////////////// // // My model, collection, and 2 views // // Note that I left out some basic steps // ////////////////////////////////////////////// window.User = Backbone.Model.extend({}); window.Users = Backbone.Collection.extend({ model: User }); window.UserView = Backbone.View.extend({ // Init, events, etc ... render: function(){ this.collection.forEach(function(user){ App.once.userSubView = new UserSubView({ model: user }); this.$el.append(App.once.userSubView.el); }) } }); window.UserSubView = Backbone.View.extend({}); /////////////////////////////////////////////// // // One of the routes of my router. // // All my routs begin with move() and end // with clean(). // ////////////////////////////////////////////// App.move(); App.once.users = new Users(); // Create the views App.once.users.fetch({ success: function(){ App.once.userView = new UserView({ collection: App.once.users }) $('body').append(App.once.userView.el); } }) App.clean(); </code></pre>
[]
[ { "body": "<p>This code looks mostly fine to me, when the <code>.move</code> method gets called, <code>.once</code> gets moved to <code>.old</code> and then when <code>.clean</code> happens, <code>.old</code> gets deleted (and eventually garbage collected unless a reference to it continues to exist somewhere else).</p>\n\n<p>However I think you could do better by encapsulating each route in a function that takes care of <code>.move</code> and <code>.clean</code> for you.</p>\n\n<p>Something like:</p>\n\n<pre><code>route(function () {\n App.once.users = new Users();\n\n App.once.users.fetch({\n success: function () {\n App.once.userView = new UserView({\n collection: App.once.users\n });\n $('body').append(App.once.userView.el);\n }\n });\n});\n</code></pre>\n\n<p>where route is:</p>\n\n<pre><code>function route(fn) {\n App.move();\n fn();\n App.clean();\n}\n</code></pre>\n\n<p>(but you probably already have a method like this in your code where these things would belong)</p>\n\n<p>A better question: Why do you need this <code>.once</code> property anyway? It looks like it is just holding private data for the route. Why not make it private to the route then?</p>\n\n<pre><code>route(function () {\n var users = new Users();\n\n users.fetch({\n success: function () {\n $('body').append(new UserView({ collection: users }).el);\n }\n });\n});\n</code></pre>\n\n<h2>Garbage collection in JavaScript</h2>\n\n<p>(very simplified basic design ignoring tricks/special cases)</p>\n\n<p>Every variable in javascript can be thought of as a reference to an underlying system object.</p>\n\n<p>That is, in JS you have:</p>\n\n<pre><code>var a, b;\n</code></pre>\n\n<p>to the system there is:</p>\n\n<pre><code>var all = [ {data: a, declaredScope: function()}, {data: b, declaredScope: function()}];\nvar scope = function();\n</code></pre>\n\n<p>When the garbage collector runs, it does something like this:</p>\n\n<pre><code>function markDescend(variable) {\n for (var child in variable) { //the system has the child as seen in the \"all\" array\n if (child !== undefined &amp;&amp; child !== null &amp;&amp; !child.marked) {\n child.marked = true;\n markDescend(child);\n }\n }\n}\nvar tempscope = scope;\nvar tempall = all;\ndo {\n for (var variable in tempall) {\n if(tempscope === variable.declaredScope) {\n variable.marked = true;\n markDescend(variable);\n }\n }\n tempscope = tempscope.outer;\n} while (tempscope);\n\nall = [];\nfor (var variable in tempall) {\n if(variable.marked) {\n variable.marked = false;\n all.push(variable);\n } else {\n __free(variable);\n }\n}\n</code></pre>\n\n<p>That is to say, when the garbage collector runs, all variables reachable from the current scope (and closure scopes) are marked; then a second loop runs and all variables not marked are freed from memory.</p>\n\n<p>Thus, if there is no way for the system to reach an object via scope then it is going to be collected. From a user perspective, there are a few ways to create objects that the user can not reach, but are still in scope. Some examples:</p>\n\n<ul>\n<li><code>window.setTimeout(function () {}, x)</code> - this function is reachable from global scope until it finishes running; and it has access to any variables from any of its closure scopes (even though you may not be able to reach it)</li>\n<li><code>$.ajax('asdg', function () {})</code> - same as setTimeout</li>\n<li>Any attached DOM node is reachable from the global scope. You may attach events to these nodes and if you don't maintain the reference, you would lose access to it.</li>\n</ul>\n\n<p>In these cases, you would need to do more than what you are currently doing in your <code>.move</code> method to take care of unregistering these functions (<em>In IE7 and below</em>). My perspective would be just to let it leak (tell the users to get a better browser). IE6 would leak until the browser is closed, IE7 would leak until the page is out of the navigation cache. In every other browser, once the DOM is detached (or the timeout occurs, or the ajax post happens, etc.) these functions are not reachable from the global scope anymore (and so they are removed in the next garbage collection cycle). </p>\n\n<h2>Cleanup in IE</h2>\n\n<p>Essentially what you are doing in <code>.move</code> is move the stuff you want to delete in the previous route to <code>.old</code> and then in <code>.clean</code> you take care of deleting the old references.</p>\n\n<p>Really the only things you should care about are those properties that you cannot actually get at via variable properties once set. Whenever you do a <code>window.setTimeout()</code> (or similar) you would want to do something like this:</p>\n\n<pre><code>function setTimeout(fn, msec, App) {\n var id = window.setTimeout(function () {\n fn();\n destructor.removeReference = null;\n }, msec),\n destructor = {\n removeReference: function () { window.clearTimeout(id); }\n };\n App.once.push(destructor);\n}\n\nfunction setInterval(fn, msec, App) {\n var id = window.setInterval(fn, msec);\n App.once.push({\n removeReference: function () { window.clearInterval(id); }\n });\n}\n</code></pre>\n\n<p>and so on for attaching events, setting DOM properties, making ajax requests, etc. Then in <code>.clean</code> you would check if the object in <code>.old</code> has a removeReference function; if so run it then delete it and the object.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T17:18:42.683", "Id": "18204", "Score": "0", "body": "Thanks for commenting, good suggestions. I have added a response to your answer in the OP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T21:34:23.447", "Id": "18228", "Score": "0", "body": "Take note, I am trying to explain this so that anyone who can read JS can understand how this collection process works (there are many technicalities that I am glossing over). Another edit is coming with changes necessary to get around the DOM circular reference issue in IE." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T15:01:33.487", "Id": "11346", "ParentId": "11333", "Score": "4" } } ]
{ "AcceptedAnswerId": "11346", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T11:49:48.660", "Id": "11333", "Score": "1", "Tags": [ "javascript", "memory-management", "backbone.js", "garbage-collection" ], "Title": "Will this code get cleaned up by the garbage collector?" }
11333
<p>I have an HTML table representing a database table and a sidebar which holds different anchors ready to perform CRUD operations on click.</p> <p>Because the <code>href</code>s in the anchors aren't general valid for all columns I have written a script which automatically inserts the id of a selected column into the <code>href</code>s:</p> <pre><code>/localhost/image/var/edit =&gt; /localhost/image/4/edit </code></pre> <p>The code I have written works but it isn't very clean and smart. Could somebody take a look and say where I have space of improvement?</p> <pre><code>&lt;script type="text/javascript" src="{{ asset('bundles/acme/js/jquery.js'&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $('table tr').click(function(){ $('.selected').removeClass('selected'); $(this).addClass('selected'); var name = $(this).find('td:nth-child(2)').html(); $('.image_bar ul li a').each(function(){ var oldUrl = $(this).attr('href'); var newUrl = oldUrl.replace('var', name); $(this).attr('href', newUrl); }); }); &lt;/script&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T13:53:21.153", "Id": "18183", "Score": "0", "body": "fiddle please.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T14:27:37.257", "Id": "18184", "Score": "1", "body": "Your code is fine, only thing i would change is giving the table an ID, so it dosent bind all tables, and it find the element faster. And combine oldUrl and newUrl into one line, no reason to make the oldurl since you don't use it as an var." } ]
[ { "body": "<p>I do not like too much this:</p>\n\n<pre><code>var name = $(this).find('td:nth-child(2)').html(); \n</code></pre>\n\n<p>I would generally use html5 data attribute on the tr row to pass the id.</p>\n\n<p>example:</p>\n\n<pre><code>&lt;table&gt;\n &lt;tr data-id=\"1\"&gt;&lt;td&gt;bla&lt;/td&gt;&lt;td&gt;bla&lt;/td&gt;&lt;td&gt;bla&lt;/td&gt;&lt;/tr&gt;\n &lt;tr data-id=\"2\"&gt;&lt;td&gt;bla&lt;/td&gt;&lt;td&gt;bla&lt;/td&gt;&lt;td&gt;bla&lt;/td&gt;&lt;/tr&gt;\n&lt;/table&gt;\n\nvar selectedId = $(this).data(\"id\"); \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T16:38:15.973", "Id": "18185", "Score": "0", "body": "Hi, the problem is that I don't directly use the id as identificator. I mostly use a slug which is in some <td>-block. But good idea for normal identification!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T15:35:31.703", "Id": "11336", "ParentId": "11335", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T13:49:55.257", "Id": "11335", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "HTML table representing a database table and a sidebar" }
11335
<p>This allows users to upload an file from the browser into my Rails app using the paperclip gem. Once the file is uploaded it gets saved into the filesystem. When the user then goes in and the "show" method or the "edit" method is evoked the image is shown to the user. This is fine for image files but for .csv and .txt files I don't want to show the preview in the browser. This code is clunky and I know there is a better way to do this.</p> <pre><code>&lt;% if @user.image? %&gt; &lt;%=filetype = @user.image.url %&gt;&lt;br/&gt; &lt;%if filetype.include? ".jpeg" %&gt; &lt;b&gt;isJpeg&lt;/b&gt; &lt;%= image_tag @user.image.url %&gt; &lt;br /&gt; &lt;%= link_to @user.image.url, @user.image.url %&gt; &lt;% end %&gt; &lt;%if filetype.include? ".gif" %&gt; &lt;b&gt;isGif&lt;/b&gt; &lt;%= image_tag @user.image.url %&gt; &lt;br /&gt; &lt;%= link_to @user.image.url, @user.image.url %&gt; &lt;% end %&gt; &lt;%if filetype.include? ".png" %&gt; &lt;b&gt;isPNG&lt;/b&gt; &lt;%= image_tag @user.image.url %&gt; &lt;br /&gt; &lt;%= link_to @user.image.url, @user.image.url %&gt; &lt;% end %&gt; &lt;%if filetype.include? ".jpg" %&gt; &lt;b&gt;isJPG&lt;/b&gt; &lt;%= image_tag @user.image.url %&gt; &lt;br /&gt; &lt;%= link_to @user.image.url, @user.image.url %&gt; &lt;% end %&gt; &lt;%if filetype.include? ".csv" %&gt; &lt;b&gt;isCSV&lt;/b&gt; &lt;p&gt;Your file was a csv file and has no preview&lt;/p&gt; &lt;%= link_to @user.image.url, @user.image.url %&gt; &lt;% end %&gt; &lt;%= image_tag @user.image.url %&gt; &lt;br /&gt; &lt;%= link_to @user.image.url, @user.image.url %&gt; &lt;% end %&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T18:26:19.930", "Id": "18191", "Score": "1", "body": "write a helper that returns a string given a filetype (isJPG, isPNG, ...)." } ]
[ { "body": "<p><a href=\"https://stackoverflow.com/users/188031/tokland\">tokland</a> is right (on both counts), you should push all that logic into a helper. You can also add a bit of <a href=\"http://ruby-doc.org/stdlib-1.9.3/libdoc/ostruct/rdoc/OpenStruct.html\" rel=\"nofollow noreferrer\">OpenStruct</a> into the mix to make the helper nicer:</p>\n\n<pre><code># in app/helpers/application_helper.rb or another helper\ndef user_image_info(user)\n info = OpenStruct.new(:has_image? =&gt; false)\n return info if(!user.image?)\n\n # There might be better ways to do this but I don't know paperclip.\n u = user.image.url\n %w[jpeg gif png jpg csv].find do |ext|\n # A small abuse of `find` but reasonable in this case.\n info.is = \"is#{ext.upcase}\" if(u.include?(\".#{ext}\"))\n end\n if(info.is == 'isCSV')\n info.preview_link = '&lt;p&gt;Your file was a csv file and has no preview&lt;/p&gt;'.html_safe\n else\n info.preview_link = (image_tag(user.image.url) + '&lt;br&gt;').html_safe\n end\n info\nend\n</code></pre>\n\n<p>Then in your ERB, you could do something like this:</p>\n\n<pre><code>&lt;% info = user_image_info(@user) %&gt;\n&lt;% if info.has_image? %&gt;\n &lt;b&gt;&lt;%= info.is %&gt;&lt;/b&gt;\n &lt;%= info.preview_link %&gt;\n &lt;%= link_to @user.image.url, @user.image.url %&gt;\n&lt;% end %&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T18:58:24.893", "Id": "11340", "ParentId": "11339", "Score": "2" } }, { "body": "<p>I'd use some kind of presenter here. Or exhibit (see <a href=\"http://objectsonrails.com/#ID-2656c30c-080a-4a4e-a53e-4fbaad39c262\" rel=\"nofollow\">Objects on Rails</a>). So some object where you can extract your view logic.</p>\n\n<pre><code># replace you view with these 2 lines of code\n&lt;% @user = UserExhibit.new(user, view) %&gt;\n&lt;%= @user.render %&gt;\n\n\n\nclass UserExhibit &lt; SimpleDelegator\n def initialize(user, context)\n @context = context\n super(user)\n end\n\n def render\n return '' unless @user.image?\n @context.render partial: \"user_image\", locals: { user: self }\n end\n\n def filetype\n image.url\n end\n\n def image_is_picture?\n filetype =~ /\\.(jpeg|gif|png|jpg)$/\n end\n\n def image_type\n filetype[/\\.(\\w+)$/, 1]\n end\nend\n\n\n# _user_image.html.erb partial\n&lt;b&gt;is&lt;%= @user.image_type.upcase %&gt;&lt;/b&gt;\n\n&lt;%if @user.image_is_picture? %&gt;\n &lt;%= image_tag @user.image.url %&gt; &lt;br/&gt;\n &lt;%= link_to @user.image.url, @user.image.url %&gt;\n&lt;% else %&gt;\n &lt;p&gt;Your file was a &lt;%= @user.image_type %&gt; file and has no preview&lt;/p&gt;\n &lt;%= link_to @user.image.url, @user.image.url %&gt;\n&lt;% end %&gt; \n\n&lt;%= image_tag @user.image.url %&gt; &lt;br/&gt;\n&lt;%= link_to @user.image.url, @user.image.url %&gt;\n</code></pre>\n\n<p>Also, you may find useful these links:</p>\n\n<ul>\n<li><a href=\"http://railscasts.com/episodes/287-presenters-from-scratch\" rel=\"nofollow\">http://railscasts.com/episodes/287-presenters-from-scratch</a> </li>\n<li><a href=\"http://railscasts.com/episodes/286-draper\" rel=\"nofollow\">http://railscasts.com/episodes/286-draper</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T17:01:28.220", "Id": "11410", "ParentId": "11339", "Score": "1" } } ]
{ "AcceptedAnswerId": "11340", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T18:24:32.020", "Id": "11339", "Score": "2", "Tags": [ "beginner", "ruby", "ruby-on-rails", "image", "file-system" ], "Title": "Uploading a file from the browser" }
11339
<p>I've written a script that deletes a member of a hash if an array within the has contains all the other elements of another array within the same hash.</p> <p>It works but it looks a little messy. Is there a better way to do this?</p> <pre><code>def title_contains_blocks(candidate, titles, index) test_group = titles.dup test_group.delete_at(index) test_group.each do |title| return true if true === title[:blocks].all?{|block| candidate[:blocks].include?(block)} end return false end titles = [ {:blocks =&gt; [1,2,3,4,5,6]}, {:blocks =&gt; [1,2,3]}, {:blocks =&gt; [4,5,6]} ] titles = titles.delete_if.each_with_index {|candidate, index| title_contains_blocks(candidate, titles, index) } puts titles.inspect #=&gt; [{:blocks=&gt;[1, 2, 3]}, {:blocks=&gt;[4, 5, 6]}] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T12:36:48.943", "Id": "18192", "Score": "0", "body": "Would it have been equivalent if you removed the [1,2,3] and [4,5,6]? That is, do you simply need to cover all digits and remove redundant entries?" } ]
[ { "body": "<p>Convert the Hashes to Arrays, then use the difference operations on them.</p>\n\n<pre><code>a = { :a =&gt; 1, :b =&gt; 2, :c =&gt; 2 }\nb = { :a =&gt; 1 }\n\np (b.to_a - a.to_a).empty?\n</code></pre>\n\n<p>You can do other things, like identify if two Hashes overlap in any places, by use the intersection too:</p>\n\n<pre><code>p (a.to_a &amp; b.to_a).any?\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-16T07:11:58.070", "Id": "140719", "Score": "0", "body": "in the the first example, if `b` is a superset of `a` then it would also result in `empty? == true`... FYI for everybody trying to compare with this method" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T08:54:40.057", "Id": "11342", "ParentId": "11341", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T07:52:52.293", "Id": "11341", "Score": "4", "Tags": [ "ruby" ], "Title": "Comparing hash members to other hash members" }
11341
<p>This hides <code>div.extended</code> then creates a button that toggles its text and <code>div.extended</code>'s visibility.</p> <p>While the below works, I was wondering if there was a more concise way of writing this code.</p> <pre><code>(function() { var extended = $('.extended').hide(); $('&lt;button&gt;&lt;/button&gt;', { text: 'Read more' }).appendTo('.intro') .on('click', function(){ extended.slideToggle(); }).toggle( function(){ $(this).text('Read Less') }, function(){ $(this).text('Read More') }); })() </code></pre>
[]
[ { "body": "<pre><code>$(function () {\n var extended = $('.extended').hide(),\n hidden = true;\n $('&lt;button&gt;&lt;/button&gt;', {\n text: 'Read more'\n }).appendTo('.intro').on('click', function () {\n extended.slideToggle();\n hidden = !hidden;\n $(this).text(hidden ? 'Read More' : 'Read Less');\n });\n});\n</code></pre>\n\n<p>You only need to bind the click event once (toggle is a shortcut for binding to click and attaching two alternating event handlers).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T14:50:17.440", "Id": "18195", "Score": "0", "body": "Many thanks Mr Barry. I've learnt something today." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T14:27:20.467", "Id": "11345", "ParentId": "11344", "Score": "4" } } ]
{ "AcceptedAnswerId": "11345", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T13:46:57.240", "Id": "11344", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Toggling button & content with jQuery" }
11344
<p>Though it works I wonder if there might be a better way to do this. I would like to reuse this loading and establishing of fields of another class(es) (the static TileMapper class mentioned at the end) in a C#/.net/XNA environment.</p> <p>I noticed that when moving through the OpenFileDialog to find files it felt sluggish. Is that because I had to set [STAThreadAttribute] just to get it to open?</p> <pre><code>private void loadMapToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); openFile.Title = "Select a File"; openFile.InitialDirectory = Application.StartupPath + @"\Content\Map\"; openFile.Filter = "MAP Files (.MAP)|*.MAP"; openFile.FilterIndex = 1; openFile.Multiselect = false; if (openFile.ShowDialog() != DialogResult.Cancel) { try { // Example file - _W25_H25_SET_GL_test.Map TileMapper.LoadMap(new FileStream(openFile.FileName, FileMode.Open)); // remove directory information string[] _mapname = openFile.FileName.Split('\\'); string tempmap = _mapname.Last(); // remove .map string[] removemap = tempmap.Split('.'); MapName = removemap.First(); //print file name txtMapName.Text = MapName; //get info stored in file name string[] nameParts = MapName.Split('_'); string[] widthPart = nameParts[1].Split('W'); string[] heightPart = nameParts[2].Split('H'); TileMapper.MapWidth = int.Parse(widthPart[1]); TileMapper.MapHeight = int.Parse(heightPart[1]); } catch { System.Diagnostics.Debug.Print("Unable to load map file"); } } else return; } </code></pre>
[]
[ { "body": "<blockquote>\n <p>I noticed that when moving through the OpenFileDialog to find files it\n felt sluggish. Is that because I had to set [STAThreadAttribute] just\n to get it to open?</p>\n</blockquote>\n\n<p>That is a StackOverflow or GameDev.StackExchange kind of question.</p>\n\n<p>Refactoring the code like this could be a start:</p>\n\n<pre><code>private void loadMapToolStripMenuItem_Click(object sender, EventArgs e)\n{\n var openFile = new OpenFileDialog\n {\n Title = \"Select a File\",\n InitialDirectory = Application.StartupPath + @\"\\Content\\Map\\\",\n Filter = \"MAP Files (.MAP)|*.MAP\",\n FilterIndex = 1,\n Multiselect = false\n };\n\n if (openFile.ShowDialog() != DialogResult.Cancel)\n {\n try\n {\n string otherMapName;\n\n LoadMap(TileMapper, openFile.FileName, out otherMapName);\n\n txtMapName.Text = otherMapName;\n }\n catch\n {\n //TODO: display an error message box?\n System.Diagnostics.Debug.Print(\"Unable to load map file\");\n }\n }\n}\n\n//TODO: why not move this method inside TileMapper?\nprivate void LoadMap(TileMapper tileMapper, string fileName, out string mapName)\n{\n mapName = null;\n\n // Example file - _W25_H25_SET_GL_test.Map\n tileMapper.LoadMap(new FileStream(fileName, FileMode.Open));\n\n mapName = Path.GetFileNameWithoutExtension(fileName);\n\n //get info stored in file name\n string[] nameParts = mapName.Split('_');\n string[] widthPart = nameParts[1].Split('W');\n string[] heightPart = nameParts[2].Split('H');\n\n tileMapper.MapWidth = int.Parse(widthPart[1]);\n tileMapper.MapHeight = int.Parse(heightPart[1]);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T18:29:24.833", "Id": "18210", "Score": "0", "body": "TileMapper is a static class which does contain the LoadMap method hence the call TileMapper.LoadMap which contains a deserializer etc. Or is that something I was doing wrong? I guess what I felt was the worst in the code was the use of 5 string arrays to extract specifics defined by the filename itself" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T20:45:26.593", "Id": "18225", "Score": "0", "body": "1. Your method of storing width and height in file name looks weird - why not serialize them into the file content?\n2. Try to avoid using static classes with state. You can create instances of common classes in Game class and pass them to all users. Read about SOLID principles." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T04:52:34.193", "Id": "18240", "Score": "0", "body": "1. True, the grand idea was that the filenames would be easier for me when connecting maps as the name contains its size as well as what tile set it was based on." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T16:50:20.537", "Id": "11351", "ParentId": "11348", "Score": "1" } } ]
{ "AcceptedAnswerId": "11351", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T15:53:19.347", "Id": "11348", "Score": "1", "Tags": [ "c#", ".net", "winforms" ], "Title": "What should I do to improve this snippet" }
11348
<p>I have a class <code>bar</code> that keeps track of <code>N</code> instances of class <code>foo</code> in a <code>std::map</code> (so <code>N</code> = <code>map.size()</code>). When I call <code>bar::func</code> I want to have <code>N</code> threads that call <code>foo::foo_func</code>.</p> <p><code>foo::foo_func</code> requires multiple arguments though, namely the instance of <code>bar</code> that it's related to.</p> <p>I was thinking of doing <em>something</em> like:</p> <pre><code>void * _threaded_foo_func(void *); struct box { bar * the_bar; foo * the_foo; }; class bar { class sub_bar { // stuff }; map&lt;foo*, sub_bar*&gt; foo_mappings; void func() { pthread_t threads[ foo_mappings.size() ]; map&lt;foo*, sub_bar*&gt;::iterator it = foo_mappings.begin(); int i=0; for(it; it != foo_mappings.end() &amp;&amp; i &lt; foo_mappings.size(); ++it, ++i) { box * args = new args(); args-&gt;the_bar = this; args-&gt;the_foo = it-&gt;first; pthread_create( &amp;threads[i], NULL, _threaded_foo_func, (void*) args); } for(int i=0; i&lt;bar_mappings.size(); ++i) { pthread_join(threads[i], NULL); } } }; void * _threaded_foo_func(void * args) { box * b = (box*) args; bar * the_bar = b-&gt;the_bar; foo * the_foo = b-&gt;the_foo; the_foo-&gt;foo_func(the_bar); return NULL; } </code></pre> <p>My questions are:</p> <ul> <li>Is there a better way to do this? Cleaner? Thoughts on using <code>fork()</code>? </li> <li>Does this look like a poor design of the relationship between foo &amp; bar?</li> </ul> <p><strong>To make this fun, you're only allowed to use pthread.h, no C++11 stuff :)</strong></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T16:55:48.723", "Id": "18215", "Score": "1", "body": "Can you use C++11's `std::thread`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T16:57:34.563", "Id": "18216", "Score": "1", "body": "If your threads are cpu bound, starting one for every element in the map will overload the CPU. A better technique is to create a pipe/mailbox with the number of worker threads for the number of cores on the machine and then feeding the arguments into the pipe. Each thread is a loop reading from the pipe and then exits when the pipe is empty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T16:57:39.383", "Id": "18217", "Score": "0", "body": "I'd like to, but let's say that we're a special kind of lazy and would just rather use pthread.h" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T17:02:04.220", "Id": "18218", "Score": "0", "body": "@K-RAN: Then look into (for one example) Anthony Williams's implementation of a [thread-safe queue using condition variables](http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T17:03:36.467", "Id": "18219", "Score": "0", "body": "@BurtonSamograd -- How do I ensure that the threads are not CPU bound, if possible? Also, say that I were to implement the pipe/mailbox schema with worker threads: is there a way to find out the number of cores that the native machine has? I'm kinda new to this particular side of C/C++ programming so any kind of reference would be greatly appreciated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T17:05:39.163", "Id": "18221", "Score": "0", "body": "If your threads are not doing IO then they are probably CPU bound. Finding the number of cores is not portable so it's difficult to say how you would do that unless we knew your operating system. One linux you can just grep /proc/cpuinfo, but on windows, I'm really not sure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T18:25:58.910", "Id": "18222", "Score": "0", "body": "Say that I fire off a set number of threads, say `M` of them, and as each one joins it is immediately assigned a new task; do this until we've processed all `N` `foo` objects. Assuming that the entire program cannot procede without all `N` `foo` objects processed, how is it different from utilizing a thread pool?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T18:26:15.353", "Id": "18223", "Score": "0", "body": "Also, no one has answered my second question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T21:56:53.340", "Id": "18229", "Score": "0", "body": "Firing off N processing threads vs. N tasks being serviced by M threads (where M is based on the number of available cores) will be less efficient because of extra task switching." } ]
[ { "body": "<p>You might want to take a look at C++'s new <a href=\"http://en.cppreference.com/w/cpp/thread/thread\" rel=\"nofollow\">std::thread</a> class, which is part of the C++11 standard library. Its constructor is scheduled to run the created thread immediately and takes a function object such as a function pointer or <a href=\"http://en.wikipedia.org/wiki/C%2B%2B11#Lambda_functions_and_expressions\" rel=\"nofollow\">lambda function</a> and function arguments. It has the same mechanisms and functionality as pthreads but is platform-independent and object-oriented, making your code cleaner and more consistent with C++ style.</p>\n\n<p>std::thread can be used in gcc by compiling with the <code>-std=c++0x</code> flag for gcc 4.6 and earlier (I believe back to 4.4) and with <code>std=c++11</code> on gcc 4.7. Visual Studio 2010 doesn't support it, and it can be used in Visual Studio 11 by default.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T17:05:29.883", "Id": "18224", "Score": "0", "body": "I didn't specify in the question that you're only allowed to use pthread.h, sorry about the confusion. I'll definitely take a look at C++11 though so thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T17:02:49.460", "Id": "11353", "ParentId": "11352", "Score": "1" } }, { "body": "<p>How many instances of <code>foo</code> are you going to have? Spawning a large number of threads or forking a large number of processes isn't going to scale well in terms of both CPU and memory resources.</p>\n\n<p>Another approach that generally has better scalability is a <a href=\"http://en.wikipedia.org/wiki/Thread_pool_pattern\" rel=\"nofollow\">thread pool</a>. The basic idea is that you have a fixed number of threads that pull and execute tasks from a queue, resulting in better resource utilization.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T17:06:31.803", "Id": "11354", "ParentId": "11352", "Score": "3" } } ]
{ "AcceptedAnswerId": "11354", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T16:49:17.133", "Id": "11352", "Score": "10", "Tags": [ "c++", "pthreads" ], "Title": "Is there a better way to thread this class function?" }
11352
<p>I am making an interpreter for a custom programming language (concatenative, soft-typed) and for that purpose I have a central datatype <code>Token</code>. A Token can be of one of the many different types, either of scalar ones or vector ones. To minimize the amount of memory, I used a <code>union</code> first but then I could only use plain-old data structures in the union, so I resorted to a <code>struct</code> with all the fields (<code>long asInteger;</code>, <code>boost::shared_ptr&lt;std::string&gt; asString</code>, ...). That was of course a bad idea from a memory consumption viewpoint but it got the job done.</p> <p>The project has grown quite a bit since the original formulation and is now nearing 5000 lines altogether (mainly consisting of various functions that are built in the interpreter). Since the <code>Token</code> datatype was almost 100 bytes long (making an array of 1,000,000 integers almost 100 megabytes for example), the original formulation showed massively inadequate. Today I revamped the implementation to dynamically allocate the memory needed for each element with copy semantics so that I got something similar to the <code>union</code> if I could use it with classes.</p> <p>This is the new class definition:</p> <pre><code>typedef struct _st_VariableData { char name[32]; Context *context; vector&lt;long&gt; index; } VariableData; typedef struct _st_FuncCallData { char asFunctionName[32]; } FuncCallData; // Opaque pointer type typedef struct _st_HandleData { void * ptr; long size; } HandleData; class Token { protected: TokenType tokenType_; template&lt;class T&gt; inline void copyToken(void * src, void * dst) { *static_cast&lt;T*&gt;(dst) = *static_cast&lt;T*&gt;(src); }; template&lt;class T&gt; inline void deleteValue() { delete static_cast&lt;T*&gt;(data); }; void deleteData() { switch (tokenType_) { case T_OPERATOR: deleteValue&lt;OperatorType&gt;(); break; case T_FUNCCALL: deleteValue&lt;FuncCallData&gt;(); break; case T_VARIABLE: deleteValue&lt;VariableData&gt;(); break; case T_INTEGER: deleteValue&lt;long&gt;(); break; case T_BOOL: deleteValue&lt;bool&gt;(); break; case T_FLOAT: deleteValue&lt;double&gt;(); break; case T_STRING: deleteValue&lt;boost::shared_ptr&lt;std::string&gt;&gt;(); break; case T_CODEBLOCK: case T_ARRAY: deleteValue&lt;boost::shared_ptr&lt;std::vector&lt;Token&gt;&gt;&gt;(); break; case T_HANDLE: deleteValue&lt;HandleData&gt;(); break; default: ; } } void allocate(const TokenType tokenType) { switch (tokenType) { case T_OPERATOR: data = new OperatorType; break; case T_FUNCCALL: data = new FuncCallData; break; case T_VARIABLE: data = new VariableData; break; case T_INTEGER: data = new long; break; case T_BOOL: data = new bool; break; case T_FLOAT: data = new double; break; case T_STRING: data = new boost::shared_ptr&lt;std::string&gt;; break; case T_CODEBLOCK: case T_ARRAY: data = new boost::shared_ptr&lt;std::vector&lt;Token&gt;&gt;; break; case T_HANDLE: data = new HandleData; break; default: data = NULL; } }; void * data; public: char * fileName; int lineNum; const TokenType type() { return tokenType_; }; const TokenType type() const { return tokenType_; }; void set_type(const TokenType tokenType) { deleteData(); tokenType_ = tokenType; allocate(tokenType); }; Token() : tokenType_ (T_EMPTY) { data = NULL; }; Token(const TokenType tokenType) : tokenType_ (tokenType) { allocate(tokenType); }; Token(const Token&amp; old_token) { fileName = old_token.fileName; lineNum = old_token.lineNum; tokenType_ = old_token.tokenType_; allocate(old_token.tokenType_); switch (old_token.tokenType_) { case T_OPERATOR: copyToken&lt;OperatorType&gt;(old_token.data, data); break; case T_FUNCCALL: copyToken&lt;FuncCallData&gt;(old_token.data, data); break; case T_VARIABLE: copyToken&lt;VariableData&gt;(old_token.data, data); break; case T_INTEGER: copyToken&lt;long&gt;(old_token.data, data); break; case T_BOOL: copyToken&lt;bool&gt;(old_token.data, data); break; case T_FLOAT: copyToken&lt;double&gt;(old_token.data, data); break; case T_STRING: copyToken&lt;boost::shared_ptr&lt;std::string&gt;&gt;(old_token.data, data); break; case T_CODEBLOCK: case T_ARRAY: copyToken&lt;boost::shared_ptr&lt;std::vector&lt;Token&gt;&gt;&gt;(old_token.data, data); break; case T_HANDLE: copyToken&lt;HandleData&gt;(old_token.data, data); break; default: ; } }; template&lt;class T&gt; T&amp; retreive() { return *static_cast&lt;T*&gt;(data); }; template&lt;class T&gt; const T&amp; retreive() const { return *static_cast&lt;T*&gt;(data); }; void operator=(const Token &amp;rhs) { fileName = rhs.fileName; lineNum = rhs.lineNum; set_type(rhs.tokenType_); switch (rhs.tokenType_) { case T_OPERATOR: copyToken&lt;OperatorType&gt;(rhs.data, data); break; case T_FUNCCALL: copyToken&lt;FuncCallData&gt;(rhs.data, data); break; case T_VARIABLE: copyToken&lt;VariableData&gt;(rhs.data, data); break; case T_INTEGER: copyToken&lt;long&gt;(rhs.data, data); break; case T_BOOL: copyToken&lt;bool&gt;(rhs.data, data); break; case T_FLOAT: copyToken&lt;double&gt;(rhs.data, data); break; case T_STRING: copyToken&lt;boost::shared_ptr&lt;std::string&gt;&gt;(rhs.data, data); break; case T_CODEBLOCK: case T_ARRAY: copyToken&lt;boost::shared_ptr&lt;std::vector&lt;Token&gt;&gt;&gt;(rhs.data, data); break; case T_HANDLE: copyToken&lt;HandleData&gt;(rhs.data, data); break; default: ; } }; ~Token() { deleteData(); }; }; </code></pre> <p>Now the above code <strong>works</strong>, but is terribly slow (200% slower than the previous implementation). A profiler shows that almost half of the execution time is spent on <code>new</code> and <code>free()</code>. I have tried using placement new syntax with a <code>char data[50]</code> and that speeds it up a lot but still not as fast as original (about 20% slower).</p> <p>I am quite new to C++ (this is my first large project) so please excuse me if I have made some blatant mistakes arising from misconceptions. Generally I would like to minimize the memory allocation cost while also minimizing the required memory.</p> <p>If this is usually done a whole different way, please advise me how to do it. The entire source code (bleeding-edge without build automation) is available <a href="http://www.ojdip.net/stutsk/stutsk-current/stutsk-current.tar.gz" rel="nofollow">here</a>.</p> <p>Thank you for help!</p>
[]
[ { "body": "<p>This problem is solved very elegantly by <a href=\"http://www.boost.org/doc/libs/1_49_0/doc/html/variant.html\" rel=\"nofollow\">Boost.Variant</a>.</p>\n\n<p>Not only is it easier and more efficient, it’s also completely type safe (meaning, you cannot accidentally retrieve a wrong type) when using the <code>boost::apply_visitor</code> template function to access data.</p>\n\n<p>Furthermore, I’d separate an object and its token representation. Objects can be the result of a computation (1 + 1, say) but this has no representation in the source file, right? This way, you can save storing he line number for tokens which aren’t in a file. I’d also refrain from storing the filename for each token – wouldn’t it be enough to store that once?</p>\n\n<p>With that in mind, a token can be represented by the following variant:</p>\n\n<pre><code>struct token_array;\n\ntypedef boost::variant&lt;\n OperatorType,\n FuncCallData,\n VariableData,\n long,\n …,\n boost::recursive_wrapper&lt;token_array&gt;\n&gt; token;\n\nstruct token_array {\n std::vector&lt;token&gt; tokens;\n};\n</code></pre>\n\n<p>Note that you no longer need to take care of (de)allocation and copying yourself.</p>\n\n<hr>\n\n<p>Apart from that, your code features a few peculiarities from C:</p>\n\n<pre><code>typedef struct _st_FuncCallData {\n char asFunctionName[32];\n} FuncCallData;\n</code></pre>\n\n<p>First of all, there is no need to do <code>typedef struct … { } …;</code> in C++. Second of all, the struct name is invalid: in the global namespace, names starting with an underscore are reserved to the implementation in C++.</p>\n\n<p>The following is completely equivalent:</p>\n\n<pre><code>struct FuncCallData {\n char asFunctionName[32];\n};\n</code></pre>\n\n<p>I’d also question the usefulness of using a fixed-size char array here instead of just a <code>std::string</code> but oh well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T16:30:16.993", "Id": "18539", "Score": "0", "body": "Thank you! I've since tried with Boost Variant, but the code ended up being slower than before, the profiler showed that a very large amount of time was spent in some `boost::variant` function. I did not use `boost::recursive_wrapper`, so maybe this has something to do with it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T16:35:44.707", "Id": "18541", "Score": "0", "body": "@Tibor Which function was the time spent in? Anyway, if Boost.Variant turns out to be too slow I would nonetheless look at its implementation for inspiration. Having the multiple `switch`es that you have is a definite no-go." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T16:44:16.477", "Id": "18542", "Score": "1", "body": "That would be the um... boost::detail::variant::visitation_impl<boost::mpl::int_<0>,boost::detail::variant::visitation_impl_step<boost::mpl::l_iter<boost::mpl::l_item<boost::mpl::long_<9>,enum _en_OperatorType,boost::mpl::l_item<boost::mpl::long_<8>,_st_FuncCallData,boost::mpl::l_item<boost::mpl::long_<7>,_st_VariableData,boost::mpl::l_item<boost::mpl::long_<6>,boost::shared_ptr<std::basic_string<char,std::char_traits<char>,std::allocator<char> >" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T16:25:10.273", "Id": "11566", "ParentId": "11358", "Score": "1" } } ]
{ "AcceptedAnswerId": "11566", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T21:46:09.907", "Id": "11358", "Score": "2", "Tags": [ "c++", "performance" ], "Title": "Memory allocation for a variant-typed token" }
11358
<p>I just recently learned how to use Bit Field Structures in C++, and I was thinking of applying it to a project. It would certainly make the project code much easier to work with. So, I typed up a quick test program to see if it would work as I expected, and it does. But, I'm not 100% convinced that it is safe. </p> <p>I am fairly confident my <code>CRC16</code> <code>union</code> is Endianess specific, but I'm not sure about the Bit Field <code>struct</code>, I suspect it is... Can anyone confirm this?</p> <ol> <li>Is this usage of a bit field struct safe?</li> <li>Can it be made safer?</li> <li>Is it Endianess specific?</li> </ol> <p><strong>Note:</strong> So far, I have only tested this on 64 bit Linux.</p> <hr> <pre><code>#include &lt;stdint.h&gt; #include &lt;cstring&gt; #include &lt;iostream&gt; #include &lt;iomanip&gt; typedef union { int16_t Value; struct { int8_t Lo; int8_t Hi; } Bytes; //This is all I could think of to call this. If you can think of something better, let me know. } CRC16; #ifdef _MSC_VER #pragma pack(push, 1) #endif typedef struct { uint8_t SOH; uint16_t Count : 14; uint16_t Select : 1; uint16_t Qsync : 1; uint8_t Resp; uint8_t Num; uint8_t Addr; CRC16 Blck; #ifdef _MSV_VER } DataHeader; #pragma pack(pop) #else } __attribute__((packed)) DataHeader; #endif template&lt;typename T&gt; void PrintHex(std::string Description, T Value, long Mask = -1) { using namespace std; cout &lt;&lt; hex &lt;&lt; setiosflags(ios_base::showbase) &lt;&lt; Description &lt;&lt; " = " &lt;&lt; (static_cast&lt;unsigned short&gt;(Value) &amp; Mask) &lt;&lt; resetiosflags(ios_base::showbase) &lt;&lt; endl; } int main() { DataHeader test; int8_t packet[8] = {0x64,0x42,0x81,0x42,0x43,0x01,0x32,0x97}; //this is the most important part, as this structure would be //passed to Windows API calls, potentially file and socket I/O //functions, etc. memcpy(&amp;test, packet, sizeof(packet)); std::cout &lt;&lt; "sizeof(DataHeader) = " &lt;&lt; sizeof(DataHeader) &lt;&lt; std::endl; PrintHex("SOH", test.SOH); PrintHex("Count", test.Count); PrintHex("Select", test.Select); PrintHex("Qsync", test.Qsync); PrintHex("Resp", test.Resp); PrintHex("Num", test.Num); PrintHex("Addr", test.Addr); PrintHex("Blck.Value", test.Blck.Value); PrintHex("Blck.Bytes.Lo", test.Blck.Bytes.Lo, 0xFF); PrintHex("Blck.Bytes.Hi", test.Blck.Bytes.Hi, 0xFF); return 0; } </code></pre> <hr/> <p><strong>Output</strong></p> <blockquote> <p>sizeof(DataHeader) = 8<br/> SOH = 0x64<br/> Count = 0x142<br/> Select = 0<br/> Qsync = 0x1<br/> Resp = 0x42<br/> Num = 0x43<br/> Addr = 0x1<br/> Blck.Value = 0x9732<br/> Blck.Bytes.Lo = 0x32<br/> Blck.Bytes.Hi = 0x97<br/></p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T06:55:47.710", "Id": "18242", "Score": "0", "body": "Does DataHeader represent a (partial) DDCMP data message?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T21:54:22.363", "Id": "18250", "Score": "0", "body": "@DrTwox, why yes it is. But be honest, did you search Google, or are you familiar with DDCMP?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T22:27:31.117", "Id": "18251", "Score": "0", "body": "@DrTwox, you may notice an increase in your Stack Overflow reputation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T00:07:22.453", "Id": "18255", "Score": "1", "body": "I used Google, but looking at the variable names and packing it was sure to be some archaic network protocol :) Thanks for the rep!" } ]
[ { "body": "<pre><code>#include &lt;stdint.h&gt;\n</code></pre>\n\n<p>At least officially, you're supposed to prefer to use <code>&lt;cstdint&gt;</code> instead. I have a hard time getting very excited about it though.</p>\n\n<pre><code>#include &lt;cstring&gt;\n</code></pre>\n\n<p>From the looks of the code, you really wanted to include <code>&lt;string&gt;</code> here instead. You use an <code>std::string</code> in one place anyway (and I don't any use of anything from <code>&lt;cstring&gt;</code>).</p>\n\n<pre><code>typedef union \n{\n int16_t Value;\n struct\n {\n int8_t Lo;\n int8_t Hi;\n } Bytes; //This is all I could think of to call this. If you can think of something better, let me know.\n} CRC16;\n</code></pre>\n\n<p>This usage is fairly typical in C, but in C++, I'd just use:</p>\n\n<pre><code>union CRC16 { \n // ...\n};\n</code></pre>\n\n<p>Just like with <code>class</code>/<code>struct</code>, there's no need for a <code>typedef</code> in C++.</p>\n\n<p>As you guessed, this is endian-specific. Given that this is apparently an old DEC protocol, chances are that it's also little-endian. That's good to the degree that it works fine with Intel processors, but bad to the degree that the normal <code>ntohl</code>, <code>ntohs</code> (etc.) are all defined in terms of big-endian network format, so you can't use them to easily write portable code that converts endianness when needed.</p>\n\n<pre><code>#ifdef _MSC_VER\n#pragma pack(push, 1)\n#endif\ntypedef struct\n</code></pre>\n\n<p>Same comment as above--no real need for a <code>typedef</code> in C++.</p>\n\n<pre><code>uint16_t Count : 14;\nuint16_t Select : 1;\nuint16_t Qsync : 1;\n</code></pre>\n\n<p>You probably want to be aware that the mapping from bitfields to bits can vary (even independent of endianness). Not necessarily something you want to change or can fix, but with a different compiler (even with the same CPU) this could rather suddenly break.</p>\n\n<pre><code>#ifdef _MSV_VER\n</code></pre>\n\n<p>Minor typo--this should almost certainly be <code>_MSC_VER</code>.</p>\n\n<pre><code>template&lt;typename T&gt; \nvoid PrintHex(std::string Description, T Value, long Mask = -1)\n{\n using namespace std;\n cout &lt;&lt; hex\n &lt;&lt; setiosflags(ios_base::showbase)\n &lt;&lt; Description \n &lt;&lt; \" = \"\n &lt;&lt; (static_cast&lt;unsigned short&gt;(Value) &amp; Mask)\n &lt;&lt; resetiosflags(ios_base::showbase)\n &lt;&lt; endl;\n}\n</code></pre>\n\n<p>This has (IMO) a problem: after it's done, the hex flag is reset, even if it may have been set before the function was called. I'd rather use <code>ios_base::flags()</code> to retrieve the current flags, when again to restore then when finished. As (nearly) always when taking some action like that which you want to do, then un-do later, I'd prefer to put it into a small class that uses RAII to automate the restoring:</p>\n\n<pre><code>class flag_rest {\n std::ios_base::fmtflags original;\n std::ostream &amp;s;\npublic:\n flag_rest(std::ostream &amp;s) : original(s.flags()), s(s) {}\n ~flag_rest() { s.flags(original); }\n};\n</code></pre>\n\n<p>Using that, <code>printhex</code> gets a little simpler:</p>\n\n<pre><code>template&lt;typename T&gt;\nvoid PrintHex(std::string Description, T Value, long Mask = -1)\n{\n using namespace std;\n flag_rest f(cout);\n\n cout &lt;&lt; showbase\n &lt;&lt; hex\n &lt;&lt; Description\n &lt;&lt; \" = \"\n &lt;&lt; (static_cast&lt;unsigned short&gt;(Value) &amp; Mask)\n &lt;&lt; endl;\n}\n</code></pre>\n\n<p>Probably more importantly, it also restores the flag to the state it held before the call, and does so dependably (even if the function exits via an exception). Of course, it's also nice that <code>flag_rest</code> is fairly reusable as well.</p>\n\n<p>Of course, the cast to <code>unsigned short</code> means this can (will) misbehave or any type larger than a short, though I doubt you really care a lot about it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-09T13:13:34.953", "Id": "75884", "Score": "0", "body": "I like the idea of having a flags guard :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-09T03:08:08.987", "Id": "43836", "ParentId": "11360", "Score": "7" } } ]
{ "AcceptedAnswerId": "43836", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T01:22:09.183", "Id": "11360", "Score": "3", "Tags": [ "c++" ], "Title": "Bit field structures in C++" }
11360
<p>I know it's been done a million times already, but I couldn't find a serialization library to suit my needs. This is the very basis of what I came up with. I know the code is ugly and unstructured, so you don't have to tell me that.</p> <p>My goal is to make a serialization/deserialization system that provides a minimal, optimally non-intrusive interface for all classes, but can also store data verbosely, including variable names and type names. I will also implement a linear search-like tool that allows you to quickly access only a certain variable inside a structure hierarchy without having to serialize your whole app.</p> <p>I'm wondering if any of this can be done in a more simple way. I especially don't like that I need to hard-code the class name for my classes, but I couldn't find a more simple solution to do it in a compiler-independent way.</p> <p>Serializer.h:</p> <pre><code>#ifndef jag_SERIALIZER_H_ #define jag_SERIALIZER_H_ #include "jag_config.h" namespace jag { namespace Serializer { struct SerializedData { SerializedData(const std::string&amp; n, const std::string&amp; val = "", const std::string&amp; t = "") : name(n), value(val), type_name(t) { } std::string name; std::string value; std::string type_name; std::list&lt;SerializedData&gt; collection_value; }; template&lt;class T&gt; struct Type { static const std::string GetTypeName() { return T::GetTypeName(); } }; #define PRIMITIVE_TYPENAME(type) \ template&lt;&gt; \ struct Type&lt;type&gt; { \ static const std::string GetTypeName() { \ return #type; \ } }; PRIMITIVE_TYPENAME(int) PRIMITIVE_TYPENAME(float) #undef PRIMITIVE_TYPENAME #define COLLECTION_TYPENAME(type) \ template&lt;class T&gt; \ struct Type&lt;std::type&lt;T&gt;&gt; { \ static const std::string GetTypeName() { \ return std::string(#type) + " of " + Type&lt;T&gt;::GetTypeName(); \ } }; COLLECTION_TYPENAME(list) #undef COLLECTION_TYPENAME template&lt;class T&gt; struct EnumeratedValue { EnumeratedValue(T&amp; val, const std::string&amp; n) : name(n), value(val), type_name(Type&lt;T&gt;::GetTypeName()) { } std::string name; T&amp; value; std::string type_name; }; template&lt;class T, class Collector&gt; struct GetSer { static SerializedData GetSerializedData(const EnumeratedValue&lt;T&gt;&amp; data) { SerializedData sd(data.name); Collector coll; data.value.EnumerateComponents(coll); sd.collection_value = coll.datas; sd.type_name = data.type_name; return sd; } }; #define LEXICAL_SPEC(type) \ template&lt;class Collector&gt; \ struct GetSer&lt;type, Collector&gt; { \ static SerializedData GetSerializedData(const EnumeratedValue&lt;type&gt;&amp; data) { \ return SerializedData(data.name, boost::lexical_cast&lt;std::string&gt;(data.value), data.type_name); \ } \ }; LEXICAL_SPEC(float) LEXICAL_SPEC(int) #undef LEXICAL_SPEC template&lt;class T, class Collector&gt; struct GetSer&lt;std::list&lt;T&gt;, Collector&gt; { static SerializedData GetSerializedData(const EnumeratedValue&lt;std::list&lt;T&gt; &gt;&amp; data) { SerializedData all_sd(data.name); unsigned count = 0; for (auto&amp; d : data.value) { Collector coll; d.EnumerateComponents(coll); SerializedData sd("#" + boost::lexical_cast&lt;std::string&gt;(count)); sd.type_name = Type&lt;T&gt;::GetTypeName(); sd.collection_value = coll.datas; all_sd.collection_value.push_back(sd); ++count; } all_sd.type_name = data.type_name; return all_sd; } }; struct SerializerCollector { template&lt;class T&gt; SerializerCollector&amp; operator&lt;&lt;(const EnumeratedValue&lt;T&gt;&amp; en) { SerializedData sd = GetSer&lt;T, SerializerCollector&gt;::GetSerializedData(en); datas.push_back(sd); return *this; } std::list&lt;SerializedData&gt; datas; }; inline std::string FlattenSerializedData(const std::list&lt;SerializedData&gt;&amp; datas, const std::string&amp; prefix) { std::stringstream ret; for (auto&amp; d : datas) { ret &lt;&lt; "\n"; ret &lt;&lt; prefix &lt;&lt; d.type_name &lt;&lt; " " &lt;&lt; d.name &lt;&lt; " ="; if (!d.value.empty()) { ret &lt;&lt; " " &lt;&lt; d.value; } else { ret &lt;&lt; "\n" &lt;&lt; FlattenSerializedData(d.collection_value, prefix + " "); } } return ret.str(); } template&lt;class T&gt; std::string Serialize(const EnumeratedValue&lt;T&gt;&amp; val) { return val.type_name + " " + val.name + " = " + FlattenSerializedData(GetSer&lt;T, SerializerCollector&gt;::GetSerializedData(val).collection_value, " "); } #define E(x) (jag::Serializer::EnumeratedValue&lt;decltype(x)&gt;(x, #x)) struct Sample2 { int b; /* template&lt;class T&gt; void EnumerateComponents(T&amp; e) { e &lt;&lt; E(b); }*/ }; struct Sample { float a; Sample2 s; Sample() : a(4.2f) { s.b = 3; } template&lt;class T&gt; void EnumerateComponents(T&amp; e) { e &lt;&lt; E(a)&lt;&lt; E(s); } }; template&lt;class Collector&gt; struct GetSer&lt;Sample2, Collector&gt; { static SerializedData GetSerializedData(const EnumeratedValue&lt;Sample2&gt;&amp; data) { SerializedData sd(data.name); sd.value = "go away"; return sd; } }; } } #endif /* jag_SERIALIZER_H_ */ </code></pre> <p>A simple class that uses it:</p> <pre><code> namespace Math { template&lt;class T&gt; struct Triangle { explicit Triangle(const T&amp; p1, const T&amp; p2, const T&amp; p3, bool validate = true) : p1(p1), p2(p2), p3(p3) { if (validate) Validate(); } Triangle() { } template&lt;class B&gt; void EnumerateComponents(B&amp; e) { e &lt;&lt; E(p1)&lt;&lt; E(p2) &lt;&lt; E(p3); } static const std::string GetTypeName() { return "Triangle of " + Serializer::Type&lt;T&gt;::GetTypeName(); } inline bool operator==(const Triangle&lt;T&gt;&amp; other) const { return p1 == other.p1 &amp;&amp; p2 == other.p2 &amp;&amp; p3 == other.p3; } inline void Validate() const { JAG_ASSERT(p1 != p2 &amp;&amp; p2 != p3 &amp;&amp; p3 != p1); } inline bool Contains(const vec3&amp; coord) const { return p1 == coord || p2 == coord || p3 == coord; } inline T GetSurfaceNormalCCW() const { Validate(); const T u = p2 - p1; const T v = p3 - p1; vec3 norm; norm.x = u.y * v.z - u.z * v.y; norm.y = u.z * v.x - u.x * v.z; norm.z = u.x * v.y - u.y * v.x; return Math::normalize(norm); } const T* data() const { return &amp;p1; } T p1; T p2; T p3; }; </code></pre> <p>As you can see I only had to add two functions - an enumerator and a typename function.</p> <p>Here's a test function:</p> <pre><code>Math::Triangle&lt;int&gt; tri; tri.p1 = 2; tri.p2 = 3; tri.p3 = 4; std::list&lt;Math::Triangle&lt;int&gt; &gt; trilist; trilist.push_back(tri); tri.p3 = 666; trilist.push_back(tri); JAG_LOG&lt;&lt; "\n" &lt;&lt; Serializer::Serialize(E(trilist)); </code></pre> <p>And finally, the result:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>list of Triangle of int trilist = Triangle of int #0 = int p1 = 2 int p2 = 3 int p3 = 4 Triangle of int #1 = int p1 = 2 int p2 = 3 int p3 = 666 </code></pre> </blockquote>
[]
[ { "body": "<p>The claim <em>\"As you can see I only had to add two functions - an enumerator and a typename function.\"</em> will not generally be true for every type. Specifically, you'll also need to provide an appropriate <code>operator&lt;&lt;</code> for every type you'd like to use as a member in a serializable type.</p>\n\n<p>When doing so, you'll also need to pay special attention to pointers and pointer-like things. Currently, if your program tries to use a deserialized pointer that was serialized by another instance of your program, things will likely blow up. You'll want to serialize the pointed-at thing as well. And you'll need to keep track of all those pointed-at things, so that multiple pointers can point to the same thing on both ends.</p>\n\n<p>There are other types that will be problematic as well, such as mutexes. Basically, unless it employs pure value semantics, it's going to be hard to serialize reliably. Trying to handle all of this in the serializer is going to get really messy really quickly. So come up with some way for classes to say \"Nuh-uh, I'm gonna do my own (de)serialization\".</p>\n\n<p>I also have some portability and maintainability concerns regarding the way you're storing type information. As the code currently stands, I'm not sure how you plan on identifying the correct type to instantiate when deserializing. </p>\n\n<p>I'd also strongly recommend adding some protocol information at the start of any serialization stream. At the very least have a couple of magic bytes, so you can avoid blowing up when faced with something that's not actually a serialization stream. If you eventually want to support this code in the wild, I'd also suggest adding versioning to your protocol.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-29T16:38:36.940", "Id": "75139", "ParentId": "11367", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T09:31:36.180", "Id": "11367", "Score": "6", "Tags": [ "c++", "library", "reflection", "serialization" ], "Title": "Basis of custom C++ serialization lib" }
11367
<p>Here is what I have. A <code>User</code> model and an <code>Address</code> model. <code>User</code> <code>has_many :addresses</code> and Address belongs_to :user.</p> <p>Now I want to search for users whose email contains a give term, or one of the user's addresses contains that term. So lets say the term is 'jap', any User whose <code>email like '%jap%'</code> or any user whose any address city or address_line is <code>like '%jap%'</code> should be returned.</p> <p>I can get the Users with a simple join like this:</p> <pre><code>users = User.joins('LEFT OUTER JOIN addresses ON users.id=addresses.user_id').where('users.email like '%jap%' OR addresses.city like '%jap%' OR addresses.address_line like '%jap%') </code></pre> <p>then to get those addresses (if any) that matched the search term I have to query again for each user returned:</p> <pre><code>users.each do |u| u.addresses.where("addresses.city like '%jap%' OR addresses.address_line like '%jap%'") end </code></pre> <p>Is there a way to improve this so that I only search the addresses table once? I mean, a single query that returns the Users and the matching addresses for each user.</p>
[]
[ { "body": "<pre><code>User.joins(:addresses).where([\"addresses.city like ? OR addresses.address_line like ?\", '%jap%', '%jap%'])\n</code></pre>\n\n<p>or</p>\n\n<pre><code>a = Address.arel_table\nUser.joins(:addresses).where(a[:city].matches('%jap%').or(a[:address_line].matches('%jap%')))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T08:18:21.720", "Id": "11393", "ParentId": "11375", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T21:52:12.820", "Id": "11375", "Score": "2", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Query Rails 3 Active Record Fetch associated model based on conditions" }
11375
<p>Do you have any suggestions about how to make this code faster/better? Maybe suggest new features or better comments/docstrings? </p> <pre><code>from time import time, ctime, sleep from random import choice, uniform from glob import glob import os # Gets current working directory DIRECTORY_NAME = os.getcwd() def load(): """Prints loading messages""" os.system("clear") MESSAGES = ["Deleting hard drive...", "Reticulating Spines...", "Fetching Your Credit Card Number...", "Hacking your computer..."] print(choice(MESSAGES)) sleep(uniform(1, 5)) os.system("clear") def print_dir(dirname): """Prints the current directory""" print("Directory: %s" % dirname) print("-"*80) def number_of_files(dirname): """Finds the number of files in the directory using glob""" num_of_files = len(glob("*")) print(num_of_files, "files") print("-"*80) def last_access(dirname): """Prints a ctime representation of the last access to a file""" print("Last Access: ") print(ctime(os.path.getatime(dirname))) print("-"*80) def last_change(dirname): """Prints a ctime representation of the last change to a file""" print("Last Change: ") print(ctime(os.path.getmtime(dirname))) print("-"*80) def size_of_dir(dirname): """Walks through the directory, getting the cumulative size of the directory""" sum = 0 for file in os.listdir(dirname): sum += os.path.getsize(file) print("Size of directory: ") print(sum, "bytes") print(sum/1000, "kilobytes") print(sum/1000000, "megabytes") print(sum/1000000000, "gigabytes") print("-"*80) input("Press ENTER to view all files and sizes") def files_in_dir(dirname): """Walks through the directory, printing the name of the file as well as its size""" print("Files in directory: %s" % dirname) for file in os.listdir(dirname): print("{0} =&gt; {1} bytes".format(file, os.path.getsize(file))) load() print_dir(DIRECTORY_NAME) number_of_files(DIRECTORY_NAME) last_access(DIRECTORY_NAME) last_change(DIRECTORY_NAME) size_of_dir(DIRECTORY_NAME) files_in_dir(DIRECTORY_NAME) </code></pre>
[]
[ { "body": "<pre><code>input(\"Press ENTER to view all files and sizes\")\n</code></pre>\n\n<p>should be at the beginning of the <code>files_in_dir</code> function. <code>size_of_dir</code> should not know anything about what is next called function after it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T00:05:28.447", "Id": "18254", "Score": "0", "body": "Thanks for the suggestion, I'll implement it. Anything else you'd like to add? Did you like the code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T00:12:29.293", "Id": "18256", "Score": "0", "body": "It's fine for me, but I have never written any code in Python :-) I guess others will check it too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T00:01:37.183", "Id": "11381", "ParentId": "11376", "Score": "0" } }, { "body": "<pre><code>from time import time, ctime, sleep\nfrom random import choice, uniform\nfrom glob import glob\nimport os\n\n# Gets current working directory \nDIRECTORY_NAME = os.getcwd()\n</code></pre>\n\n<p>Given that its global and all caps, I'd expect it to be a constant. But it's not really a constant.</p>\n\n<pre><code>def load():\n \"\"\"Prints loading messages\"\"\"\n os.system(\"clear\")\n</code></pre>\n\n<p>This isn't portable, you may want to check out: <a href=\"https://stackoverflow.com/questions/2084508/clear-terminal-in-python\">https://stackoverflow.com/questions/2084508/clear-terminal-in-python</a></p>\n\n<pre><code> MESSAGES = [\"Deleting hard drive...\", \"Reticulating Spines...\", \"Fetching Your Credit Card Number...\", \"Hacking your computer...\"]\n</code></pre>\n\n<p>I'd put this as a global outside of the function.</p>\n\n<pre><code> print(choice(MESSAGES))\n sleep(uniform(1, 5))\n os.system(\"clear\")\n\ndef print_dir(dirname):\n \"\"\"Prints the current directory\"\"\"\n</code></pre>\n\n<p>It prints the directory passed in, not the current directory</p>\n\n<pre><code> print(\"Directory: %s\" % dirname)\n print(\"-\"*80)\n</code></pre>\n\n<p>You do this several times, perhaps write a function for it</p>\n\n<pre><code>def number_of_files(dirname):\n \"\"\"Finds the number of files in the directory using glob\"\"\"\n</code></pre>\n\n<p>I wouldn't put details like how it counts the files in the docstring</p>\n\n<pre><code> num_of_files = len(glob(\"*\"))\n print(num_of_files, \"files\")\n print(\"-\"*80)\n\ndef last_access(dirname):\n \"\"\"Prints a ctime representation of the last access to a file\"\"\"\n print(\"Last Access: \")\n print(ctime(os.path.getatime(dirname)))\n print(\"-\"*80)\n\ndef last_change(dirname):\n \"\"\"Prints a ctime representation of the last change to a file\"\"\"\n print(\"Last Change: \")\n print(ctime(os.path.getmtime(dirname)))\n print(\"-\"*80)\n</code></pre>\n\n<p>These two functions are quite similar. Considering combining them, passing the os.path.xtime function as a parameter</p>\n\n<pre><code>def size_of_dir(dirname):\n \"\"\"Walks through the directory, getting the cumulative size of the directory\"\"\"\n sum = 0\n</code></pre>\n\n<p>sum isn't a great choice because there is a builtin python function by that name</p>\n\n<pre><code> for file in os.listdir(dirname):\n sum += os.path.getsize(file)\n</code></pre>\n\n<p>I'd use <code>directory_size = sum(map(os.path.getsize, os.listdir(dirname))</code></p>\n\n<pre><code> print(\"Size of directory: \")\n print(sum, \"bytes\")\n print(sum/1000, \"kilobytes\")\n print(sum/1000000, \"megabytes\")\n print(sum/1000000000, \"gigabytes\")\n print(\"-\"*80)\n input(\"Press ENTER to view all files and sizes\")\n</code></pre>\n\n<p>As palacsint mentioned, this should really be in the next function, or perhaps in your main function.</p>\n\n<pre><code>def files_in_dir(dirname):\n \"\"\"Walks through the directory, printing the name of the file as well as its size\"\"\"\n print(\"Files in directory: %s\" % dirname)\n for file in os.listdir(dirname):\n</code></pre>\n\n<p>file is builtin class in python, I'd avoid using it as a local variable name</p>\n\n<pre><code> print(\"{0} =&gt; {1} bytes\".format(file, os.path.getsize(file)))\n\n\nload()\nprint_dir(DIRECTORY_NAME)\nnumber_of_files(DIRECTORY_NAME)\nlast_access(DIRECTORY_NAME)\nlast_change(DIRECTORY_NAME)\nsize_of_dir(DIRECTORY_NAME)\nfiles_in_dir(DIRECTORY_NAME)\n</code></pre>\n\n<p>I'd suggesting putting all of these in a main() function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T00:31:14.557", "Id": "11382", "ParentId": "11376", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T22:56:47.220", "Id": "11376", "Score": "1", "Tags": [ "python" ], "Title": "Directory operations" }
11376
<p>I was looking for a solution to allow me to rate limit the number of outgoing REST calls but preserved the order of queued elements so I found a <a href="http://www.pennedobjects.com/2010/10/better-rate-limiting-with-dot-net/" rel="noreferrer">rate limiter implementation</a> and combined it with <code>ConcurrentQueue&lt;T&gt;</code>.</p> <p>Improvements/critique?</p> <p><strong>Version 2 after assimilating svick's comments and adding a Unit Test</strong></p> <p>Throttle class is the renamed version of RateGate</p> <pre><code>public static class BlockingCollectionExtensions { // TODO: devise a way to avoid problems if collection gets too big (produced faster than consumed) public static IObservable&lt;T&gt; AsRateLimitedObservable&lt;T&gt;(this BlockingCollection&lt;T&gt; sequence, int items, TimeSpan timePeriod, CancellationToken producerToken) { Subject&lt;T&gt; subject = new Subject&lt;T&gt;(); // this is a dummyToken just so we can recreate the TokenSource // which we will pass the proxy class so it can cancel the task // on disposal CancellationToken dummyToken = new CancellationToken(); CancellationTokenSource tokenSource = CancellationTokenSource.CreateLinkedTokenSource(producerToken, dummyToken); var consumingTask = new Task(() =&gt; { using (var throttle = new Throttle(items, timePeriod)) { while (!sequence.IsCompleted) { try { T item = sequence.Take(producerToken); throttle.WaitToProceed(); try { subject.OnNext(item); } catch (Exception ex) { subject.OnError(ex); } } catch (OperationCanceledException) { break; } } subject.OnCompleted(); } }, TaskCreationOptions.LongRunning); return new TaskAwareObservable&lt;T&gt;(subject, consumingTask, tokenSource); } private class TaskAwareObservable&lt;T&gt; : IObservable&lt;T&gt;, IDisposable { private readonly Task task; private readonly Subject&lt;T&gt; subject; private readonly CancellationTokenSource taskCancellationTokenSource; public TaskAwareObservable(Subject&lt;T&gt; subject, Task task, CancellationTokenSource tokenSource) { this.task = task; this.subject = subject; this.taskCancellationTokenSource = tokenSource; } public IDisposable Subscribe(IObserver&lt;T&gt; observer) { var disposable = subject.Subscribe(observer); if (task.Status == TaskStatus.Created) task.Start(); return disposable; } public void Dispose() { // cancel consumption and wait task to finish taskCancellationTokenSource.Cancel(); task.Wait(); // dispose tokenSource and task taskCancellationTokenSource.Dispose(); task.Dispose(); // dispose subject subject.Dispose(); } } } </code></pre> <p>Unit test:</p> <pre><code>class BlockCollectionExtensionsTest { [Fact] public void AsRateLimitedObservable() { const int maxItems = 1; // fix this to 1 to ease testing TimeSpan during = TimeSpan.FromSeconds(1); // populate collection int[] items = new[] { 1, 2, 3, 4 }; BlockingCollection&lt;int&gt; collection = new BlockingCollection&lt;int&gt;(); foreach (var i in items) collection.Add(i); collection.CompleteAdding(); IObservable&lt;int&gt; observable = collection.AsRateLimitedObservable(maxItems, during, CancellationToken.None); BlockingCollection&lt;int&gt; processedItems = new BlockingCollection&lt;int&gt;(); ManualResetEvent completed = new ManualResetEvent(false); DateTime last = DateTime.UtcNow; observable // this is so we'll receive exceptions .ObserveOn(new SynchronizationContext()) .Subscribe(item =&gt; { if (item == 1) last = DateTime.UtcNow; else { TimeSpan diff = (DateTime.UtcNow - last); last = DateTime.UtcNow; Assert.InRange(diff.TotalMilliseconds, during.TotalMilliseconds - 30, during.TotalMilliseconds + 30); } processedItems.Add(item); }, () =&gt; completed.Set() ); completed.WaitOne(); Assert.Equal(items, processedItems, new CollectionEqualityComparer&lt;int&gt;()); } } </code></pre> <p><strong>Version 1 for reference</strong></p> <pre><code>public static class QueueExtensions { public static IObservable&lt;T&gt; LimitRateObservable&lt;T&gt;(this ConcurrentQueue&lt;T&gt; sequence, int items, TimeSpan timePeriod, CancellationToken token) { Subject&lt;T&gt; subject = new Subject&lt;T&gt;(); Task.Factory.StartNew(() =&gt; { using (var rateGate = new RateGate(items, timePeriod)) { while (!token.IsCancellationRequested) { // we could have added a Sleep() here if the queue is empty // to avoid hammering it with Dequeue requests // but the limiting itself does the work for us T item; if (sequence.TryDequeue(out item)) { rateGate.WaitToProceed(); subject.OnNext(item); } } Console.WriteLine("Stopping"); } subject.OnCompleted(); }); return subject.AsObservable(); } } class Program { static void Main(string[] args) { ConcurrentQueue&lt;int&gt; queue = new ConcurrentQueue&lt;int&gt;(); int c = 0; var timer = new Timer(foo =&gt; { queue.Enqueue(c++); Console.WriteLine("Added item " + c); }, null, 0, 300); CancellationTokenSource tokenSource = new CancellationTokenSource(); IObservable&lt;int&gt; observable = queue.LimitRateObservable(1, TimeSpan.FromSeconds(1), tokenSource.Token); using (observable.Timestamp().Subscribe( x =&gt; Console.WriteLine("{0}: {1}", x.Value, x.Timestamp.ToString("u")))) { Console.WriteLine("Press any key to unsubscribe"); Console.ReadKey(); timer.Dispose(); tokenSource.Cancel(); } Console.WriteLine("Disposed"); Thread.Sleep(4000); // wait to show that the produced has finished } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T23:28:39.507", "Id": "18252", "Score": "0", "body": "I don't understand, why is `BlockingCollection` lacking when it comes to order of the elements? By default, it internally uses `ConcurrentQueue`, which guarantees FIFO order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T23:47:33.097", "Id": "18253", "Score": "0", "body": "Hm... you are correct, I messed something up in my original tests. `BlockingCollection<T>.GetConsumingEnumerable()` does return the items in order. However, an integration point with the rate limiter is still necessary and so the implementation above would stay the same (I might as well use `ConcurrentQueue<T>`). I'll edit my question to remove this comment." } ]
[ { "body": "<p>I think the worst thing in that code is what you alluded to in your comment: if the queue is empty, your code will busy-wait, which is a very bad idea. To fix that, you could use <code>BlockingCollection&lt;T&gt;</code> and its blocking method <a href=\"http://msdn.microsoft.com/en-us/library/dd287085.aspx\" rel=\"nofollow\"><code>Take()</code></a>. And no, using <code>Thread.Sleep()</code> is not a good idea either.</p>\n\n<p>Another thing is that if the rate of the producer is higher than the rate of the limiter, the memory used by your application will increase indefinitely. You should devise some way to limit that, like setting an upper bound to your <code>BlockingCollection&lt;T&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T00:26:25.233", "Id": "18258", "Score": "0", "body": "Great idea. I've adapted the implementation and it's much cleaner. I'm having a problem where the first item I'm calling OnNext() doesn't get printed. I think it is related to the `Task` starting before returning the `Observable`. Any ideas how to solve this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T00:37:08.110", "Id": "18259", "Score": "0", "body": "I think you have to `Subscribe()` to your observable before starting the timer to fix that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T00:01:30.480", "Id": "11380", "ParentId": "11377", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T23:01:56.557", "Id": "11377", "Score": "5", "Tags": [ "c#", "system.reactive" ], "Title": "Implementation of a throttled ConcurrentQueue Rx observer" }
11377
<p>I previously posted my <a href="https://codereview.stackexchange.com/questions/10858/what-is-wrong-with-this-java-code-is-it-hard-to-follow">first attempt</a> at writing a program that I was given to test my skills for a position that I was interviewing for. I have rewritten the program using the excellent advice that I received from that posting and I also started reading a book on Java Objects.</p> <p>I would like to see if I am getting a better understanding of OO design with this version.</p> <p>If anyone has suggestions for some good object design books, I would appreciate if you could post those too!</p> <p>I didn't include the two exception classes, but they just extend Exception.</p> <p>Thanks!</p> <p>Sample input: "CSE258: CSE244 CSE243 INTR100", "CSE221: CSE254 INTR100", "CSE254: CSE111 MATH210 INTR100", "CSE244: CSE243 MATH210 INTR100", "MATH210: INTR100", "CSE101: INTR100", "CSE111: INTR100", "ECE201: CSE111 INTR100", "ECE111: INTR100", "CSE243: CSE254", "INTR100:"</p> <pre><code>public class CourseLoad { private List courseCatalog; public CourseLoad(String[] courseDescriptions) throws InvalidCourseNameException, InvalidCourseDescriptionException { this.courseCatalog = new ArrayList(); for (int i = 0; i &lt; courseDescriptions.length; i++) { courseCatalog.add(new Course(courseDescriptions[i], false)); } } public List getCourseCatalog() { return courseCatalog; } } public class Schedule { private List courses; public Schedule() { courses = new ArrayList(); } public boolean hasCourseBeenTaken(Course course) { return courses.contains(course); } public void addCourse(Course course) { courses.add(course); } public String[] getPrintableSchedule() { String[] classes = new String[courses.size()]; for (int i = 0; i &lt; classes.length; i++) { classes[i] = ((Course) courses.get(i)).getCourseName(); } return classes; } public List getCourses() { return courses; } } public class Course { private List prerequisites; private String department; private int courseNumber; private static final int COURSE_NUMBER_LENGTH = 3; public Course(String courseDescription, boolean isPrerequisite) throws InvalidCourseDescriptionException, InvalidCourseNameException { if (!isPrerequisite) { if (isValidCourseDescription(courseDescription)) { int colonIndex = courseDescription.indexOf(':'); String courseName = courseDescription.substring(0, colonIndex); if (isValidCourseName(courseName)) { department = courseName.substring(0, courseName.length() - COURSE_NUMBER_LENGTH); courseNumber = Integer.parseInt(courseName.substring(courseName.length() - COURSE_NUMBER_LENGTH)); String prerequisites = courseDescription.substring(colonIndex); if (prerequisites.length() &gt; 1) { this.prerequisites = new ArrayList(); prerequisites = prerequisites.substring(1); StringTokenizer tokenizer = new StringTokenizer(prerequisites, " "); while (tokenizer.hasMoreTokens()) { String prerequisite = tokenizer.nextToken(); if (isValidCourseName(prerequisite)) { this.prerequisites.add(new Course(prerequisite, true)); } else { throw new InvalidCourseNameException("Invalid course name: " + courseName); } } } } else { throw new InvalidCourseNameException("Invalid course name: " + courseName); } } else { throw new InvalidCourseDescriptionException("Invalid course description: " + courseDescription); } } else { if (isValidCourseName(courseDescription)) { department = courseDescription.substring(0, courseDescription.length() - COURSE_NUMBER_LENGTH); courseNumber = Integer.parseInt(courseDescription.substring(courseDescription.length() - COURSE_NUMBER_LENGTH)); } else { throw new InvalidCourseNameException("Invalid course name: " + courseDescription); } } } public String getCourseName() { return department + courseNumber; } public List getPrerequisites() { return prerequisites; } public String getDepartment() { return department; } public int getCourseNumber() { return courseNumber; } public boolean hasPrerequisites() { return prerequisites != null &amp;&amp; prerequisites.size() &gt; 0; } private boolean isValidCourseName(String courseName) { // validate the course name - i.e. "CSE111" or "MATH999" Pattern courseNamePattern = Pattern.compile("^[A-Z]{3,4}[1-9][0-9]{2}$"); Matcher matcher = courseNamePattern.matcher(courseName); return matcher.matches(); } private boolean isValidCourseDescription(String courseDescription) { // validate the course description - i.e. "CSE111: CSE110 MATH101" // or "CSE110:" Pattern courseDescriptionPattern = Pattern.compile("^[A-Z]{3,4}[1-9][0-9]{2}(:$|:(\\s[A-Z]{3,4}[1-9][0-9]{2})+)"); Matcher matcher = courseDescriptionPattern.matcher(courseDescription); return matcher.matches(); } public boolean equals(Object that) { if (this == that) return true; if ( !(that instanceof Course) ) return false; return ((Course) that).department.equals(this.department) &amp;&amp; ((Course) that).courseNumber == this.courseNumber; } public int hashCode() { return this.department.hashCode() + this.courseNumber; } } public class CourseScheduler { public CourseScheduler() { } public String[] scheduleCourses(String[] courseDescriptions) { CourseLoad courseLoad; Schedule schedule = new Schedule(); if (courseDescriptions != null) { try { courseLoad = new CourseLoad(courseDescriptions); buildSchedule(schedule, courseLoad); } catch (InvalidCourseNameException e) { System.out.println(e.getMessage()); schedule.getCourses().clear(); } catch (InvalidCourseDescriptionException e) { System.out.println(e.getMessage()); schedule.getCourses().clear(); } } return schedule.getPrintableSchedule(); } private void buildSchedule(Schedule schedule, CourseLoad courseLoad) throws InvalidCourseNameException { Course course; Course courseToAdd = null; while (courseLoad.getCourseCatalog().size() &gt; 0) { for (int i = 0; i &lt; courseLoad.getCourseCatalog().size(); i++) { course = (Course) courseLoad.getCourseCatalog().get(i); if (havePrerequisitesBeenTaken(course, schedule)) { if (courseToAdd == null) { courseToAdd = course; } else if (course.getCourseNumber() &lt; courseToAdd.getCourseNumber()) { courseToAdd = course; } else if (course.getCourseNumber() == courseToAdd.getCourseNumber()) { if (course.getDepartment().compareTo(courseToAdd.getDepartment()) &lt; 0) { courseToAdd = course; } } } } if (courseToAdd == null) { throw new InvalidCourseNameException("No course found to add to schedule."); } schedule.addCourse(courseToAdd); courseLoad.getCourseCatalog().remove(courseToAdd); courseToAdd = null; } } private boolean havePrerequisitesBeenTaken(Course course, Schedule schedule) { if (!course.hasPrerequisites()) return true; List prerequisites = course.getPrerequisites(); for (int i = 0; i &lt; prerequisites.size(); i++) { if (!schedule.hasCourseBeenTaken((Course) prerequisites.get(i))) { return false; } } return true; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T20:25:41.570", "Id": "18349", "Score": "1", "body": "I'll take a look at it. I suggest you take a look at how to use [Generics](http://tutorials.jenkov.com/java-generics/index.html) properly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T09:15:12.213", "Id": "21688", "Score": "0", "body": "This code seems okay but it is really very simple.\nIf you would like to know whether you are understanding OOD, perhaps you should talk through the concepts with someone you know? If you do not know anyone near you there are various programming forums you can post on as well as people you might know online. Why don't you try to explain to an experienced programmer what you think the main points of OO are." } ]
[ { "body": "<p>Some quick comments:</p>\n\n<p>For the getPrintableSchedule method in class Schedule.\nYou can override the method toString() in the class Course, so you get a \"printable\" version of a Course.</p>\n\n<p>In your for loops, you are calculating the length of your arrays in every iteration. Since you are not using threads and there is no risk of changing the size of your array during the execution of your loop, it is more efficient to extract it from your loop. Example: class Schedule - getPrintableSchedule</p>\n\n<pre><code>int arrayLength = classes.length;\nfor (int i=0; i &lt; arrayLenght; i++) { ... }\n</code></pre>\n\n<p>In your constructor Course, there is some repeated code for getting the course department and number. You can create a method </p>\n\n<pre><code>public String getCourseDepartment(String myCourse) {\n return myCourse.substring(0, myCourse.lenght() - COURSE_NUMBER_LENGTH);\n}\n</code></pre>\n\n<p>and call it with the appropiate String from the two points of your code.</p>\n\n<p>Same thing for getting the course number.</p>\n\n<p>It is more, I would refactor the constructor to something like this:</p>\n\n<pre><code>public Course(String courseDescription, boolean isPrerequisite) throws InvalidCourseDescriptionException, InvalidCourseNameException {\n if (isValidCourseDescription(courseDescription)) {\n String courseName = courseDescription;\n if (!isPrerequisite) {\n int colonIndex = courseDescription.indexOf(':');\n courseName = courseDescription.substring(0, colonIndex);\n }\n\n if (isValidCourseName(courseName)) {\n department = getCourseDepartment();\n courseNumber = getCourseNumber();\n } \n ....\n // Process prerequisites, etc...\n }\n}\n</code></pre>\n\n<ul>\n<li>I think that some validations could be done twice as well. Does not course description validation ensure that the course name is valid?</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T00:39:10.690", "Id": "15054", "ParentId": "11379", "Score": "3" } }, { "body": "<p>wow that's alot of code in the Course <strong>constructor</strong>. Could this perhaps be factored out into some sort of load method. Or if you need to run this code for every course object, perhaps make a course createable using a static factory. So going with the refactoring suggestions already mentioned, you could do something like:</p>\n\n<pre><code>public class Course {\n\n protected Course() {\n // any initialisations could be done here as long as there are no side effects?\n }\n\n public static Course Create(String courseDescription, boolean isPrerequisite) throws InvalidCourseDescriptionException, InvalidCourseNameException {\n\n Course course = new Course(courseDescription);\n\n if(isPrerequisite) {\n course.LoadPrequisite(courseDescription);\n } else {\n course.Load(courseDescription);\n }\n\n return course();\n }\n\n protected void LoadPrerequisite(String courseDescription) {\n\n }\n\n protected void LoadCourse(String courseDescription) {\n\n }\n}\n</code></pre>\n\n<p>then it would be used:</p>\n\n<pre><code>Course course = Course.Create(description, isPrequisite);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T05:30:28.420", "Id": "15056", "ParentId": "11379", "Score": "2" } }, { "body": "<p>I think by far the most important advice I could give you is not to do any work in your constructors. Look up <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow\">dependency injection</a>. It basically states that you should ask for the objects that you need directly, instead of asking for building blocks and using those to construct your dependencies yourself. </p>\n\n<p>So a simplified example:</p>\n\n<pre><code>//The wrong way, doesn't ask for what it needs, lies about its dependencies.\npublic Foo(Bar bar) {\n this.fooBar = bar.getFooBar();\n}\n\n//The right way, asks only for what it needs.\npublic Foo(FooBar fooBar) {\n this.fooBar = fooBar;\n}\n</code></pre>\n\n<p>I recommend you watch <a href=\"https://www.youtube.com/watch?v=RlfLCWKxHJ0&amp;list=FLfyOD7OZAkkkazjTXb_pRfQ&amp;index=4\" rel=\"nofollow\">this lecture</a> by Misko Hevery, who explains this very well.</p>\n\n<p>On an unrelated note: even if your constructor was a regular method, it would still be waaay too big. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-17T20:44:55.260", "Id": "54556", "ParentId": "11379", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T23:48:31.603", "Id": "11379", "Score": "1", "Tags": [ "java", "object-oriented" ], "Title": "Do the objects in this code follow OO standards?" }
11379
<p>I'm writing a program to build and solve a Maze using DFS and backtracking using Java Swing. The code was a mess when I have to put my logic into my JPanel in order to show animation via the call to <code>repaint()</code>. Here are all classes: </p> <p><strong>Point</strong></p> <pre><code>public class Point { public int mX; public int mY; public Point(int x, int y) { mX = x; mY = y; } } </code></pre> <p><strong>Turtle</strong> </p> <pre><code>import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; public class Turtle { private int mXPos; private int mYPos; private Color mColor; public Turtle(Color c) { mXPos = 0; mYPos = 0; mColor = c; } public void setPosition(int x, int y) { mXPos = x; mYPos = y; } public int getXPos() { return mXPos; } public int getYPos() { return mYPos; } public void draw(Graphics g) { int width = 15; int height = 18; int heading = 0; int xPos = mXPos; int yPos = mYPos; // cast to 2d object Graphics2D g2 = (Graphics2D) g; // save the current transformation AffineTransform oldTransform = g2.getTransform(); // rotate the turtle and translate to xPos and yPos g2.rotate(Math.toRadians(heading),xPos,yPos); // determine the half width and height of the shell int halfWidth = (int) (width/2); // of shell int halfHeight = (int) (height/2); // of shell int quarterWidth = (int) (width/4); // of shell int thirdHeight = (int) (height/3); // of shell int thirdWidth = (int) (width/3); // of shell // draw the body parts (head) g2.setColor(mColor); g2.fillOval(xPos - quarterWidth, yPos - halfHeight - (int) (height/3), halfWidth, thirdHeight); g2.fillOval(xPos - (2 * thirdWidth), yPos - thirdHeight, thirdWidth, thirdHeight); g2.fillOval(xPos - (int) (1.6 * thirdWidth), yPos + thirdHeight, thirdWidth, thirdHeight); g2.fillOval(xPos + (int) (1.3 * thirdWidth), yPos - thirdHeight, thirdWidth, thirdHeight); g2.fillOval(xPos + (int) (0.9 * thirdWidth), yPos + thirdHeight, thirdWidth, thirdHeight); // draw the shell g2.setColor(mColor); g2.fillOval(xPos - halfWidth, yPos - halfHeight, width, height); // reset the transformation matrix g2.setTransform(oldTransform); } } </code></pre> <p><strong>MazeBuilder</strong> </p> <pre><code>import java.awt.BasicStroke; import java.awt.Color; import java.awt.Component; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import java.util.List; import java.util.ArrayList; import java.util.Scanner; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; public class MazeBuilder extends JPanel { /* * Maze row */ private static int ROW = 15; /* * Maze Column */ private static int COLUMN = 15; /* * Number of vertices */ private static int VERTICES = ROW * COLUMN; /* * Length of edge */ private static int SPACING = 40; /* * Spacing from the top left corner (0, 0) */ private static int SHIFTING = 50; /* * The goal is at the lower right corner */ private int mGoalVertex = VERTICES - 1; /* * The marked drawing map */ private boolean[][] mMap = new boolean[VERTICES][VERTICES]; /* * Vertex information * if mExplored[u] == true * vertex u is already visited */ private boolean[] mExplored = new boolean[VERTICES]; /* * Vertex information for solver * if mExplored[u] == true * vertex u is already visited */ private boolean[] mTurtleExplored = new boolean[VERTICES]; /* * The waiting time for repaint */ private static int BUILD_TIME = 5; /* * Delay time */ private static int SOLVE_TIME = 500; /* * Parent frame */ private JFrame mFrame; /* * Random generator */ private Random mRandom; /* * Current position of turtle */ private int mCurrentVertex = 0; /* * Solve mode */ private boolean flag = false; /* * Flag variable to signify the * maze have been completely built */ private boolean isCompletelyBuilt = false; /* * The turtle for maze solver */ private Turtle mSolver; /** * Constructor * * @param frame * the parent frame */ public MazeBuilder(JFrame frame) { mFrame = frame; // initialize random mRandom = new Random(); mSolver = new Turtle(Color.red); initGraph(); initExplored(); buildMenu(mFrame); } /** * Delay for an amount of time * before redraw the panel */ private void delay(int delayTime) { try { Thread.sleep(delayTime); } catch (InterruptedException e) { System.err.println("Error in delay"); } } private boolean noMoreVertices() { for (int i = 0; i &lt; VERTICES; ++i) { if (mTurtleExplored[i] == false) return false; } return true; } private void solveMazeBacktracking(int u) { mCurrentVertex = u; if (u == mGoalVertex || noMoreVertices()) { flag = false; return; } mTurtleExplored[u] = true; // for each neighbor of u make a move List&lt;Integer&gt; neighbors = getTurtleNeighbors(u); for (int i = 0; i &lt; neighbors.size(); ++i) { int v = neighbors.get(i); if (mMap[u][v] == true || mMap[v][u] == true) { delay(SOLVE_TIME); repaint(); solveMazeBacktracking(v); } } } /** * Build the menu bar and add * it to frame f * * @param f * frame to hold menu bar */ public void buildMenu(JFrame f) { JMenuBar bar = new JMenuBar(); JMenu optionMenu = new JMenu("Option"); JMenuItem item; item = new JMenuItem("Solve"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { flag = true; (new Thread() { public void run() { solveMazeBacktracking(0); } }).start(); } }); optionMenu.add(item); item = new JMenuItem("Build"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // repaint(); (new Thread() { public void run() { buildMazeDfs(0); } }).start(); } }); optionMenu.add(item); item = new JMenuItem("Reset"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (isCompletelyBuilt) { isCompletelyBuilt = false; resetMaze(); repaint(); } } }); optionMenu.add(item); bar.add(optionMenu); f.setJMenuBar(bar); } /** * Check if a square is in a maze * * @param x * the x coordinate in JPanel * @param y * the y coordinate in JPanel * * @return * true if it's in maze * false otherwise */ private boolean isInMaze(int x, int y) { return (x &gt;= 0 &amp;&amp; x &lt; ROW &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; COLUMN); } /** * Get the number of neighbors of a vertex * * @param u * vertex * * @return neighbors * an array list of int */ private List&lt;Integer&gt; getTurtleNeighbors(int u) { List&lt;Integer&gt; neighbors = new ArrayList&lt;Integer&gt;(); Point p = toPoint(u); int to = -1; // up if (isInMaze(p.mX - 1, p.mY)) { to = toVertex(p.mX - 1, p.mY); if (!mTurtleExplored[to]) neighbors.add(to); } // down if (isInMaze(p.mX + 1, p.mY)) { to = toVertex(p.mX + 1, p.mY); if (!mTurtleExplored[to]) neighbors.add(to); } // left if (isInMaze(p.mX, p.mY - 1)) { to = toVertex(p.mX, p.mY - 1); if (!mTurtleExplored[to]) neighbors.add(to); } // right if (isInMaze(p.mX, p.mY + 1)) { to = toVertex(p.mX, p.mY + 1); if (!mTurtleExplored[to]) neighbors.add(to); } return neighbors; } /** * Get the number of neighbors of a vertex * * @param u * vertex * * @return neighbors * vertex neighbor of u */ private List&lt;Integer&gt; getNeighbors(int u) { List&lt;Integer&gt; neighbors = new ArrayList&lt;Integer&gt;(); Point p = toPoint(u); int to = -1; // up if (isInMaze(p.mX - 1, p.mY)) { to = toVertex(p.mX - 1, p.mY); if (!mExplored[to]) neighbors.add(to); } // down if (isInMaze(p.mX + 1, p.mY)) { to = toVertex(p.mX + 1, p.mY); if (!mExplored[to]) neighbors.add(to); } // left if (isInMaze(p.mX, p.mY - 1)) { to = toVertex(p.mX, p.mY - 1); if (!mExplored[to]) neighbors.add(to); } // right if (isInMaze(p.mX, p.mY + 1)) { to = toVertex(p.mX, p.mY + 1); if (!mExplored[to]) neighbors.add(to); } return neighbors; } /** * DFS algorithm to remove edges * * @param u * starting vertex * */ private void buildMazeDfs(int u) { // mark that vertex as visited mExplored[u] = true; // get all neighbors List&lt;Integer&gt; neighbors = getNeighbors(u); int v = -1; // get a random vertex v if (neighbors.size() &gt; 0) { int idx = mRandom.nextInt(neighbors.size()); v = neighbors.get(idx); } if (v == -1) { System.out.println("Backtrack"); repaint(); isCompletelyBuilt = true; return; } // remove edge from u to v mMap[u][v] = true; mMap[v][u] = true; // loop through all u's neighbors for (int n = 0; n &lt; neighbors.size(); ++n) { // get the next neighbor int next = neighbors.get(n); // if it's not explored if (mExplored[next] == false) { // delay(BUILD_TIME); // repaint(); buildMazeDfs(next); } } } /** * Initialize vertices * false: unexplored * true: explored */ private void initExplored() { for (int i = 0; i &lt; VERTICES; ++i) { mExplored[i] = false; mTurtleExplored[i] = false; } } /** * Initialize all marked to true: * if mGraph[x][y] = true then * draw a line from x -&gt; y * * neighbor coordinates * ------------------------------------- * | | | | * | | (x-1, y) | | * | | | | * ------------------------------------- * | | | | * | (x, y-1) | (x, y) | (x, y+1) | * | | | | * ------------------------------------- * | | | | * | | (x+1, y) | | * | | | | * ------------------------------------- * */ private void initGraph() { // initialize all marked to false int vertices = ROW * COLUMN; for (int u = 0; u &lt; vertices; ++u) { for (int v = 0; v &lt; vertices; ++v) { mMap[u][v] = false; } } } /** * Convert a coordinate (x, y) to a vertex on graph * * ------------- * | 0 | 1 | 2 | * ------------- * | 3 | 4 | 5 | * ------------- * | 6 | 7 | 8 | * ------------- * * 1) formula: * -------------------------- * - vertex = x * ROW + y - * -------------------------- * * 2) check: * ROW = 3, COLUMN = 3 * then * [0][0] = 0 * 3 + 0 = 0 * [0][1] = 0 * 3 + 1 = 1 * [0][2] = 0 * 3 + 2 = 2 * * [1][0] = 1 * 3 + 0 = 3 * [1][1] = 1 * 3 + 1 = 4 * [1][2] = 1 * 3 + 2 = 5 * * [2][0] = 2 * 3 + 0 = 6 * [2][1] = 2 * 3 + 1 = 7 * [2][2] = 2 * 3 + 2 = 8 * * @param x * x coordinate * @param y * y coordinate * * @return * a vertex * */ private int toVertex(int x, int y) { return (x * ROW + y); } /** * Convert from a vertex v to a pair (x, y) * * 1) formula: * ----------------- * - x = v / ROW - * - y = v % ROW - * ----------------- * * 2) check: * 0 and [0][0] * x = 0 / 3 = 0 * y = 0 % 3 = 0 * * 1 and [0][1] * x = 0 / 3 = 0 * y = 1 % 3 = 1 * * 6 and [2][0] * x = 6 / 3 = 2 * y = 0 % 3 = 0 * * 8 and [0][1] * x = 8 / 3 = 2 * y = 8 % 3 = 2 * * @param v * vertex * * @return * a point */ private Point toPoint(int v) { return new Point(v / ROW, v % COLUMN); } private void resetMaze() { initGraph(); initExplored(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2D = (Graphics2D) g; g2D.setStroke(new BasicStroke(3f)); g.setColor(Color.black); for (int x = 0; x &lt; ROW; ++x) { for (int y = 0; y &lt; COLUMN; ++y) { Point p = new Point(x, y); drawAPoint(g, p); } } // for each vertex u, we check its 4 neighbors int left; int right; int up; int down; Point from; Point to; for (int u = 0; u &lt; VERTICES; ++u) { int c = u % COLUMN; int r = u / ROW; left = -1; right = -1; up = -1; down = -1; from = toPoint(u); // left if (c - 1 &gt;= 0) { left = r * ROW + c - 1; } // right if (c + 1 &lt;= COLUMN - 1) { right = r * ROW + c + 1; } // down if (r - 1 &gt;= 0) { down = (r - 1) * ROW + c; } // up if (r + 1 &lt;= ROW - 1) { up = (r + 1) * ROW + c; } if (left != -1) { to = toPoint(left); if (mMap[u][left]) drawRemoveEdge(g, from, to); } if (right != -1) { to = toPoint(right); if (mMap[u][right]) drawRemoveEdge(g, from, to); } if (up != -1) { to = toPoint(up); if (mMap[u][up]) drawRemoveEdge(g, from, to); } if (down != -1) { to = toPoint(down); if (mMap[u][down]) drawRemoveEdge(g, from, to); } // delay(BUILD_TIME); } for (int i = 0; i &lt; VERTICES; ++i) { if (mExplored[i]) { Point p = toPoint(i); g.setColor(Color.red); g.drawOval(p.mX * SPACING + 17 + SHIFTING, p.mY * SPACING + 17 + SHIFTING, 2, 2); } } if (flag) { Point p = toPoint(mCurrentVertex); mSolver.setPosition(p.mX * SPACING + 17 + SHIFTING, p.mY * SPACING + 17 + SHIFTING); mSolver.draw(g); for (int i = 0; i &lt; VERTICES; ++i) { if (mTurtleExplored[i]) { Point pp = toPoint(i); g.setColor(Color.green); g.drawOval(pp.mX * SPACING + 17 + SHIFTING, pp.mY * SPACING + 17 + SHIFTING, 2, 2); } } } // this is the only way out Color c = Color.decode("#EEEEEE"); g.setColor(c); Point p = new Point((ROW - 1)* SPACING + SHIFTING, (COLUMN - 1) * SPACING + SHIFTING); g.drawLine(p.mX + SPACING, p.mY, p.mX + SPACING, p.mY + SPACING); } /** * Remove an edge from to point * * @param g * graphics component * * @param cur * the current vertex * * @param adj * its neighbor */ private void drawRemoveEdge(Graphics g, Point cur, Point adj) { Color c = Color.decode("#EEEEEE"); g.setColor(c); Point p = new Point(cur.mX * SPACING + SHIFTING, cur.mY * SPACING + SHIFTING); // right if (cur.mX + 1 == adj.mX &amp;&amp; cur.mY == adj.mY) { g.drawLine(p.mX + SPACING, p.mY, p.mX + SPACING, p.mY + SPACING); } // left else if (cur.mX - 1 == adj.mX &amp;&amp; cur.mY == adj.mY) { g.drawLine(p.mX, p.mY, p.mX, p.mY + SPACING); } // top else if (cur.mX == adj.mX &amp;&amp; cur.mY - 1 == adj.mY) { g.drawLine(p.mX, p.mY, p.mX + SPACING, p.mY); } else if (cur.mX == adj.mX &amp;&amp; cur.mY + 1 == adj.mY){ g.drawLine(p.mX, p.mY + SPACING, p.mX + SPACING, p.mY + SPACING); } } /** * Draw a box around one point * * @param g * graphics component * * @param p * the point to be drawn */ private void drawAPoint(Graphics g, Point p) { // add spacing p.mX = p.mX * SPACING + SHIFTING; p.mY = p.mY * SPACING + SHIFTING; // draw top g.drawLine(p.mX, p.mY, p.mX + SPACING, p.mY); // draw left g.drawLine(p.mX, p.mY, p.mX, p.mY + SPACING); // draw right g.drawLine(p.mX + SPACING, p.mY, p.mX + SPACING, p.mY + SPACING); // draw bottom g.drawLine(p.mX, p.mY + SPACING, p.mX + SPACING, p.mY + SPACING); } /** * Build entire UI */ public static void buildGUI() { // create a container level JFrame JFrame frame = new JFrame("Maze Generator"); // set up frame frame.setSize(800, 800); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); // create a panel MazeBuilder app = new MazeBuilder(frame); app.buildMenu(frame); frame.setContentPane(app); } } </code></pre> <p><strong>Program</strong> </p> <pre><code>import javax.swing.SwingUtilities; public class Program { public static void main(String args[]) { // run on event-dispatching thread SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MazeBuilder.buildGUI(); } }); } } </code></pre> <p>I knew it was very bad when putting the logic of maze into the UI class, but I couldn't find a way to extract them out. Please help criticizing my code. Thanks.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T16:44:26.100", "Id": "18296", "Score": "1", "body": "Why did you create your own `Point` class? [Java already has one](http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Point.html) which looks identical to yours, except with some additional functionality. I would also either use or extend from it in the `Turtle` class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T01:08:29.370", "Id": "18310", "Score": "0", "body": "I'm newbie to Swing and Java, so I was not aware of that class. Thanks a lot." } ]
[ { "body": "<p>Here's a few tips:</p>\n\n<ul>\n<li>When I ran you program at first, I got a blank frame. Make sure <code>frame.setVisible(true)</code> is the last thing you do. Everything else should be set up before that.</li>\n<li><p>Really, really, really avoid magic numbers. Code like this:</p>\n\n<pre><code>public void draw(Graphics g) {\n int width = 15;\n int height = 18;\n // etc.\n}\n</code></pre>\n\n<p>Is really hard to maintain. You have a few constants. Just add more.</p></li>\n<li><p>Swing uses swing Timer and SwingWorker rather than threads. For example,</p>\n\n<pre><code>private class MazeSolvingWorker extends SwingWorker&lt;Void, Boolean[][]&gt; {\n\n // Stores its own copy of the map\n private Boolean[][] map_;\n\n // Needs to get map from main program\n public MazeSolvingWorker(Boolean[][] map) {\n map_ = map;\n }\n\n // This function replaces the run method\n @Override\n protected Void doInBackground() throws Exception {\n solveMazeBacktracking(0);\n return null;\n }\n\n // Need to override when you use publish\n @Override\n protected void process(List&lt;Boolean[][]&gt; chunks) {\n mMap = chunks.get(chunks.size() - 1);\n repaint();\n }\n\n private void solveMazeBacktracking(int u) {\n mCurrentVertex = u;\n if (u == mGoalVertex || noMoreVertices()) {\n flag = false;\n return;\n }\n\n mTurtleExplored[u] = true;\n\n // for each neighbor of u make a move\n List&lt;Integer&gt; neighbors = getTurtleNeighbors(u);\n for (int i = 0; i &lt; neighbors.size(); ++i) {\n int v = neighbors.get(i);\n if (map_[u][v] == true || map_[v][u] == true) {\n delay(SOLVE_TIME);\n // Thread-safe alternative to calling repaint directly\n publish(map_);\n solveMazeBacktracking(v);\n }\n }\n }\n\n}\n</code></pre>\n\n<p>Now you can replace this:</p>\n\n<pre><code>item.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n flag = true;\n (new Thread() {\n public void run() {\n solveMazeBacktracking(0);\n }\n }).start();\n }\n});\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code>item.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n flag = true;\n new MazeSolvingWorker(mMap).execute();\n }\n});\n</code></pre>\n\n<p>Replacing buildMazeDfs(int) is up to you.</p></li>\n<li><p>Normally, I would recommend using the <a href=\"http://piemaster.net/2011/07/entity-component-artemis/\">entity-system framework</a> to separate logic from data and ui, but you have a very simple program. Factor out a Maze class.</p></li>\n<li>This is just nit-picky, but you don't need a static method in <code>MazeBuilder</code> to build the gui. You can move that to <code>Program</code>, where it makes more sense. Or you could get rid of the <code>Program</code> class and put main in <code>MazeBuilder</code>. Just a style preference though. :)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-01T06:40:49.233", "Id": "13233", "ParentId": "11383", "Score": "5" } } ]
{ "AcceptedAnswerId": "13233", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T00:43:36.677", "Id": "11383", "Score": "6", "Tags": [ "java", "swing" ], "Title": "How to separate logic and GUI" }
11383
<p>I have found that writing unit tests helps me to discover both the intent and also reusability of code that I'm working on. It has been generally helpful in helping develop my "code smell."</p> <p>I was working on two unit tests that are basically mirror images, and realized that I was typing code that looked almost identical. I am hoping that someone could help me refactor the similar parts of these two unit tests into shared setup and tear-down methods.</p> <pre><code>- (void)testBlockMethodOne { NSError *expectedError = [NSError errorWithDomain:@"An error" code:42 userInfo:nil]; [mockClassA setError:expectedError]; [mockClassA setRunCompletionBlockImmediately:YES]; __block NSError *actualError = nil; __block id actualObject = nil; [classB fireClassAsBlockThenDoThisBlock:^(id object, NSError *error) { actualObject = object; actualError = error; }]; STAssertNil(actualObject, @"There was a problem"); STAssertEqualObjects(actualError, expectedError, @"Got the expected error"); } - (void)testBlockMethodTwo { NSObject *expectedObject = [[NSObject alloc] init]; [mockClassA setObject:expectedObject]; [mockClassA setRunCompletionBlockImmediately:YES]; __block NSError *actualError = nil; __block id actualObject = nil; [classB fireClassAsBlockThenDoThisBlock:^(id object, NSError *error) { actualObject = object; actualError = error; }]; STAssertNil(actualError, @"There was a problem"); STAssertEqualObjects(actualObject, expectedObject, @"Got the expected object"); } </code></pre> <p>A little background about what's being tested:</p> <p>In production code, <code>-fireClassAsBlockThenDoThisBlock</code> is asynchronous. But, of course, in the unit tests I have a mock standing in for "Class A" that just calls the block immediately with either the error or object that I set on the mock.</p> <p>I've repeated more setup code then I'd really like to between the two tests. My hope is once I see how someone else attacks this, I'll have gained some insight into refactoring block based methods.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T01:31:24.020", "Id": "18265", "Score": "0", "body": "I just realized that my method name could be read: \"Fire Class as...\" but it's intended as \"Fire Class A's...\"" } ]
[ { "body": "<p>It looks like you can extract the method bodies entirely. Warning: I typed this code into a web browser, not an IDE:</p>\n\n<pre><code>- (NSDictionary *)invokeClassBBlockRunnerWithExpectedObject: (id)object expectedError: (NSError *)error {\n [mockClassA setObject: object];\n [mockClassA setError: error];\n [mockClassA setRunCompletionBlockImmediately: YES];\n\n __block NSError *actualError = nil;\n __block id actualObject = nil;\n\n [classB fireClassAsBlockThenDoThisBlock: ^(id object, NSError *error) {\n actualObject = object;\n actualError = error;\n }];\n\n NSMutableDictionary *results = [NSMutableDictionary dictionary];\n if (actualObject) [results setObject: actualObject forKey: @\"Object\"];\n if (actualError) [results setObject: actualError forKey: @\"Error\"];\n return results;\n}\n\n- (void)testBlockMethodOne {\n NSError *expectedError = [NSError errorWithDomain: @\"An Error\" code: 42 userInfo: nil];\n NSDictionary *results = [self invokeClassBBlockRunnerWithObject: nil error: expectedError];\n\n STAssertNil([results objectForKey: @\"Object\"], @\"Shouldn't get an object when an error occurs\");\n STAssertEqualObjects(expectedError, [results objectForKey: @\"Error\"], @\"Should get the error I expected\");\n}\n\n- (void)testBlockMethodTwo {\n id expectedObject = [[NSObject alloc] init];\n NSDictionary *results = [self invokeClassBBlockRunnerWithObject: expectedObject error: nil];\n\n // you get the idea\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T09:23:51.077", "Id": "11398", "ParentId": "11384", "Score": "2" } } ]
{ "AcceptedAnswerId": "11398", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T01:26:34.527", "Id": "11384", "Score": "2", "Tags": [ "unit-testing", "objective-c" ], "Title": "Asyncronous unit test refactoring in Objective-C" }
11384
<p>I have recently made a small program to generate D&amp;D (original edition) monster stat blocks in text form. I use this program myself to generate stats block so that I can then copy and paste them in the adventures I am writing.</p> <p>The main reason for using a program is to have the program roll the random values.</p> <p>Here is an example of usage:</p> <pre><code>monsterGenerator:monster("Kobold", 3). </code></pre> <p>Here is an example of output:</p> <pre><code>Kobold(3), AC 7, HD 1/2, HP (1, 4, 2), Att 1 weapon, Dmg (Club 1d3-1, Dagger 1d4-1, Dagger 1d4-1), Save Normal Man, Morale 6, Treasure (2 cp, 12 cp, 21 cp), XP 5 </code></pre> <p>Here is the code in question:</p> <p>monsterGenerator.erl</p> <pre><code>-module(monsterGenerator). -export([monster/2]). monster(Name, Number) -&gt; case Name of "Bugbear" -&gt; io:format("~s(~p), AC 5, HD 3+1, HP ~p, Att 1 weapon, Dmg ~s +1 ~n", [Name, Number, [monster_hp(3, 1) || _ &lt;- lists:seq(1, Number)], [monsterWeapons:generate_weapon(large) || _ &lt;- lists:seq(1, Number)]]), io:format("Save Normal Man, Morale 6, Treasure ~s ~s, XP 50 ~n", [monsterTreasures:generate_treasure(p), monsterTreasures:generate_treasure(q)]); "Kobold" -&gt; io:format("~s(~p), AC 7, HD 1/2, HP ~p, Att 1 weapon, Dmg ~s -1 ~n", [Name, Number, [monster_hp(0.5) || _ &lt;- lists:seq(1, Number)], [monsterWeapons:generate_weapon(small) || _ &lt;- lists:seq(1, Number)]]), io:format("Save Normal Man, Morale 6, Treasure ~s, XP 5 ~n", [monsterTreasures:generate_treasure(p)]); "Skeleton" -&gt; io:format("~s(~p), AC 7, HD 1, HP ~p, Att 1 weapon, Dmg Claws 1d2 ~n", [Name, Number, [monster_hp(1) || _ &lt;- lists:seq(1, Number)]]), io:format("Save F1, Morale 12, Treasure ~s, XP 10 ~n", [monsterTreasures:generate_treasure(nil)]); "Goblin" -&gt; io:format("~s(~p), AC 6, HD 1-1, HP ~p, Att 1 weapon, Dmg ~s ~n", [Name, Number, [monster_hp(1, -1) || _ &lt;- lists:seq(1, Number)], [monsterWeapons:generate_weapon(small) || _ &lt;- lists:seq(1, Number)]]), io:format("Save Normal Man, Morale 6, Treasure ~s, XP 5 ~n", [[monsterTreasures:generate_treasure(r) || _ &lt;- lists:seq(1, Number)]]); "Centaur" -&gt; io:format("~s(~p), AC 5, HD 4, HP ~p, Att 2 hooves / 1 weapon, Dmg 1d6/1d6/by weapon ~s ~n", [Name, Number, [monster_hp(4) || _ &lt;- lists:seq(1, Number)], [monsterWeapons:generate_weapon(medium) || _ &lt;- lists:seq(1, Number)]]), io:format("Save Normal F4, Morale 8, Treasure ~s, XP 75 ~n", [monsterTreasures:generate_treasure(nil)]); "Neanderthal" -&gt; io:format("~s(~p), AC 8, HD 2, HP ~p, Att 1 weapon ~s ~n", [Name, Number, [monster_hp(2) || _ &lt;- lists:seq(1, Number)], [monsterWeapons:generate_weapon(primitive) || _ &lt;- lists:seq(1, Number)]]), io:format("Save Normal F2, Morale 8, Treasure ~s, XP 20 ~n", [monsterTreasures:generate_treasure(nil)]); "Harpy" -&gt; io:format("~s(~p), AC 7, HD 3, HP ~p, Att 3 2 claws / 1 weapon 1d4/1d4/ ~s ~n", [Name, Number, [monster_hp(3) || _ &lt;- lists:seq(1, Number)], [monsterWeapons:generate_weapon(medium) || _ &lt;- lists:seq(1, Number)]]), io:format("Save Normal F2, Morale 8, Treasure ~s, XP 20 ~n", [monsterTreasures:generate_treasure(nil)]); _ -&gt; io:format("Unknown.~n") end. monster_hp(0.5) -&gt; random:uniform(round(4)); monster_hp(HitDice) -&gt; lists:foldl(fun(X, Sum) -&gt; X + Sum end, 0, [random:uniform(round(8)) || _ &lt;- lists:seq(1, HitDice)]). monster_hp(HitDice, Modifier) -&gt; monster_hp(HitDice) + Modifier. </code></pre> <p>monsterTreasures.erl</p> <pre><code>-module(monsterTreasures). -export([generate_treasure/1]). generate_treasure(Type) -&gt; case Type of p -&gt; [integer_to_list(roll_dice(3, 8)), " cp"]; q -&gt; [integer_to_list(roll_dice(3, 6)), " sp"]; r -&gt; [integer_to_list(roll_dice(2, 6)), " ep"]; s -&gt; [integer_to_list(roll_dice(2, 4)), " gp", conditional_treasure(5, 1, "gems")]; t -&gt; [integer_to_list(roll_dice(1, 6)), " pp", conditional_treasure(5, 1, "gems")]; u -&gt; [conditional_treasure(10, 100, "cp "), conditional_treasure(10, 100, "sp "), conditional_treasure(5, 100, "gp "), conditional_treasure(5, 2, "gems "), conditional_treasure(5, 4, "jewelry "), conditional_treasure(2, 1, "special treasure "), conditional_treasure(2, 1, "magical items ")]; v -&gt; [conditional_treasure(10, 100, "sp "), conditional_treasure(5, 100, "ep "), conditional_treasure(10, 100, "gp "), conditional_treasure(5, 100, "pp "), conditional_treasure(10, 2, "gems "), conditional_treasure(10, 4, "jewelry "), conditional_treasure(5, 1, "special treasure "), conditional_treasure(5, 1, "magical items ")]; _ -&gt; ["No treasure"] end. conditional_treasure(Chance, Number, TreasureName) -&gt; Result = random:uniform(100), if Result =&lt; Chance -&gt; [integer_to_list(random:uniform(Number)), " ", TreasureName]; true -&gt; "" end. roll_dice(Number, DiceType) -&gt; lists:foldl(fun(_, Sum) -&gt; random:uniform(DiceType) + Sum end, 0, lists:seq(1, Number </code></pre> <p>monsterWeapons.erl</p> <pre><code>-module(monsterWeapons). -export([generate_weapon/1]). generate_weapon(Type) when Type == small -&gt; Weapons = ["Hand Axe 1d6 ", "Blackjack 1d2 ", "Torch 1d4 ", "Dagger 1d4 ", "Short Sword 1d6 ", "Small club 1d2 ", "Sling 1d4 "], pick_random_from_list(Weapons); generate_weapon(Type) when Type == medium -&gt; Weapons = ["Battle Axe 1d8 ", "Club 1d4 ", "War Hammer 1d6 ", "Mace 1d6 ", "Staff 1d6 ", "Trident 1d6 ", "Normal Sword 1d8 ", "Whip 1d2 ", "Bow, Short 1d6 ", "Crossbow, Lt 1d6 ", "Throwing Hammer 1d4 ", "Shield, Sword 1d4 +2 "], pick_random_from_list(Weapons); generate_weapon(Type) when Type == primitive -&gt; Weapons = ["Blackjack 1d2 ", "Sling 1d4 ", "Small club 1d2 ", "Staff 1d6 ", "Club 1d4 ", "Stone Mace 1d6 ", "Stone Spear 1d6 "], pick_random_from_list(Weapons); generate_weapon(Type) when Type == large -&gt; Weapons = ["Battle Axe 1d8 ", "Halberd 1d10 ", "Polearm 1d10 ", "Two-Handed Sword 1d10 ", "Normal Sword 1d8 ", "Club 1d4 "], pick_random_from_list(Weapons). pick_random_from_list(List) -&gt; Index = random:uniform(length(List)), lists:nth(Index, List). </code></pre> <p>I welcome review on any aspect of the code. Note that I am a novice with Erlang.</p>
[]
[ { "body": "<p>Erlang does pattern-matching, so anywhere you do</p>\n\n<pre><code>function_name(Arg) -&gt; \n case Arg of foo [foo code]\n bar [bar code]\n etc\n end.\n</code></pre>\n\n<p>or similar, you can instead do</p>\n\n<pre><code>function_name(foo) -&gt; [foo code];\nfunction_name(bar) -&gt; [bar code];\netc.\n</code></pre>\n\n<p>This works for any data type, so you can apply it to each of your functions; </p>\n\n<pre><code>monster(\"Bugbear\", Number) -&gt; ...\n\ngenerate_treasure(p) -&gt; ...\n\ngenerate_weapon(small) -&gt; ...\n</code></pre>\n\n<hr>\n\n<p>A good fit for RPG stat blocks would be Erlang's <a href=\"http://www.erlang.org/doc/reference_manual/records.html\" rel=\"nofollow\">records</a>. <a href=\"http://www.erlang.org/doc/man/ets.html\" rel=\"nofollow\">ETS</a>/<a href=\"http://www.erlang.org/doc/man/dets.html\" rel=\"nofollow\">DETS</a>/<a href=\"http://www.erlang.org/doc/apps/mnesia/users_guide.html\" rel=\"nofollow\">Mnesia</a> seems like a much better way in general to keep this data around than writing it all out in code. Specifically, you could store weapons as</p>\n\n<pre><code>-record(weapon, {name, damage}).\n</code></pre>\n\n<p>and monsters as</p>\n\n<pre><code>-record(monster, {name, ac, hit_dice, hp_mod, attacks, weapon_type, damage, save, type, morale, treasure_type, xp}).\n</code></pre>\n\n<hr>\n\n<p>Your monster two-liners are all very similar. You can probably abstract that out into a separate function, especially if you go the data route as I've suggested. </p>\n\n<p>Something like </p>\n\n<pre><code>print_monster(#monster{name=Name, ac=AC, hit_dice=Hit, hp_mod=Mod, type=Type,\n attacks=Attacks, weapon_type=Weap, damage=Damage, \n save=Save, morale=Morale, treasure_type=T, xp=XP}, \n Number) -&gt;\n io:format(\"~s(~p), AC ~s, HD ~s~s, HP ~p, Att ~s, Dmg ~s ~n\",\n [Name, AC, Hit, Mod, [monster_hp(Hit, Mod) || _ &lt;- lists:seq(1, Number)], Attacks, \n [monsterWeapons:generate_weapon(Weap) || _ &lt;- lists:seq(1, Number)]]),\n io:format(\"Save ~s ~a, Morale ~s, Treasure (~s), XP ~s ~n\",\n [Save, Type, Morale, lists:map(monsterTreasures:generate_treasure/1, T)]).\n</code></pre>\n\n<hr>\n\n<p>You can pass a literal list to <code>pick_random_from_list</code>, so your <code>generate_weapon</code> clauses can be significantly simplified;</p>\n\n<pre><code>generate_weapon(small) -&gt; \n pick_random_from_list([\"Hand Axe 1d6 \", \"Blackjack 1d2 \", \"Torch 1d4 \",\n \"Dagger 1d4 \", \"Short Sword 1d6 \", \"Small club 1d2 \", \n \"Sling 1d4 \"]);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T03:55:04.510", "Id": "11388", "ParentId": "11386", "Score": "1" } } ]
{ "AcceptedAnswerId": "11388", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T02:12:02.863", "Id": "11386", "Score": "1", "Tags": [ "erlang" ], "Title": "Erlang code that generates text output" }
11386
<p>How can I make this piece of code better? The problem to be solved is in the topmost comment.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;cassert&gt; #include &lt;stdint.h&gt; #include &lt;iterator&gt; #include &lt;queue&gt; /* * Shuttle Puzzle: * A Shuttle Puzzle of size 4 consists of 4 white marbles, 4 black marbles, and a strip of * wood with 9 holes (as shown below). The marbles of the same color are placed in the * holes at the opposite ends of the strip leaving the center hole empty. The object of the * puzzle is to completely reverse the marbles on the strip. In general, a shuttle puzzle of * size N consists of N white marbles, N black marbles and 2N+1 holes. There are only * two permissible types of moves. You may slide 1 marble 1 space (into an empty hole) * or jump 1 marble over 1 mar * * W W W W O B B B B */ //-------------------------------------------------------------------------------// //Definition class shuttle_puzzle { private : /* Private member variables and typedefs */ typedef std::vector&lt;char&gt; board; board _game_board; uint32_t _N; enum SwapCase { LeftSkip = -2, ImmediateLeft = -1, Invalid = 0, ImmediateRight = 1, RightSkip = 2 }; bool _problem_solved; std::queue&lt;board&gt; _solutions; /* Private Methods */ void has_left_swap_move(uint32_t open_loc, SwapCase* cases, board &amp;check_board); void has_right_swap_move(uint32_t open_loc, SwapCase* cases, board &amp;check_board); bool solved(uint32_t open_loc, board &amp;check_board); board swap_marbles(uint32_t open_location, SwapCase curr_case, board modify_board); public : /* ctor */ shuttle_puzzle(uint32_t N); /* Method that solves the problem above */ void solve(uint32_t empty_location, board curr_game_board); /* getter */ const board &amp;get_game_board() const { return _game_board; } uint32_t get_start_open_loc() const { return _N; } const std::queue&lt;board&gt; &amp;get_solutions() const { return _solutions; } }; //shuttle_puzzle //-------------------------------------------------------------------------------// //Implmentation /* * ctor * Build the table with N Ws on the left and N Bs on the * right, and a O representing the empty location in the middle. * N Specifies the number of white marbles or black marbles. */ shuttle_puzzle::shuttle_puzzle(uint32_t N) : _N(N), _problem_solved(false) { try { _game_board.resize(2*N + 1); } catch (std::bad_alloc ba) { throw ba; } uint32_t left = 0; uint32_t right = _game_board.size() - 1; for (; left != right; ++left, --right) { _game_board[left] = 'W'; _game_board[right] = 'B'; } _game_board[left] = 'O'; assert(left == right &amp;&amp; _game_board[left] == 'O' &amp;&amp; _game_board[right] == 'O'); } /* * The approach to this problem uses the fact that one step towards the solution * is a binary choice of swapping to the left or to the right. As in the tree below * * W O B * / \ * O W B W B O * * Using back tracking if a path down the tree will not lead to a solution */ void shuttle_puzzle::solve(uint32_t empty_location, board curr_game_board) { /* * Once we have found a solution mark problem as solved for this object */ if (solved(empty_location, curr_game_board)) { _solutions.push(curr_game_board); _problem_solved = true; return; } SwapCase left_cases[2] = {Invalid, Invalid}; SwapCase right_cases[2] = {Invalid, Invalid}; has_left_swap_move(empty_location, left_cases, curr_game_board); has_right_swap_move(empty_location, right_cases, curr_game_board); /* * If you can swap a white marble into the empty location (left_cases[0]) or if you can * hop a black with a white into an empty location (left_cases[1]) */ if (left_cases[0] || left_cases[1]) { SwapCase left_swap_case = ((left_cases[0]) ? left_cases[0] : left_cases[1]); // -1 or -2 will be results // swap marble at -1 or -2 from empty location with the empty location board game_board_swap_left = swap_marbles(empty_location, left_swap_case, curr_game_board); _solutions.push(curr_game_board); if (!_problem_solved) { solve(empty_location + left_swap_case, game_board_swap_left); } if (!_problem_solved) { _solutions.pop(); } } /* * If you can swap a black marble into the empty location (right_cases[0]) or if you can * hop a white with a black into an empty location (right_cases[1]) */ if (right_cases[0] || right_cases[1]) { SwapCase right_swap_case = ((right_cases[0]) ? right_cases[0] : right_cases[1]); // 1 or 2 will be results // swap marble at 1 or 2 from empty location with the empty location board game_board_swap_right = swap_marbles(empty_location, right_swap_case, curr_game_board); _solutions.push(curr_game_board); if (!_problem_solved) { solve(empty_location + right_swap_case, game_board_swap_right); } if (!_problem_solved) { _solutions.pop(); } } } /* * This method will tell you which swap is valid to the left of the open * spot on the board. The cases are depeicted below * * W O B -- Immediate Left Move * W B O -- Left Skip * O W W B B -- Invalid */ void shuttle_puzzle::has_left_swap_move(uint32_t open_loc, SwapCase *cases, board &amp;check_board) { /* * If piece to left is black or piece to left * is white and the piece to the left of that is * black. Make sure to check that you are within * bounds */ if (static_cast&lt;int&gt;(open_loc) - 1 &lt; 0) { cases[0] = Invalid; cases[1] = Invalid; } else if (static_cast&lt;int&gt;(open_loc) - 2 &gt;= 0) { if (check_board[open_loc - 1] == 'W') { cases[0] = ImmediateLeft; cases[1] = Invalid; } else if (check_board[open_loc - 1] == 'B' &amp;&amp; check_board[open_loc - 2] == 'W') { cases[0] = Invalid; cases[1] = LeftSkip; } } else if (static_cast&lt;int&gt;(open_loc) - 1 &gt;= 0 &amp;&amp; check_board[open_loc - 1] == 'W') { cases[0] = ImmediateLeft; cases[1] = Invalid; } else { cases[0] = Invalid; cases[1] = Invalid; } } /* * This method will tell you which swap is valid to the right of the open * spot on the board. The cases are depeicted below * * W O B -- Immediate Right Move * O W B -- Right Skip * W W B B O -- Invalid */ void shuttle_puzzle::has_right_swap_move(uint32_t open_loc, SwapCase *cases, board &amp;check_board) { /* * If piece to right is white or piece to right * is black and the piece to the right of that is * white. Make sure to check that you are within * bounds */ if (open_loc + 1 &gt;= check_board.size()) { cases[0] = Invalid; cases[1] = Invalid; } else if (open_loc + 2 &lt; check_board.size()) { if (check_board[open_loc + 1] == 'B') { cases[0] = ImmediateRight; cases[1] = Invalid; } else if (check_board[open_loc + 1] == 'W' &amp;&amp; check_board[open_loc + 2] == 'B') { cases[0] = Invalid; cases[1] = RightSkip; } } else if (open_loc + 1 &lt; check_board.size() &amp;&amp; check_board[open_loc + 1] == 'B') { cases[0] = ImmediateRight; cases[1] = Invalid; } else { cases[0] = Invalid; cases[1] = Invalid; } } /* * A puzzle is solved if the open location is in the middle * of the board and if all the white marbles are on the right * and all the black marbles are on the left */ bool shuttle_puzzle::solved(uint32_t open_loc, board &amp;check_board) { uint32_t middle = (check_board.size()/2); if (open_loc != middle) { return false; } for (int i = 0, j = check_board.size() - 1; i != j; ++i, --j) { if (check_board[i] == 'W' || check_board[j] == 'B') { return false; } } return true; } /* * We cannot modify the original board, so we must return a copy * of the modified board. So we obtain a copy of the board. Modify * the copy, and return it to the caller for further processing */ shuttle_puzzle::board shuttle_puzzle::swap_marbles(uint32_t open_location, SwapCase curr_case, board modify_board) { board ret = modify_board; char tmp = ret[open_location]; ret[open_location] = ret[open_location + curr_case]; ret[open_location + curr_case] = tmp; return ret; } int main(int argc, char *argv[]) { shuttle_puzzle sp(1); sp.solve(sp.get_start_open_loc(), sp.get_game_board()); std::queue&lt;std::vector&lt;char&gt; &gt; sol = sp.get_solutions(); for (;!sol.empty();) { std::copy(sol.front().begin(), sol.front().end(), std::ostreambuf_iterator&lt;char&gt;(std::cout)); std::cout &lt;&lt; std::endl; sol.pop(); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T08:17:25.563", "Id": "18270", "Score": "2", "body": "Note that `_N` is illegal. See [what are the rules about using an underscore](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797) Using '_' as the first letter in an identifier is not a good idea." } ]
[ { "body": "<p>What's the point of this code? </p>\n\n<pre><code>try {\n _game_board.resize(2*N + 1);\n } catch (std::bad_alloc ba) {\n throw ba;\n }\n</code></pre>\n\n<p>For rethrowing you just do <code>throw</code>, but I see no logic here. If you catch an exception, then process it. If you don't process it, then don't catch it, and let a function at top level do it.</p>\n\n<p>Catch an exception by reference, not by value:</p>\n\n<pre><code>catch (const std::bad_alloc&amp; ba)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T08:34:17.830", "Id": "11394", "ParentId": "11387", "Score": "4" } }, { "body": "<h3>Small Syntax problems</h3>\n\n<p>Since all your other header files are C++, why not make this one C++?</p>\n\n<pre><code>#include &lt;stdint.h&gt;\n\n// Change to \n\n#include &lt;cstdint&gt;\n</code></pre>\n\n<p>Identifiers beginning with <code>_</code> and then a capitol letter is reserved in all scopes.</p>\n\n<pre><code>uint32_t _N;\n</code></pre>\n\n<p>In general it is best to avoid underscore as the first letter of an identifier (as the rules are not obvious (unless you know where to look them up).</p>\n\n<p>Passing pointers as parameters should be avoided:</p>\n\n<pre><code>void has_left_swap_move (uint32_t open_loc, SwapCase* cases, board &amp;check_board);\nvoid has_right_swap_move(uint32_t open_loc, SwapCase* cases, board &amp;check_board);\n // ^^^^^^^^^\n</code></pre>\n\n<p>Why do you need a getter?</p>\n\n<pre><code>const board &amp;get_game_board() const { return _game_board; }\nuint32_t get_start_open_loc() const { return _N; }\nconst std::queue&lt;board&gt; &amp;get_solutions() const { return _solutions; }\n</code></pre>\n\n<p>Methods should manipulate the object not expose the internals.</p>\n\n<p>When you catch an exception you should catch by const reference:</p>\n\n<pre><code>catch (std::bad_alloc const&amp; ba)\n</code></pre>\n\n<p>Otherwise you put yourself in the position of slicing the object on the catch.</p>\n\n<p>Did you really want to pass <code>curr_game_board</code> by value?</p>\n\n<pre><code>void shuttle_puzzle::solve(uint32_t empty_location, board curr_game_board)\n</code></pre>\n\n<h3>Functions:</h3>\n\n<p>The functions:</p>\n\n<pre><code>void shuttle_puzzle::has_left_swap_move(uint32_t open_loc, SwapCase *cases, board &amp;check_board)\nvoid shuttle_puzzle::has_right_swap_move(uint32_t open_loc, SwapCase *cases, board &amp;check_board)\n</code></pre>\n\n<p>Seem to be practically identical. You should be able to refactor into a single function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T08:42:44.157", "Id": "11395", "ParentId": "11387", "Score": "5" } } ]
{ "AcceptedAnswerId": "11395", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T03:13:25.030", "Id": "11387", "Score": "3", "Tags": [ "c++", "algorithm", "programming-challenge" ], "Title": "Shuttle Puzzle solver" }
11387
<p>This code achieves the effect, but is it a resource friendly way of doing it?</p> <p>Just to clarify: target <code>div.fixMe</code> and fix it to the top of the window when the user scrolls past its natural position. (I do realise there are plugins to achieve this result, but I wanted to build it myself)</p> <p>Is this the best way to achieve the desired result? Is it a good idea that the whole function triggers whenever the user scrolls, or should I be splitting up code?</p> <pre><code>(function() { var fixedElement = $('.fixMe').offset(), scrolled = $(window).scroll(function() { var winScrolled = $(this).scrollTop(); if(winScrolled &gt; fixedElement.top - 10) { $('.fixMe').css({'position': 'fixed','top' : '10px'}) } else { $('.fixMe').css({'position': 'static'}) } }); })() </code></pre> <p>Any feedback/criticism is welcome. I should probably get/set the width of <code>div.fixMe</code> to avoid display issues.</p>
[]
[ { "body": "<p>Two things I noticed/would recommend:</p>\n\n<ol>\n<li>Cache jQuery variables such as $(this) and $('.fixMe') to prevent redundant lookups during each scroll event.</li>\n<li>Implement an event debouncer/limiter, this is because the scroll event fires a lot more than you likely think it does. There are many utils/plugins to achieve this such as:\n<ul>\n<li><a href=\"https://github.com/cowboy/jquery-throttle-debounce\" rel=\"nofollow\">https://github.com/cowboy/jquery-throttle-debounce</a></li>\n<li><a href=\"http://unscriptable.com/2009/03/20/debouncing-javascript-methods/\" rel=\"nofollow\">http://unscriptable.com/2009/03/20/debouncing-javascript-methods/</a></li>\n<li><a href=\"http://documentcloud.github.com/underscore/\" rel=\"nofollow\">http://documentcloud.github.com/underscore/</a></li>\n</ul></li>\n</ol>\n\n<p>I even wrote a very simple one: <a href=\"http://limit.gotsomething.com/\" rel=\"nofollow\">http://limit.gotsomething.com/</a>. My site will show you why debouncing/limiting is useful.</p>\n\n<p>Other than that looks good to me!</p>\n\n<p>cheers,\nMarc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T12:59:55.213", "Id": "18290", "Score": "0", "body": "Thanks Marc. While only recently making a concerted effort to learn JQuery I was conscious of many events firing. However if a project is of this scale, do I need to worry about this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T15:08:32.680", "Id": "18293", "Score": "0", "body": "In reality your code does so little that there isn't a great need to deal with these performance enhancements. Just keep them in mind when you are triggering events or functions a lot and when the result if large iterations or heavy DOM manipulation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T15:54:22.077", "Id": "18294", "Score": "0", "body": "Caching `$('.fixme')` outside of the scroll event will be noticeable on IE at least. In IE7 on a decent sized page I think you might have trouble even scrolling the page by doing that lookup in the scroll event." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T12:17:10.990", "Id": "11401", "ParentId": "11397", "Score": "3" } }, { "body": "<p>Here is my code for this:</p>\n\n<p>clone <code>&lt;div&gt;</code> element when original element reach the top of window on page-scroll.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function divFloater(div){\n var win = $(window);\n var divTop = div.offset().top;\n var divLeft = div.offset().left;\n\n win.scroll(function(){ \n var has_fixed = div.children('div').hasClass('fixed');\n var winTop = win.scrollTop();\n if ((winTop &gt; divTop) &amp;&amp; !has_fixed){ \n div.clone().appendTo(div).addClass(\"fixed\");\n $('.fixed').css({'left':divLeft+'px'}).fadeIn();\n } else if ((winTop &lt;= divTop)){\n $('.fixed').fadeOut();\n div.children('.fixed').remove();\n }\n// console.log(winTop+'|'+divTop'|'+has_fixed+);\n }); \n};\n\n$(document).ready(function(){\n var floating_div=$('.view-aktualis-palyazatok').children('.view-header');\n divFloater(floating_div);\n});\n</code></pre>\n\n<p>CSS code for this\n</p>\n\n<pre><code>.view-header {\n position:relative;\n}\n.view-header.fixed {\n position:fixed;\n display:none;\n top: 0;\n}\n</code></pre>\n\n<p>sandbox: <a href=\"http://jsfiddle.net/eapo/Djf3E/1/\" rel=\"nofollow\">http://jsfiddle.net/eapo/Djf3E/1/</a></p>\n\n<p>Please feel free to catch bugs, and advices are welcome.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-27T00:03:48.963", "Id": "23194", "ParentId": "11397", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T09:06:43.427", "Id": "11397", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Fix element on window scroll" }
11397
<p>Hope that title makes sense. This is part of an object I have:<br> The event listener attaches to the correct marker passed in the parameter but inside the function, <code>this</code> points to something else.</p> <pre><code>function UserGoogleMap($mapElement) { this.$mapElement = $mapElement; this.map = {}; this.marker = null; this.coords = new google.maps.LatLng(25.2697, 55.3095) this.initMap = function () { google.maps.event.addListener(this.marker, 'dragend', function() { console.log(this.marker); // Undefined pos = this.marker.getPosition(); $('#google-map-info').html("Latitude:" + pos.lat() + " Longitude: " + pos.lng()); }); } </code></pre> <p>This works with a local variable:</p> <pre><code> var marker = this.marker; google.maps.event.addListener(marker, 'dragend', function() { pos = marker.getPosition(); $('#google-map-info').html("Latitude:" + pos.lat() + " Longitude: " + pos.lng()); }); this.initMap(); } </code></pre> <p>Is there anyway to rewrite this to use <code>this.marker?</code> or am I stuck with creating a local variable to refer to it? Also is there a way to have <code>this.initMap()</code> execute automatically instead of having to add <code>this.initMap();</code> at the end of the class?</p> <p>Any other feedback would be appreciated.</p>
[]
[ { "body": "<p>There's nothing too elegant to be done here, just use</p>\n\n<pre><code>var that = this;\n</code></pre>\n\n<p>And inside your functions, use <code>that</code>.</p>\n\n<p>As in:</p>\n\n<pre><code>function UserGoogleMap($mapElement) {\n this.$mapElement = $mapElement;\n this.map = {};\n this.marker = null;\n this.coords = new google.maps.LatLng(25.2697, 55.3095) \n\n var that = this;\n this.initMap = function () {\n google.maps.event.addListener(that.marker, 'dragend', function() {\n console.log(that.marker); // not Undefined anymore! ;-)\n pos = that.marker.getPosition();\n $('#google-map-info').html(\"Latitude:\" + pos.lat() + \" Longitude: \" + pos.lng());\n });\n }\n}\n</code></pre>\n\n<p>As for the <code>this.initMap();</code> part, AFAIK since JavaScript's class concept are not really classes but functions, you'll have to manually call it or really make a construct that'll call it like this:\n<a href=\"https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript#The_Constructor\" rel=\"nofollow\">https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript#The_Constructor</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T12:48:03.917", "Id": "18287", "Score": "0", "body": "Just realized this after submitting the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T12:49:05.407", "Id": "18288", "Score": "0", "body": "Hehe happens all the time, np :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T12:43:51.390", "Id": "11403", "ParentId": "11402", "Score": "2" } }, { "body": "<p>The \"that\" solution works well, but you can also bind your function to this :</p>\n\n<pre><code>function UserGoogleMap($mapElement) {\n this.$mapElement = $mapElement;\n this.map = {};\n this.marker = null;\n this.coords = new google.maps.LatLng(25.2697, 55.3095) \n\n this.initMap = function () {\n google.maps.event.addListener(this.marker, 'dragend', function() {\n console.log(this.marker);\n pos = this.marker.getPosition();\n $('#google-map-info').html(\"Latitude:\" + pos.lat() + \" Longitude: \" + pos.lng());\n }.bind(this));\n }\n}\n</code></pre>\n\n<p>There is a way to execute initMap directly :</p>\n\n<pre><code>this.initMap = function () {\n google.maps.event.addListener(this.marker, 'dragend', function() {\n pos = this.marker.getPosition();\n $('#google-map-info').html(\"Latitude:\" + pos.lat() + \" Longitude: \" + pos.lng());\n }.bind(this));\n return arguments.callee;\n }();\n</code></pre>\n\n<p>But arguments.callee is deprecated (due to performance issues), so calling initMap manually is better.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-15T10:33:07.237", "Id": "47217", "ParentId": "11402", "Score": "3" } } ]
{ "AcceptedAnswerId": "11403", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T12:34:22.103", "Id": "11402", "Score": "1", "Tags": [ "javascript", "object-oriented" ], "Title": "Trying to use \"this\" to refer to a class's instance variable inside a function within the class's method in JavaScript" }
11402
<p>Here's a program I wrote to sort a list of numbers in increasing order (without using inbuilt sort function).</p> <pre><code>(define (sort-list l) (define first-element (if (not (null? l)) (car l) 0)) (cond ((null? l) (quote ())) (else (cons (find-shortest l first-element) (sort-list (remove-member l (find-shortest l first-element))))))) (define find-shortest (lambda (tl b) (cond ((null? tl) b) ((&lt; (car tl) b) (set! b (car tl)) (find-shortest (cdr tl) b)) (else (find-shortest (cdr tl) b))))) (define remove-member (lambda (tl2 a) (cond ((null? tl2) (quote ())) ((= a (car tl2)) (cdr tl2)) (else (cons (car tl2) (remove-member (cdr tl2) a)))))) </code></pre> <p>It works, but I know it's very badly written. It has way too many recursions than what's necessary. Can someone suggest ways to make this code better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T03:03:26.823", "Id": "18285", "Score": "0", "body": "I think that `find-shortest` should be named `find-smallest`." } ]
[ { "body": "<p>What you've written is called \"selection sort\", and it works fine. It's not the best sort, but it's not bad, either. It's one of a class called \"n^2\" sorts, because it generally runs in time proportional to the square of the length of the list.</p>\n\n<p>Selection sort is a somewhat painful sort to write in a recursive style, because removing an element from a list is not so natural. </p>\n\n<p>You can make it look a smidgen more natural if you rebuild the list on the way back out after removing it. However, the second pass over the list (as you've written it) does <em>not</em> change the asymptotic running time; it's still \"order n-squared\".</p>\n\n<p>One note: you gain nothing by mutating \"b\" in the body of \"find-shortest.\" Instead, replace</p>\n\n<pre><code>(set! b (car tl)) (find-shortest (cdr tl) b)\n</code></pre>\n\n<p>with</p>\n\n<pre><code>(find-shortest (cdr tl) (car tl))\n</code></pre>\n\n<p>... to make your code shorter and cleaner.</p>\n\n<p>Also, If you were in my class, I would ask you for purpose statements and test cases. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T04:11:59.553", "Id": "18286", "Score": "1", "body": "`O(n^2)` is pretty bad for sorting..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T12:49:56.427", "Id": "18289", "Score": "0", "body": "It's not bad for short collections, even though insertion sort would be better." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T03:40:15.340", "Id": "11405", "ParentId": "11404", "Score": "6" } }, { "body": "<ul>\n<li><p>Within the <code>sort-list</code> function, you can just use <code>(car l)</code> in-place of <code>first-element</code> because your first <code>cond</code> clause ensures that in the remaining clauses, l is not null</p></li>\n<li><p>Also in <code>sort-list</code> You call <code>(find-shortest l first-element)</code> twice. You could bind the result of this call once and save one call into <code>find-shortest</code></p></li>\n</ul>\n\n<p>Taking those two points and @Dan D.'s point about renaming <code>find-shortest</code> to <code>find-smallest</code> this is how my <code>sort-list</code> would look</p>\n\n<pre><code>(define (sort-list l)\n (cond ((null? l) '()) ; or (quote ()) - whichever you prefer\n (else (let ((smallest (find-smallest l (car l))))\n (cons smallest\n (sort-list (remove-member l smallest)))))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T20:01:57.433", "Id": "11414", "ParentId": "11404", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T02:59:00.113", "Id": "11404", "Score": "5", "Tags": [ "beginner", "scheme", "sorting" ], "Title": "Sorting a list of numbers in increasing order" }
11404
<p>Here is my implementation of the <a href="http://en.wikipedia.org/wiki/Greedy_algorithm" rel="nofollow">greedy algorithim</a> in Ruby. Do you have any suggestions?</p> <pre><code>class Greedy def initialize(unit, total, *coins) @total_coins = 0 @unit = unit @total = total @currency = coins.sort @currency = @currency.reverse unless @currency.include?(1) @currency.push(1) end end def sort_coins @currency.each do |x| @pos = @total / x @pos = @pos.floor @total_coins += @pos @total -= x * @pos puts "#{@pos}: #{x} #{@unit}" end puts "#{@total_coins} total coins" end end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T15:02:33.863", "Id": "18398", "Score": "1", "body": "It is \"a solution using a greedy algorithm\", not \"the Greedy Algorithm\" itself. Greedy algorithm is a concept." } ]
[ { "body": "<p><code>@currency</code> could be renamed <code>@currencies</code>, or perhaps better, <code>@denominations</code>. Naming an array in the plural leads to easy naming when iterating, e.g.:</p>\n\n<pre><code>@currencies.each do |currency|\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>@currency.each do |x|\n</code></pre>\n\n<p>The name of method <code>sort_coins</code> doesn't match what it's doing. Whether or not it's sorting, it's also printing. A better name might be <code>print_coins</code>.</p>\n\n<p><code>@quotient</code> might be a better name for <code>@pos</code>. </p>\n\n<p>Most of the variables in sort_coins do not need to be member variables: <code>@pos</code> and <code>@total_coins</code> should lose the <code>@</code>. And, if you decide to make it an argument to <code>sort_coins</code> (see below), <code>@total</code> as well.</p>\n\n<p>This:</p>\n\n<pre><code>@currency = coins.sort\n@currency = @currency.reverse\n</code></pre>\n\n<p>Could be this:</p>\n\n<pre><code>@currency = coins.sort.reverse\n</code></pre>\n\n<p>The initialization of <code>@total_coins</code> needs to move from the constructor to <code>sort_coins</code>. This prevents a bug triggered by calling <code>sort_coins</code> more than once.</p>\n\n<p>Consider passing <code>total</code> to <code>sort_coins</code> rather than to the constructor. This would allow <code>sort_coins</code> to be called on an instance of <code>Greedy</code> with a different total each time, and no need to create a new instance of <code>Greedy</code> for each. It would also get the variable's initialization closer to where it is used, making for simpler code.</p>\n\n<p>Consider the constructor argument for the set of coins bing simply <code>coins</code> rather than <code>*coins</code>, because it makes the calling code easier to understand. E.g.,</p>\n\n<pre><code>Greedy.new('cents', 71, 1, [5, 10, 25, 50]).sort_coins\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>Greedy.new('cents', 71, 1, 5, 10, 25, 50).sort_coins\n</code></pre>\n\n<p>Put a line of white space between methods, and at the top and bottom of the class definition.</p>\n\n<hr>\n\n<p>If all acted upon, these suggestions yield:</p>\n\n<pre><code>class Greedy\n\n def initialize(unit, coins)\n @unit = unit\n @demoninations = coins.sort.reverse\n unless @demoninations.include?(1)\n @demoninations.push(1)\n end\n end\n\n def print_coins(total)\n total_coins = 0\n @demoninations.each do |demonination|\n quotient = (total / demonination).floor\n total_coins += quotient\n total -= demonination * quotient\n puts \"#{quotient}: #{demonination} #{@unit}\"\n end\n puts \"#{total_coins} total coins\"\n end\n\nend\n\nGreedy.new('cents', [1, 5, 10, 25, 50]).print_coins(72)\n#=&gt; 1: 50 cents\n#=&gt; 0: 25 cents\n#=&gt; 2: 10 cents\n#=&gt; 0: 5 cents\n#=&gt; 2: 1 cents\n#=&gt; 5 total coins\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T14:09:07.820", "Id": "29186", "Score": "0", "body": "Thanks for adding the use of the class and what it will output - it helped me figure out what was going on quickly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:28:55.607", "Id": "11443", "ParentId": "11408", "Score": "4" } } ]
{ "AcceptedAnswerId": "11443", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T15:44:08.483", "Id": "11408", "Score": "3", "Tags": [ "optimization", "ruby" ], "Title": "Greedy algorithm in Ruby - any suggestions?" }
11408
<p>I have written a custom drop down menu handler using jQuery because I felt that the native drop down didn't fit my UI. I have taking into consideration the native way of going through a drop down box using arrows and tabs to move to next input.</p> <p>I was wondering if anyone can see any mistakes or errors or anyway I could improve this.</p> <p><a href="http://jsfiddle.net/tFcQ8/1/" rel="nofollow noreferrer">jsFiddle</a></p> <p>Basic markup for a drop down box:</p> <pre><code>&lt;label&gt; &lt;a class="dropdown button drop white"&gt;&lt;span&gt;Title&lt;/span&gt;&lt;i&gt;&lt;/i&gt;&lt;/a&gt; &lt;ul class="dropmenu"&gt; &lt;li&gt;Mr&lt;/li&gt; &lt;li&gt;Mrs&lt;/li&gt; &lt;li&gt;Ms&lt;/li&gt; &lt;li&gt;Miss&lt;/li&gt; &lt;/ul&gt; &lt;input type="text" class="dropFocuser" /&gt; &lt;/label&gt; </code></pre> <p>jQuery:</p> <pre><code>(function() { var listItems , direction , index=0 , shift='off' , next , method = false; var changeInput = function(drop, next, enter) { var input = drop.parent().siblings('a').find('span'); var newinput = drop.html(); $(input).html(newinput); if(next){ if(enter) { drop.parent().removeClass('show'); drop.parent().parent().next().focus(); } else { method = true; console.log(drop.parent().removeClass('show')); console.log(drop.parent().parent().next().focus()); } } } $('input.dropFocuser').focus(function() { if(method == false) { index = 0; $(this).siblings('ul').addClass('show'); listItems = $(this).siblings('ul').find('li'); } else { method = false; } }); $('ul.dropmenu').find('li').mouseover(function(e){ var that = this; $('li').removeClass('focusList'); $(this).addClass('focusList'); $(listItems).each(function(i) { if($(listItems)[i] == that){ index = i; return false; } }); }); $('ul.dropmenu').find('li').click(function(e) { changeInput($(this), next=true); }) /** * Keep track of the shift keys so that we weither to focus next or prev input element. */ $(document).keydown(function(e){ //if shift key has been pressed down set it to on if(e.keyCode == 16) { shift = 'on'; } }); $(document).keyup(function(e){ //if shift key has been released set it to off if(e.keyCode == 16) { shift = 'off'; } }) $('input.dropFocuser').keydown(function(e) { $('li').removeClass('focusList'); switch (e.keyCode){ case 9: //this checks to see if the shift key is pressed or not and //from there takes appropriate action. if(shift == 'off'){ $(this).siblings('ul').removeClass('show'); console.log($(this).parent().next().focus()); } else { $(this).siblings('ul').removeClass('show'); console.log($(this).parent().prev().focus()); } return false; break; case 13: var current = listItems[index-1]; changeInput($(current), next=true, enter=true); $(current).addClass('focusList'); return false; break; case 40: if(index == listItems.length){ index = 1; $(listItems[0]).addClass('focusList'); changeInput($(listItems[0]), next=false); } else{ index++ } direction = 'down'; break; case 38: if(direction == 'down') { $(listItems[index-2]).addClass('focusList'); changeInput($(listItems[index-2]), next=false); index -= 1; if(index == 0) { $(listItems[listItems.length-1]).addClass('focusList'); changeInput($(listItems[listItems.length-1])); index = listItems.length; } return false; } direction = 'up'; break; default : return false; } changeInput($(listItems[index-1]), next=false); $(listItems[index-1]).addClass('focusList'); }); })(); </code></pre> <p>I have found this code to be unreliable so I did a little bit of digging and I found that I could change the native UI look that works in modern browsers. I have written in a fallback for <p><a href="http://jsfiddle.net/tFcQ8/3/" rel="nofollow noreferrer">Here</a> is the new HTML / CSS only code.</p>
[]
[ { "body": "<p>Just two small notes from a non-JavaScript/jQuery developer:</p>\n\n<ol>\n<li><p>Named constants would be better instead of the magic numbers/strings.</p>\n\n<pre><code>e.keyCode == 16\nshift = 'on';\nshift = 'off';\ncase 13:\ncase 9:\ncase 13:\ncase 40:\ncase 38:\n</code></pre></li>\n<li><p>I'd separate the API calls and logging:</p>\n\n<pre><code>var focusResult = $(this).parent().next().focus();\nconsole.log(focusResult);\n</code></pre>\n\n<p>It's easy to lost the <code>$(this).parent().next().focus()</code> call when somebody accidentally comments out the whole <code>console.log</code> line because he or she does not want the log any more.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T22:09:19.787", "Id": "18306", "Score": "1", "body": "`$(this).parent().next().focus()` will return the `$(this)` object. The variable is poorly named, but the pattern there is method chaining (the log appears to be leftover debug code)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T20:46:40.057", "Id": "11420", "ParentId": "11409", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T16:35:56.080", "Id": "11409", "Score": "3", "Tags": [ "javascript", "jquery", "html", "css", "gui" ], "Title": "Custom dropdown menu using jQuery" }
11409
<p>This is a short program meant to give me an Erlang hook into the ImageMagick FFI for performance reasons. </p> <p>All comments welcome, but specifically </p> <ul> <li>my C experience is minimal, bordering on nonexistent, so I would particularly appreciate hints in that area. </li> <li>the setup here is one of a long-running process that will be accepting many requests, so if you see any memory leaks point them out (for bonus points, try to explain why they're happening in a way that will let me recognize similar situations in the future)</li> </ul> <p>At a high level, what's happening is that the Erlang process is spawning off a new OS process of the C program and grabbing its <code>stdin</code>, <code>stdout</code> and <code>stderr</code> for communication purposes. When a request for thumbnailing comes in, the Erlang process sends its pathname to the C process then waits for one of three responses (<code>ok</code>, <code>could_not_read</code> or <code>could_not_write</code>) encoded as an integer. If successful, an image called "thumbnail.png" is created in the same directory as the incoming file.</p> <p>Erlang part first:</p> <pre class="lang-erlang prettyprint-override"><code>-module(wand). -export([start/0, stop/0, restart/0]). -export([thumbnail/1]). start() -&gt; spawn(fun() -&gt; register(wand, self()), process_flag(trap_exit, true), Port = open_port({spawn, "./wand"}, [{packet, 2}]), loop(Port) end). stop() -&gt; wand ! stop. restart() -&gt; stop(), start(). thumbnail(Filename) -&gt; call_port(Filename). call_port(Msg) -&gt; wand ! {call, self(), Msg}, receive {wand, Result} -&gt; Result end. loop(Port) -&gt; receive {call, Caller, Msg} -&gt; Port ! {self(), {command, Msg}}, receive {Port, {data, Data}} -&gt; Caller ! {wand, decode(Data)} end, loop(Port); stop -&gt; Port ! {self(), close}, receive {Port, closed} -&gt; exit(normal) end; {'EXIT', Port, Reason} -&gt; exit({port_terminated, Reason}) end. decode([0]) -&gt; {ok, 0}; decode([1]) -&gt; {error, could_not_read}; decode([2]) -&gt; {error, could_not_write}. </code></pre> <p>Next, the read/write functions to handle length headers:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;unistd.h&gt; typedef unsigned char byte; int read_cmd(byte *buff); int write_cmd(byte *buff, int len); int read_exact(byte *buff, int len); int write_exact(byte *buff, int len); int read_cmd(byte *buff) { int len; if (read_exact(buff, 2) != 2) { return(-1); } len = (buff[0] &lt;&lt; 8) | buff[1]; return read_exact(buff, len); } int write_cmd(byte *buff, int len) { byte li; li = (len &gt;&gt; 8) &amp; 0xff; write_exact(&amp;li, 1); li = len &amp; 0xff; write_exact(&amp;li, 1); return write_exact(buff, len); } int read_exact(byte *buff, int len){ int i, got=0; do { if ((i = read(0, buff+got, len-got)) &lt;= 0) { return(i); } got +=i; } while (got&lt;len); buff[len] = '\0'; return(len); } int write_exact(byte *buff, int len) { int i, wrote = 0; do { if ((i = write(1, buff+wrote, len-wrote)) &lt;= 0) { return(i); } wrote += i; } while (wrote&lt;len); return(len); } </code></pre> <p>The actual thumbnail generating piece</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;wand/MagickWand.h&gt; #define ThrowWandException(wand, ret) \ { \ char \ *description; \ \ ExceptionType \ severity; \ \ description=MagickGetException(wand,&amp;severity); \ (void) fprintf(stderr,"%s %s %lu %s\n",GetMagickModule(),description); \ description=(char *) MagickRelinquishMemory(description); \ wand=DestroyMagickWand(wand); \ MagickWandTerminus(); \ return ret; \ } int thumbnail (char *image_name, char *thumbnail_name){ MagickWand *magick_wand; MagickBooleanType status; /* Read an image. */ MagickWandGenesis(); magick_wand=NewMagickWand(); status=MagickReadImage(magick_wand, image_name); if (status == MagickFalse) ThrowWandException(magick_wand, 1); /* Turn the images into a thumbnail sequence. */ MagickResetIterator(magick_wand); while (MagickNextImage(magick_wand) != MagickFalse) MagickResizeImage(magick_wand,106,80,LanczosFilter,1.0); /* Write the image then destroy it. */ status=MagickWriteImages(magick_wand, thumbnail_name, MagickTrue); if (status == MagickFalse) ThrowWandException(magick_wand, 2); magick_wand=DestroyMagickWand(magick_wand); MagickWandTerminus(); return 0; } </code></pre> <p>Finally, <code>int main</code> and thumbnail path handling:</p> <pre><code>#include &lt;limits.h&gt; #include &lt;libgen.h&gt; #include &lt;string.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef unsigned char byte; int read_cmd(byte *buff); int write_cmd(byte *buff, int len); char *chop_path(char *orig) { char buf[PATH_MAX + 1]; char *res, *dname, *thumb; res = realpath(orig, buf); if (res) { dname = dirname(res); thumb = strcat(dname, "/thumbnail.png"); return thumb; } return 0; } int main(){ int result, i, len; byte buff[255]; char *thumb; while (read_cmd(buff) &gt; 0) { thumb = chop_path(buff); result = thumbnail(buff, thumb); buff[0] = result; write_cmd(buff, 1); } } </code></pre>
[]
[ { "body": "<p>If you are using several files to implement this, you need a header file to\nhold the prototypes of external functions (<code>read_cmd</code> etc) and types (<code>typedef\nunsigned char byte;</code>)</p>\n\n<p>In <code>read_exact</code> and <code>write_exact</code>, a <code>do .. while</code> loop is inappropriate. A\n<code>for</code> loop would be better.</p>\n\n<pre><code>for (int n, got = 0; got &lt; len; got += n) {\n if ((n = read(0, buff+got, len-got)) &lt;= 0) {\n return n;\n }\n}\n</code></pre>\n\n<p>But I'm wondering about the need for a loop and the use of raw I/O (as opposed\nto buffered). It might be easier to use buffered I/O and treat what is\nexchanged as strings. There would be no need to prepend a size, just send a\nstring terminated by \\n. When using raw I/O, your <code>while</code> loop handles\nthe case when the <code>read</code> call does not read the complete block. Since you are\nnot reading from a file that is correct, but the corollary of that is that you\nshould handle errors returned by <code>read</code>. For example EINTR should probably\nbe handled.</p>\n\n<p>Also is is better to use <code>fileno(stdin)</code>, <code>fileno(stdout)</code> instead of 0 and 1.</p>\n\n<p>In <code>chop_path</code> you have concatenated the filename \"/thumbnail.png\" onto the\ninternal buffer returned by <code>dirname</code>. In doing so you have written to a\nbuffer that should be considered <code>const</code> - you can't be sure there is space at\nthe end of the string. Also you return 0 from <code>chop_path</code> on error but\n<code>main</code> does not check for this. </p>\n\n<p>On programming style, it is normally best to define variables at the point of\nfirst use, where possible. Also, variables should be defined one per line.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T23:32:18.763", "Id": "36474", "ParentId": "11411", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T17:12:29.727", "Id": "11411", "Score": "2", "Tags": [ "c", "erlang" ], "Title": "Erlang FFI into ImageMagick" }
11411
<p>The reason I want to do this is that the JavaScript objects are created from XML elements and if the element has changed I want to be able to detect that change in the JavaScript objects. So I wrote a function which maps out the differences between the first and second object. Can you improve on this function? (<code>mapObjectDifferences</code>, not the helper functions.)</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;MAP OBJECT DIFFERENCES&lt;/title&gt; &lt;script type="text/javascript"&gt; function isArray(object) { return Object.prototype.toString.apply(object) == "[object Array]"; } function getType(variable) { var type = typeof variable; if (type == "object") if (isArray(variable)) return "array"; return type; } function arrayToObject(array) { var object = {}; for (var i = 0; i &lt; array.length; ++i) if (array[i] !== "undefined") object[i] = array[i]; return object; } function mapObjectDifferences(outerObject, innerObject) { var _mapObjectDifferences = function (outerObject, innerObject, parentMap, parentName) { var localMap = {}; for (var outerProp in outerObject) { if (outerObject.hasOwnProperty(outerProp)) { var match = false; var outerPropValue = outerObject[outerProp]; var outerType = getType(outerPropValue); var result; for (var innerProp in innerObject) { if (innerObject.hasOwnProperty(innerProp)) { var innerPropValue = innerObject[innerProp]; var innerType = getType(innerPropValue); if (outerProp == innerProp &amp;&amp; outerType == innerType) { match = true; if (outerType == "array" || outerType == "object") { if (outerType == "array") { outerPropValue = arrayToObject(outerPropValue); innerPropValue = arrayToObject(innerPropValue); } _mapObjectDifferences(outerPropValue, innerPropValue, localMap, outerProp); } break; } } } if (match == false) { localMap[outerProp] = outerType; if (parentMap) parentMap[parentName] = localMap; } else if (parentMap) { var difChild = false; for (var prop in localMap) if (localMap.hasOwnProperty(prop)) { difChild = true; break; } if (difChild == true) parentMap[parentName] = localMap; } } } return localMap; } return _mapObjectDifferences(outerObject, innerObject); } var o1 = { val: "level one", val2: 1, val3: 3, m: { s2: "this is level two", l1: ["a", "b", "c", 1, {a:"a"}], ao: [{ x: "1" }, { y: 1 }, { z: 1}] }, n: { n1: { abc: 123 } } }; var o2 = { val: "level on23e", val2: 1, m: { s3: "this is level two", l1: ["a", "b", "c"], ao: [{ x: 1 }, { y: 1 }, { z: "3"}] }, n: { n1: { abc: "abc" } } } var result = mapObjectDifferences(o1, o2); debugger; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T18:08:46.007", "Id": "18325", "Score": "0", "body": "You can simply use the jQuery `extends` function...(If jQuery is an option)" } ]
[ { "body": "<p>Replacing conditions with guard clauses would improve readability a little bit. (<a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Flattening Arrow Code</a>)</p>\n\n<p>I would try to build two maps first - one for properties of the first object, and one for the other - then compare the two maps. The key of the map could be the name of the property (in the <code>parentProperty.childProperty</code> format if a property is an other object). The value could be the type of the property.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T21:41:15.303", "Id": "11454", "ParentId": "11412", "Score": "1" } }, { "body": "<p>I was going to post this as a comment to <a href=\"https://codereview.stackexchange.com/questions/11412/how-can-you-map-the-differences-between-javascript-objects#11454\">palacsint's answer</a> but it helps to have code blocks.</p>\n\n<p>Because you're using this pattern in several places:</p>\n\n<pre><code>for (var prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n ...\n }\n}\n</code></pre>\n\n<p>One way you can reduce the depth of the \"arrowing\" is to extract that out into its own function:</p>\n\n<pre><code>function iterateMap(obj, fn, scope) {\n for(prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n fn.call(scope || this, prop);\n }\n }\n}\n\n...\n\niterateMap(obj, function(prop) {\n ...\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T21:11:28.733", "Id": "32582", "Score": "0", "body": "@palacsint: Oops, sorry! I've always wondered, what does your username mean?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T22:19:10.673", "Id": "32599", "Score": "1", "body": "Np :) It comes from 'palacsinta' (which means 'pancake' in Hungarian) without the last letter, since IRCnet allows (or allowed a couple of years ago) only nine characters in the nickname." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T22:05:40.230", "Id": "11460", "ParentId": "11412", "Score": "2" } }, { "body": "<p>The existing suggestions are good for trimming down your current code, but, as always, the most important thing to optimize is the algorithm itself. I took a crack at your problem, as I understand it, and here's the result:</p>\n\n<pre><code>function difference(o1, o2) {\n var k, kDiff,\n diff = {};\n for (k in o1) {\n if (!o1.hasOwnProperty(k)) {\n } else if (typeof o1[k] != 'object' || typeof o2[k] != 'object') {\n if (!(k in o2) || o1[k] !== o2[k]) {\n diff[k] = o2[k];\n }\n } else if (kDiff = difference(o1[k], o2[k])) {\n diff[k] = kDiff;\n }\n }\n for (k in o2) {\n if (o2.hasOwnProperty(k) &amp;&amp; !(k in o1)) {\n diff[k] = o2[k];\n }\n }\n for (k in diff) {\n if (diff.hasOwnProperty(k)) {\n return diff;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>Note that I didn't try to mimic your code exactly:</p>\n\n<ul>\n<li>Arrays are compared thoroughly, not just on numbered properties.</li>\n<li>Difference map contains new values themselves, not their types.</li>\n<li>If there are no differences then the function returns <code>false</code>, not <code>{}</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T03:40:16.220", "Id": "11580", "ParentId": "11412", "Score": "7" } }, { "body": "<p>There's a library that might help you: <a href=\"https://github.com/flitbit/diff\" rel=\"nofollow\">https://github.com/flitbit/diff</a></p>\n\n<p>Given an origin object, and another object, it'll spit out an array of differences between one and the other. Example from their docs:</p>\n\n<pre><code>var lhs = {\n name: 'my object',\n description: 'it\\'s an object!',\n details: {\n it: 'has',\n an: 'array',\n with: ['a', 'few', 'elements']\n }\n};\n\nvar rhs = {\n name: 'updated object',\n description: 'it\\'s an object!',\n details: {\n it: 'has',\n an: 'array',\n with: ['a', 'few', 'more', 'elements', { than: 'before' }]\n }\n};\n\nvar differences = diff(lhs, rhs);\n</code></pre>\n\n<p>Results in <code>differences</code> being:</p>\n\n<pre><code>[ { kind: 'E',\n path: [ 'name' ],\n lhs: 'my object',\n rhs: 'updated object' },\n { kind: 'E',\n path: [ 'details', 'with', 2 ],\n lhs: 'elements',\n rhs: 'more' },\n { kind: 'A',\n path: [ 'details', 'with' ],\n index: 3,\n item: { kind: 'N', rhs: 'elements' } },\n { kind: 'A',\n path: [ 'details', 'with' ],\n index: 4,\n item: { kind: 'N', rhs: { than: 'before' } } } ]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-02T01:00:28.907", "Id": "95517", "ParentId": "11412", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T18:39:42.010", "Id": "11412", "Score": "8", "Tags": [ "javascript", "algorithm", "xml" ], "Title": "Mapping the differences between JavaScript objects" }
11412
<p>How can I make these methods better?</p> <pre><code>Range.class_eval do def addto_begin(x) return self.begin + x..self.end end def addto_end(x) return self.begin..self.end+x end end </code></pre> <p>Right now, I have to type:</p> <pre><code>x = 1..10 x = x.addto_begin(3) </code></pre> <p>to change the begin of the range. What I want to be able to do is:</p> <pre><code>x = 1..10 x.addto_begin(3) </code></pre> <p>How do I do this?</p>
[]
[ { "body": "<p>You can't. <code>Range</code> doesn't provide write access to properties (i.e. begin/end).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T15:06:45.947", "Id": "11416", "ParentId": "11415", "Score": "1" } }, { "body": "<p>Since ranges are immutable you would need to create your own range class that encapsulates the basic range object. This class will give you that and still keep and the methods associated with the basic range object.</p>\n\n<pre><code>class Myrange\n attr_accessor :range\n def initialize(a,b=nil,exc=false)\n if a.is_a? Range\n @range = a\n else\n @range = Range.new(a,b,exc)\n end\n end\n def addto_begin(x)\n Myrange.new(@range.begin + x..@range.end)\n end\n def addto_end(x)\n Myrange.new(@range.begin..@range.end+x)\n end\n def addto_begin!(x)\n @range = @range.begin + x..@range.end\n Myrange.new(@range)\n end\n def addto_end!(x)\n @range = @range.begin..@range.end+x\n Myrange.new(@range)\n end\n def to_s\n @range.to_s\n end\n def inspect\n self.to_s\n end\n def method_missing(*args,&amp;blk)\n @range.send(*args,&amp;blk)\n end\nend\n\nx = Myrange.new(1,10)\nx = x.addto_begin(3)\np x #=&gt; 4..10\ny = x.addto_begin!(3)\np x #=&gt; 7..10\np y.addto_end(3) #=&gt; 7..13\np x.include? 9 #=&gt; true :: Range methods still work\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T17:22:19.840", "Id": "11417", "ParentId": "11415", "Score": "3" } } ]
{ "AcceptedAnswerId": "11417", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T14:57:16.627", "Id": "11415", "Score": "2", "Tags": [ "ruby" ], "Title": "How to make a mutable Range in Ruby?" }
11415
<p>I wanted to download a webpage. I confirmed that this code works. But I'm not sure whether I'm doing it neatly. Would you review my (full) code?</p> <pre><code>import java.io.IOException; import java.io.InputStream; import java.io.FileOutputStream; import java.net.URL; public class GetHTML { private InputStream in; private FileOutputStream out; private String articleName; public void setArticleName(String articleName) { this.articleName = articleName; } public void download(URL url) throws IOException { in = url.openStream(); out = new FileOutputStream(articleName + ".html"); byte[] arr = new byte[1024]; while(true) { int count = in.read(arr); if(count == -1) { break; } out.write(arr, 0, count); } in.close(); out.close(); } public static void main(String[] args) throws IOException { String site1 = "http://codereview.stackexchange.com/questions/"; String site2 = "69"; String site3 = "is-this-implementation-of-shamos-hoey-algorithm-ok"; URL url = new URL(site1 + site2 + "/" + site3); GetHTML getHTML = new GetHTML(); getHTML.setArticleName("[" + site2 + "]" + site3); getHTML.download(url); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T20:56:21.263", "Id": "18303", "Score": "0", "body": "1. Can you use automatic resource management? http://stackoverflow.com/questions/2943542/using-keyword-in-java 2. Pass the article name directly to the constructor. 3. Take the url from command line. 4. Keep it simple - e.g. every method could have been static." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T08:23:47.107", "Id": "18451", "Score": "0", "body": "I think I will not be able to take the url directly from command line because actually I have a bunch of url's. :( This is just a small program, and I hope to grow this program into a giant which will be able to handle thousands of url's automatically! :)" } ]
[ { "body": "<ol>\n<li><p>From Clean Code, page 25: </p>\n\n<blockquote>\n <p>Classes and objects should have noun or noun phrase names like <code>Customer</code>, <code>WikiPage</code>,\n <code>Account</code>, and <code>AddressParser</code>. [...] A class name should not be a verb.</p>\n</blockquote>\n\n<p>I'd simply name it <code>ArticleDownloader</code>, for example.</p></li>\n<li> \n\n<pre><code>private InputStream in;\nprivate FileOutputStream out;\n</code></pre>\n\n<p>These could inside the download method:</p>\n\n<pre><code>public void download(URL url) throws IOException {\n final InputStream in = url.openStream();\n final OutputStream out = new FileOutputStream(articleName + \".html\");\n</code></pre>\n\n<p>Reference: <em>Effective Java, 2nd edition, Item 45: Minimize the scope of local variables</em></p></li>\n<li><p>The <code>FileOutputStream out</code> could be just <code>OutputStream</code> type. (<em>Effective Java, 2nd edition, Item 52: Refer to objects by their interfaces</em>)</p></li>\n<li><p>Commons IO has a method which does the copying: <a href=\"http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#copy%28java.io.InputStream,%20java.io.OutputStream%29\"><code>IOUtils.copy(InputStream input, OutputStream output) throws IOException</code></a>. (<em>Effective Java, 2nd edition, Item 47: Know and use the libraries</em>)</p></li>\n<li><p>I'd remove the <code>setArticleName</code> method and the <code>articleName</code> field (since there is no other method which uses this field) and pass it directly to the <code>download</code> method:</p>\n\n<pre><code>public void download(URL url, final String articleName) throws IOException {...}\n</code></pre></li>\n<li><p>I'd move the <code>main</code> method to a separate class. (For example, <code>DownloaderMain</code>.) It's usually a good idea to separate a class from its clients.</p></li>\n<li><p>Close the streams in a <code>finally</code> block. (<em>Effective Java, 2nd edition, Item 7: Avoid finalizers</em>)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T21:08:35.177", "Id": "11421", "ParentId": "11418", "Score": "15" } } ]
{ "AcceptedAnswerId": "11421", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T20:35:19.490", "Id": "11418", "Score": "10", "Tags": [ "java", "html" ], "Title": "Webpage downloader" }
11418
<p>So far, this is just a class that tracks the state of a baseball game. Unfortunately, I can't tell you for sure what the next step is. It might be a an interactive playable baseball game, or a game simulator, or some combination.</p> <p>I am hoping this class is sufficient to do either of those things. The test class wouldn't fit here. The code is hosted on bitbucket <a href="https://bitbucket.org/jgrigonis/baseball_simulator/overview" rel="nofollow">here</a> as well. I'm looking for feedback from the pythonistas.</p> <pre><code>'''The Game class.''' class Game(object): '''Maintain the state of the game. Includes methods to carry out various game related events. ''' # pylint: disable=R0902 # Ignore error about too many instance attributes. def __init__(self): '''Set up a new game.''' self.count = {"balls": 0, "strikes": 0} self.score = {"home": 0, "away": 0} self.home_batter = 1 self.away_batter = 1 self.inning = {"val": 1, "half": "top"} self.bases = {"first": 0, "second": 0, "third": 0} self.winner = None self.game_over = False self.outs = 0 self.__new_inning() def strike(self): '''Pitcher throws a strike.''' if self.count["strikes"] == 2: self.__strike_out() else: self.count["strikes"] += 1 def ball(self): '''Pitcher throws a ball.''' if self.count["balls"] == 3: self.__walk() else: self.count["balls"] += 1 def foul_ball(self): '''Batter hits a foul.''' if self.count["strikes"] != 2: self.count["strikes"] += 1 def hit_by_pitch(self): "Batter is hit by pitch." self.__walk() def steal(self, base): '''Runner steals a base. base - the base that is stolen (second, third, home) If the base to be stolen is not empty, or the base they are stealing from is not occupied, an error is assumed to have occured, and nothing will happen. ''' if base == "second": if self.bases["first"] != 0 and self.bases["second"] == 0: self.bases["second"] = 1 self.bases["first"] = 0 elif base == "third": if self.bases["second"] != 0 and self.bases["third"] == 0: self.bases["third"] = 1 self.bases["second"] = 0 else: if self.bases["third"] != 0: self.bases["third"] = 0 self.__score_run() def caught_stealing(self, base): '''Runner caught stealing a base. base - the base that is attempted to be stolen (second, third, home) If the base to be stolen is not empty, or the base they are stealing from is not occupied, an error is assumed to have occured, and nothing will happen. ''' if base == "second": if self.bases["first"] != 0 and self.bases["second"] == 0: self.bases["second"] = 0 self.bases["first"] = 0 self.__put_out() elif base == "third": if self.bases["second"] != 0 and self.bases["third"] == 0: self.bases["third"] = 0 self.bases["second"] = 0 self.__put_out() else: if self.bases["third"] != 0: self.bases["third"] = 0 self.__put_out() def picked_off(self, base): '''Runner picked off from a base. base - the base that the runner was on (first, second, third) If the base is empty, an error is assumed to have occured, and nothing will happen. ''' if self.bases[base] != 0: self.bases[base] = 0 self.__put_out() def ground_out(self): '''Batter grounds out.''' self.__next_batter() if self.outs == 2: self.__side_retired() else: self.__put_out() def fly_out(self): '''Batter flies out.''' self.__next_batter() if self.outs == 2: self.__side_retired() else: self.__put_out() def balk(self): '''Pitcher performs a balk.''' if self.bases["third"] != 0: self.__score_run() self.bases["third"] = 0 if self.bases["second"] != 0: self.bases["second"] = 0 self.bases["third"] = 1 if self.bases["first"] != 0: self.bases["first"] = 0 self.bases["second"] = 1 def base_hit(self, hit_type="single", first_to_third=False, first_to_home=False, second_to_home=False): '''Batter gets a base hit. By default, any runners on base will advance by the number of bases that were hit for. first_to_third, first_to_home and second_to_home can be set to true if a baserunner was to advance more bases than the hit. They only have meaning in the case of a single or double, as all runners would score on a triple. ''' if hit_type == "single": self.__single() if second_to_home: self.__advance_runner_from("third") if first_to_third: self.__advance_runner_from("second") elif first_to_home: self.__advance_runner_from("second") self.__advance_runner_from("third") if hit_type == "double": self.__double() if first_to_home: self.__advance_runner_from("third") if hit_type == "triple": self.__triple() if hit_type == "homer": self.__homer() self.__next_batter() def double_play(self, base1="second", base2="first"): '''Batter hits into a double play. base1 - base where first out is made, assume force out. base2 - base where second out is made. ''' if self.__men_on() == 0: # Maybe log a warning here, or throw exception return self.__next_batter() if self.outs &gt; 0: self.__side_retired() else: self.outs += 2 self.bases[base1] = 0 self.bases[base2] = 0 def triple_play(self): '''Batter hits into a triple play.''' if self.__men_on() &lt; 2: # Maybe log a warning here, or throw exception return self.__next_batter() self.__side_retired() def fielders_choice(self, base="second"): '''Batter hits into a fielder's choice. A fielder's choice is when a runner is on base, the batter hits the ball such that the runner is put out, but the batter is then able to get on base. base - base where the out is made, assume force out. ''' self.__next_batter() if self.outs == 2: self.__side_retired() else: self.outs += 1 self.bases[base] = 0 def error(self, advance_from=None): '''Fielder makes an error. By default nothing happens other than to take note of the error. advance_from is a list of bases to advance runners from. The base will be cleared, and the runner moved to the next base. Advancing from third base will score the runner. If a string is used for advance_from, I just put it in a list. ''' if isinstance(advance_from, str): advance_from = [advance_from] if advance_from: for base in advance_from: if self.__empty_base(base): # Maybe log a warning here, or throw exception return if advance_from: if "third" in advance_from: self.__advance_runner_from("third") if "second" in advance_from: self.__advance_runner_from("second") if "first" in advance_from: self.__advance_runner_from("first") if "home" in advance_from: self.__advance_runner_from("home") def sacrifice(self, advance_from=None): '''Batter performs a sacrifice bunt or fly out. By default all baserunners advance one base. advance_from is a list of bases to advance runners from. The base will be cleared, and the runner moved to the next base. Advancing from third base will score the runner. If a string is used for advance_from, I just put it in a list. ''' if isinstance(advance_from, str): advance_from = [advance_from] if self.__men_on() == 0: # Maybe log a warning here, or throw exception return if advance_from: for base in advance_from: if self.__empty_base(base): # Maybe log a warning here, or throw exception return self.__next_batter() if self.outs == 2: # Again, this can't be a sac with 2 outs. # Throw exception self.__side_retired() else: self.outs += 1 if advance_from == None: self.__advance_runner_from("third") self.__advance_runner_from("second") self.__advance_runner_from("first") else: if "third" in advance_from: self.__advance_runner_from("third") if "second" in advance_from: self.__advance_runner_from("second") if "first" in advance_from: self.__advance_runner_from("first") def __empty_base(self, base): '''Tests if a base is empty. Returns True if the base is empty, false otherwise. Special case for home. ''' if base == "home": return False if self.bases[base] == 0: return True return False def __advance_runner_from(self, base): '''Advance a runner from the base to the next one, and clear the base behind. Advancing from third base will score the runner. Advancing from home infers that the batter got on base through an error. ''' if base == "third": if self.bases["third"] != 0: self.bases["third"] = 0 self.__score_run() if base == "second": if self.bases["second"] != 0: self.bases["second"] = 0 self.bases["third"] = 1 if base == "first": if self.bases["first"] != 0: self.bases["first"] = 0 self.bases["second"] = 1 if base == "home": self.bases["first"] = 1 self.__next_batter() def __new_inning(self): '''Start a fresh inning.''' self.bases = {"first": 0, "second": 0, "third": 0} self.count = {"balls": 0, "strikes": 0} self.outs = 0 def __men_on(self): '''Return a count of how many base runners there are.''' men_on = 0 for base in self.bases: if self.bases[base] != 0: men_on += 1 return men_on def __side_retired(self): '''Three outs, time to switch sides, or end the game.''' if self.inning["val"] &gt;= 9: if self.inning["half"] == "bottom": if self.score["home"] != self.score["away"]: self.__end_game() else: # top if self.score["home"] &gt; self.score["away"]: self.__end_game() if self.inning["half"] == "top": self.inning["half"] = "bottom" else: self.inning["half"] = "top" self.inning["val"] += 1 self.__new_inning() def __end_game(self): '''Game is over, winner is declared. When would we ever have a tie? ''' if self.score["home"] &gt; self.score["away"]: self.winner = "home" else: self.winner = "away" self.game_over = True return def __strike_out(self): '''Batter strikes out.''' self.__next_batter() if self.outs == 2: self.__side_retired() else: self.outs += 1 def __put_out(self): '''Runner is put out.''' if self.outs == 2: self.__side_retired() else: self.outs += 1 def __next_batter(self): '''Next batter is up in the lineup.''' if self.inning["half"] == "top": if self.away_batter == 9: self.away_batter = 1 else: self.away_batter += 1 else: # bottom if self.home_batter == 9: self.home_batter = 1 else: self.home_batter += 1 self.count["balls"] = 0 self.count["strikes"] = 0 def __score_run(self): '''Score a run.''' if self.inning["half"] == "bottom": self.score["home"] += 1 else: self.score["away"] += 1 def __walk(self): "Walk the batter." if self.bases["first"] != 0: if self.bases["second"] != 0: if self.bases["third"] != 0: self.__score_run() else: self.bases["third"] = 1 else: self.bases["second"] = 1 else: self.bases["first"] = 1 self.__next_batter() def __single(self): '''Batter hits a single.''' if self.bases["third"] != 0: self.__score_run() self.bases["third"] = 0 if self.bases["second"] != 0: self.bases["second"] = 0 self.bases["third"] = 1 if self.bases["first"] != 0: self.bases["first"] = 0 self.bases["second"] = 1 self.bases["first"] = 1 def __double(self): '''Batter hits a double.''' if self.bases["third"] != 0: self.__score_run() self.bases["third"] = 0 if self.bases["second"] != 0: self.__score_run() self.bases["second"] = 0 if self.bases["first"] != 0: self.bases["first"] = 0 self.bases["third"] = 1 self.bases["second"] = 1 def __triple(self): '''Batter hits a triple.''' if self.bases["third"] != 0: self.__score_run() self.bases["third"] = 0 if self.bases["second"] != 0: self.__score_run() self.bases["second"] = 0 if self.bases["first"] != 0: self.__score_run() self.bases["first"] = 0 self.bases["third"] = 1 def __homer(self): '''Batter hits a home run.''' if self.bases["third"] != 0: self.__score_run() self.bases["third"] = 0 if self.bases["second"] != 0: self.__score_run() self.bases["second"] = 0 if self.bases["first"] != 0: self.__score_run() self.bases["first"] = 0 self.__score_run() </code></pre> <p>The <a href="https://bitbucket.org/jgrigonis/baseball_simulator/src/3f7c62c05b77/game_test.py" rel="nofollow">test module</a> wouldn't fit, so you'll have to see it on bitbucket.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T03:29:35.217", "Id": "18312", "Score": "0", "body": "You could probably treat `bases` as a list rather than a dictionary. Then `__homer()` could simply do `self.score[\"home/away\"] = sum(self.bases)` and then `self.bases = [0, 0, 0]`" } ]
[ { "body": "<pre><code># pylint: disable=R0902\n# Ignore error about too many instance attributes.\n</code></pre>\n\n<p>PyLint is trying to tell you something. Your class is to complex, and should be split into several smaller classes</p>\n\n<pre><code>def __init__(self):\n '''Set up a new game.'''\n self.count = {\"balls\": 0, \"strikes\": 0}\n</code></pre>\n\n<p>Don't use dictionaries like this. You are using this dictionary like its an object with two attributes, \"balls\" and \"strikes\". What you should do is have a separate class called <code>AtBat</code> or something which holds that data.</p>\n\n<pre><code> self.score = {\"home\": 0, \"away\": 0}\n self.home_batter = 1\n self.away_batter = 1\n</code></pre>\n\n<p>You've got two different pieces relating to the team. Instead, you should have a <code>Team</code> object with <code>score</code> and <code>batter</code> attributes. </p>\n\n<pre><code> self.inning = {\"val\": 1, \"half\": \"top\"}\n</code></pre>\n\n<p>I'd identify an inning with a tuple <code>(1, True)</code> for the top of the first, and <code>(9, False)</code> for the bottom of the ninth. Its awkward to check for strings.</p>\n\n<pre><code> self.bases = {\"first\": 0, \"second\": 0, \"third\": 0}\n</code></pre>\n\n<p>This should be a list</p>\n\n<pre><code> self.winner = None\n self.game_over = False\n self.outs = 0\n</code></pre>\n\n<p>This is inning specific data, and suggests that you should have an inning class to hold it.</p>\n\n<pre><code> self.__new_inning()\n\n\ndef __put_out(self):\n '''Runner is put out.'''\n if self.outs == 2:\n self.__side_retired()\n else:\n self.outs += 1\n\ndef __strike_out(self):\n '''Batter strikes out.'''\n self.__next_batter()\n if self.outs == 2:\n self.__side_retired()\n else:\n self.outs += 1\n</code></pre>\n\n<p>The second function repeats the first, the second function should call the first one. </p>\n\n<pre><code>def __single(self):\n '''Batter hits a single.'''\n if self.bases[\"third\"] != 0:\n self.__score_run()\n self.bases[\"third\"] = 0\n if self.bases[\"second\"] != 0:\n self.bases[\"second\"] = 0\n self.bases[\"third\"] = 1\n if self.bases[\"first\"] != 0:\n self.bases[\"first\"] = 0\n self.bases[\"second\"] = 1\n self.bases[\"first\"] = 1\n\ndef __double(self):\n '''Batter hits a double.'''\n if self.bases[\"third\"] != 0:\n self.__score_run()\n self.bases[\"third\"] = 0\n if self.bases[\"second\"] != 0:\n self.__score_run()\n self.bases[\"second\"] = 0\n if self.bases[\"first\"] != 0:\n self.bases[\"first\"] = 0\n self.bases[\"third\"] = 1\n self.bases[\"second\"] = 1\n</code></pre>\n\n<p>These should be a single function which takes a numeric parameter 1 for a single, 2 for a double. You should be able to write a much simpler function using that.</p>\n\n<p>Your function operate at differently levels of abstraction. You've got functions for the simplest parts of baseball like a <code>strike</code> and then you've got functions for more complex things like <code>triple_play</code>. Your code should really have lower level functions for the non-batting portion as well. It should have functions like <code>batter_tagged</code> and <code>ball_at_base</code>. </p>\n\n<p>If you really need your higher level functions, they should probably be in a separate class and use the lower level functions to accomplish their goals. </p>\n\n<p>Overall, your code is way more complicated than it needs to be. Hopefully, I've given you some ideas on how to improve it. </p>\n\n<p>I'd suggest your class should operate something like this:</p>\n\n<pre><code>at_bat = game.next_at_bat()\nat_bat.pitch(STRIKE)\nat_bat.runner_moves(1,2) # steals base\nat_bat.pitch(BALL)\nat_bat.pitch(HIT)\nat_bat.all_runners_forward()\nat_bat.runner_tagged(2)\nat_bat.runner_moves(1,2)\nat_bat.ball_at_base(0)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T17:43:22.057", "Id": "11439", "ParentId": "11419", "Score": "2" } } ]
{ "AcceptedAnswerId": "11439", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T20:40:01.563", "Id": "11419", "Score": "3", "Tags": [ "python", "simulation" ], "Title": "Baseball game state class in python looking for feedback" }
11419
<p>I just made this responsive image solution, but I'm not sure if it's the best way to do what I'm trying to achieve. Use cases can be found at <a href="http://responsimage.com/" rel="nofollow">http://responsimage.com/</a>.</p> <pre><code>/* responsimage.com v0.2.3 */ (function ($, window, Date) { 'use strict'; $(function() { var rPrefs = $('meta[name="responsimage"]'), rServer = rPrefs.data('server'), rStatic = rPrefs.data('static') || 'http://f.cl.ly/items/0M3H0q3n1Z1S1y362d09/spacer.gif', rLoading = rPrefs.data('loading') || 'http://f.cl.ly/items/2w2G3N2p0B400Z380J1u/loading.gif', rLimit = rPrefs.data('limit') || 100, rTimestamp = new Date(), rTags = $('[data-responsimage]'); function responsimage(rInit) { rTags.each(function() { var rThis = $(this), filename = rThis.data('responsimage'), rWidth = rThis.width(), rHeight = rThis.height(), rAnchor = rThis.data('responsimage-anchor') || 5, rImage; if(rInit) { rThis.attr('src', rStatic).css('background', '#fff url(' + rLoading + ') no-repeat center'); } if(rThis.css('font-family') === 'pixel-ratio-2') { rWidth *= 2; rHeight *= 2; } rImage = rServer.replace('width', rWidth).replace('height', rHeight).replace('anchor', rAnchor).replace('filename', filename); if(filename !== 'disabled') { rThis.attr('src', rImage); } }); } responsimage(1); $(window).resize(function () { var rNow = new Date(); if (rNow - rTimestamp &gt;= rLimit) { responsimage(false); } }); window.onorientationchange = function() { setTimeout(responsimage, 0); }; }); }(jQuery, window, Date)); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T22:23:24.193", "Id": "18307", "Score": "4", "body": "please put code in question" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T22:24:11.557", "Id": "18308", "Score": "4", "body": "Do you start all your variables with `r` for the lulz?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T22:24:29.887", "Id": "18309", "Score": "1", "body": "jQuery dependency = not efficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T22:26:54.183", "Id": "18366", "Score": "0", "body": "I started with `r` so I would ensure no conflicts" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T22:36:52.250", "Id": "18368", "Score": "0", "body": "So you _do_ start all your variables with `r` for the lulz. Good stuff o/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T23:14:42.110", "Id": "18555", "Score": "0", "body": "I dont understand" } ]
[ { "body": "<ol>\n<li><p>declare the variables inside \"rTags.each()\" on the outside. This way there not being declared on each iteration.</p></li>\n<li><p>The naming of parameters \"window\" and \"Date\". I would suggest naming them something different to avoid confusion. This way you can distinguish between the globals from the parameters.</p></li>\n<li><p>Since you variables are scoped in the functions you can drop the \"r\" if you wanted too.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-06T20:33:11.563", "Id": "24807", "ParentId": "11422", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T22:20:02.847", "Id": "11422", "Score": "1", "Tags": [ "javascript", "image" ], "Title": "Responsive image solution" }
11422
<p>I am developing code for <a href="https://math.stackexchange.com/questions/139842/in-how-many-ways-can-a-number-be-expressed-as-a-sum-of-consecutive-numbers/140072#140072">a problem posted on StackOverflow.</a> I have written my solution in Java but it is taking too much time to execute for numbers such as <code>21432154197846387216432</code>. How could I improve the performance of the following code?</p> <pre><code>import java.util.Scanner; public class Main { // private static final double N = Double.parseDouble("916548345678631") ; // private static final long loopUntil = (int)(Math.sqrt(2 * N)); // private static double M = 1.0 ; public static void main(String[] args) { Scanner scanner = new Scanner(System.in).useDelimiter("\n"); while (scanner.hasNext()) { double N = Double.parseDouble(scanner.next()); long loopUntil = (long) (Math.sqrt(2 * N)); double M = 1.0; int doProcess = doProcess(N, loopUntil, M); System.out.println(doProcess); } scanner.close(); } public static int doProcess(double N, long loopUntil, double M) { int result = 0; double constantDevisor = 1.0 / 2.0 ; // System.out.println("Loop Unttil " + loopUntil); while (M &lt;= loopUntil) { double val = 0; // System.out.println((N / M) +" " + ( M / 2 ) + " " + (1.0/2.0)); val = (N / M) + (M / 2) + constantDevisor; // System.out.println(val); if (Math.floor(val) == val) { System.out.println("With : " + M); result++; } M++; } return result; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T23:07:18.010", "Id": "62383", "Score": "0", "body": "What about using multiple processors and threads? The algorithm in its current form is a good candidate for parallelization." } ]
[ { "body": "<p>You have one serious problem - that supergigantic number you want to use is larger than the precision of both doubles AND longs. In fact, because both doubles and longs use 64 bits in Java, you would be better off using longs because with doubles, only 53 of those 64 bits are available for what you want to do.</p>\n\n<p>What this means is that, in order to get a meaningful calculation AT ALL for 21432154197846387216432 that you would have to implement it with something else because the algorithm, as you have implemented it, will give you answers that are completely meaningless because your initial value is a victim of roundoff error.</p>\n\n<p>Now, for numbers up to the limit of long (9223372036854775807), I have created a different implementation that uses only long operations. It's organized differently because we have to force the algorithm to work correctly without any fractional arithmetic.</p>\n\n<pre><code>public class MainTwo {\n\n private static final long N = 916548345678631l;\n\n public static void main(String[] args) {\n\n long start = System.currentTimeMillis();\n long loopUntil = (long) (Math.sqrt(2 * N));\n long M = 1l;\n\n int doProcess = doProcess(N, loopUntil, M);\n System.out.println(doProcess);\n\n long end = System.currentTimeMillis();\n System.out.println(\"[Main.main] elapsed time: \" + (end - start));\n }\n\n public static int doProcess(long N, long loopUntil, long M) {\n int result = 0;\n\n while (M &lt;= loopUntil) {\n\n boolean yesProcess = false;\n long val = 0;\n boolean mEven = (M % 2) == 0;\n if (mEven) {\n yesProcess = (N % M == M/2);\n if (yesProcess) {\n val = (N + 1) / M + (M / 2);\n }\n }\n else {\n yesProcess = N % M == 0;\n if (yesProcess) {\n val = (N / M) + (M + 1) / 2;\n }\n }\n\n if (yesProcess) {\n System.out.println(\"With : \" + M);\n result++;\n }\n M++;\n }\n\n return result;\n }\n\n}\n</code></pre>\n\n<p>And just for the sake of completeness, here is an implementation using BigInteger that will be able to work correctly against your giant number. Be warned though - using BigInteger makes it more than 20 times slower than the long implementation. I used this <a href=\"http://www.merriampark.com/bigsqrt.htm\" rel=\"nofollow\"><code>BigSquareRoot</code></a> class.</p>\n\n<pre><code>public class MainThree {\n// private static final BigInteger N = new BigInteger(\"916548345678631\");\n private static final BigInteger N = new BigInteger(\"21432154197846387216432\");\n\n private static final BigSquareRoot bsr = new BigSquareRoot();\n private static final BigInteger zero = new BigInteger(\"0\");\n private static final BigInteger one = new BigInteger(\"1\");\n private static final BigInteger two = new BigInteger(\"2\");\n\n public static void main(String[] args) {\n\n long start = System.currentTimeMillis();\n BigInteger loopUntil = bsr.get(N.multiply(two)).toBigInteger();\n BigInteger M = one;\n\n int doProcess = doProcess(N, loopUntil, M);\n System.out.println(doProcess);\n\n long end = System.currentTimeMillis();\n System.out.println(\"[Main.main] elapsed time: \" + (end - start));\n }\n\n public static int doProcess(BigInteger N, BigInteger loopUntil, BigInteger M) {\n int result = 0;\n\n while (M.compareTo(loopUntil) &lt; 0) {\n\n boolean yesProcess = false;\n BigInteger val = zero;\n boolean mEven = M.mod(two).equals(zero);\n if (mEven) {\n yesProcess = N.mod(M).equals(M.divide(two));\n if (yesProcess) {\n val = (N.add(one).divide(M)).add(M.divide(two));\n }\n }\n else {\n yesProcess = N.mod(M).equals(zero);\n if (yesProcess) {\n val = N.divide(M).add(M.add(one).divide(two));\n }\n }\n\n if (yesProcess) {\n System.out.println(\"With : \" + M);\n result++;\n }\n M = M.add(one);\n }\n\n return result;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T20:30:48.923", "Id": "18430", "Score": "3", "body": "I tried running the BigInteger version against your huge number. After 6 hours of work it had not finished." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T05:25:45.650", "Id": "19515", "Score": "0", "body": "I want it to be completed in 3 minutes :(" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T15:27:09.763", "Id": "11437", "ParentId": "11425", "Score": "5" } }, { "body": "<p>Ok, here is BigInteger version that solves the 21432154197846387216432 testcase in <strong>13 seconds</strong> on my pretty old hardware C2D E7200 @3GHz. As I said it's based on that great Haskell <a href=\"https://codegolf.stackexchange.com/questions/5703/in-how-many-ways-can-a-number-be-expressed-as-a-sum-of-consecutive-numbers/5705#5705\">code</a>.</p>\n\n<pre><code>import java.math.BigInteger;\n\npublic class Test {\n\npublic static BigInteger doProcess(BigInteger n) {\n\n final BigInteger zero = BigInteger.ZERO;\n final BigInteger one = BigInteger.ONE;\n final BigInteger two = new BigInteger(\"2\");\n\n while (n.and(one).compareTo(zero) == 0) n = n.shiftRight(1);\n\n BigInteger k = zero;\n BigInteger p = new BigInteger(\"3\");\n BigInteger result = one;\n\n while (true) {\n if (n.compareTo(one) == 0) {\n result = result.multiply(k.add(one));\n break;\n }\n if (k.compareTo(zero) == 0 &amp;&amp; (p.pow(2).compareTo(n) &gt; 0)) {\n result = result.shiftLeft(1);\n break;\n }\n if (n.remainder(p).compareTo(zero) != 0) {\n result = result.multiply(k.add(one));\n p = p.add(two);\n k = zero;\n } else {\n n = n.divide(p);\n k = k.add(one);\n }\n }\n return result;\n}\n\npublic static void main(String[] rgs) {\n String[] tests = {\"9\", \"11\", \"1337\", \"9000000000000001\", \"8999999999999971\", \"21432154197846387216432\"};\n long total = System.currentTimeMillis();\n for (String test : tests) {\n long test_time = System.currentTimeMillis();\n System.out.print(test);\n System.out.print(\" = \" + doProcess(new BigInteger(test)));\n System.out.println(\" (ms) : \" + (System.currentTimeMillis() - test_time));\n }\n System.out.println(\"Total time (ms) : \" + (System.currentTimeMillis() - total));\n}\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T15:53:56.620", "Id": "19537", "Score": "0", "body": "Ok, but you're using a completely different algorithm from the OP. You should have pointed that out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T16:23:42.370", "Id": "19539", "Score": "0", "body": "Yes the algorithm is different but solve the same problem. The link to the original discussion (where the topicstarted obtains his algorithm) is here: http://codegolf.stackexchange.com/questions/5703/in-how-many-ways-can-a-number-be-expressed-as-a-sum-of-consecutive-numbers/5705#5705." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T17:08:28.763", "Id": "19542", "Score": "0", "body": "I'm just pointing out that you need to be explicit about the algorithm. Some Computer Science teachers want to see problems solved with implementations of specific algorithms. Your answer and my answer are both perfectly valid, but they *are* different. Mine is a more efficient (and limitation free) version of the original posters algorithm while yours uses an entirely different (and better) algorithm." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T15:49:49.823", "Id": "12168", "ParentId": "11425", "Score": "1" } } ]
{ "AcceptedAnswerId": "11437", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T05:50:50.750", "Id": "11425", "Score": "2", "Tags": [ "java", "algorithm", "performance" ], "Title": "{Sum+=i++} to Reach N" }
11425
<p>Right now I am working on an AJAX call that grabs a random photo that a Facebook user is tagged in and then grabs the large source for it. Is there any way to speed this up or at least distill the call into one query?</p> <pre><code>var query1 = encodeURI("SELECT pid,xcoord,ycoord FROM photo_tag WHERE subject={{mystery.uid}} order by rand() LIMIT 1"); var query2 = encodeURI("SELECT src_big FROM photo WHERE pid="); function get_pic() { var l = $.get("https://graph.facebook.com/fql?q="+query1, {access_token: "{{token}}"}, function(data1) { $.get("https://graph.facebook.com/fql?q="+query2+data1.data[0].pid, {access_token: "{{token}}"}, function(data2) { $("#mystery_img").html('&lt;center&gt;&lt;img src="'+data2.data[0].src_big+'"&gt;&lt;/center&gt;'); var top = $("#mystery_img img").offset().top + Math.floor(data1.data[0].ycoord); var left = $("#mystery_img img").offset().left + Math.floor(data1.data[0].xcoord); var img = $(document.createElement('img')).attr({src: "/static/images/curved_arrow.gif"}) .css('position', 'absolute') .css('top', top) .css('left', left); $("#mystery_img").append(img); }, "json"); }, "json"); } </code></pre>
[]
[ { "body": "<p>I haven't worked with Facebook's API using queries like this, but I know SQL inside and out, and this screams INNER JOIN to me.</p>\n\n<pre><code>var joinedQuery = \"SELECT Photo_Tag.pid,Photo_Tag.xcoord,Photo_Tag.ycoord,Photo.src_big FROM photo_tag AS Photo_Tag INNER JOIN photo AS Photo ON Photo_Tag.pid = Photo.pid WHERE Photo_Tag.subject = {{mystery.uid}} ORDER BY RAND() LIMIT 1;\";\n</code></pre>\n\n<p>Also, the use of <code>ORDER BY RAND()</code> is going to be inherently slow (especially with a system as large as Facebooks), so might I recommend something more like this:</p>\n\n<pre><code>var joinedQuery = \"SELECT Photo_Tag.pid,Photo_Tag.xcoord,Photo_Tag.ycoord,Photo.src_big FROM photo_tag AS Photo_Tag INNER JOIN photo AS Photo ON Photo_Tag.pid = Photo.pid INNER JOIN (SELECT (MAX(pid) * RAND()) AS pid FROM photo_tag WHERE Photo_Tag.subject = {{mystery.uid}}) AS MaxId ON Photo_Tag.pid = MaxId.pid WHERE Photo_Tag.subject = {{mystery.uid}} ORDER BY Photo_Tag.pid ASC LIMIT 1\";\n</code></pre>\n\n<p>Written to be more readable, that query is:</p>\n\n<pre><code>SELECT Photo_Tag.pid\n ,Photo_Tag.xcoord\n ,Photo_Tag.ycoord\n ,Photo.src_big\nFROM photo_tag AS Photo_Tag\nINNER JOIN photo AS Photo ON Photo_Tag.pid = Photo.pid\nINNER JOIN (\n SELECT (MAX(pid) * RAND()) AS pid \n FROM photo_tag\n WHERE Photo_Tag.subject = {{mystery.uid}}\n) AS MaxId ON Photo_Tag.pid = MaxId.pid\nWHERE Photo_Tag.subject = {{mystery.uid}}\nORDER BY Photo_Tag.pid ASC\nLIMIT 1;\n</code></pre>\n\n<p>Using <code>ORDER BY RAND()</code> requires querying every row to build a new \"randomness\" ID, creating and populating a temporary table with this newly randomized result set, and then querying from that table to bring back your row. For large datasets, this can be very slow.</p>\n\n<p>By instead <code>JOIN</code>ing the table back onto itself with random pids generated, then <code>ORDER</code>ing and <code>LIMIT</code>ing that dataset, it can result in a much faster query. <a href=\"http://jan.kneschke.de/projects/mysql/order-by-rand/\" rel=\"nofollow\">This article explains in (enormous) detail what I mean</a>, but also shows that a query such as the one above will be faster with a table holding as little as 100 rows, and will be no slower than the original query in any case.</p>\n\n<p>Even if you don't get rid of <code>ORDER BY RAND()</code>, your reduction to a single query should speed up your call.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-27T14:10:43.500", "Id": "38169", "ParentId": "11427", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T07:23:18.470", "Id": "11427", "Score": "3", "Tags": [ "javascript", "jquery", "ajax", "facebook" ], "Title": "Is there any way to shorten up this Facebook API call?" }
11427
<p>I'm new to using PDO and am trying to create a secure class to handle MySQL statements. Here is what I have so far:</p> <pre><code>class SQL { private static $dbh = null; private function __construct($host, $user, $pass, $data, $table) { $this-&gt;host = (!empty($host)) ? $host: 'localhost'; $this-&gt;user = $user; $this-&gt;pass = $pass; $this-&gt;data = $data; $this-&gt;table = $table; static::connect(); } private function __destruct() { static::close(); } public static function connect() { $dsn = 'mysql:dbname=' . $this-&gt;table . ';host=' . $this-&gt;host; static::$dbh = new PDO($dsn, $this-&gt;user, $this-&gt;pass); static::$dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } public static function close() { static::$dbh = null; } public static function query($query) { $sth = static::$dbh-&gt;prepare($query); $sth-&gt;execute(); } } </code></pre> <p>Is what I've done correct so far and conform to best practices?</p>
[]
[ { "body": "<p><strong>Disclaimer:</strong> I've not tackled SQL or PDO as of yet, so this answer will focus mainly on the code itself.</p>\n\n<p>You should not set <code>$this-&gt;data</code> in the <code>__construct()</code> method unless you are planning on using it. I would set it in whatever method you use to add that data. I am assuming this class is incomplete because I did not find it being used anywhere (maybe I missed it?). Doing this you won't have to hunt for that variable later when trying to debug it.</p>\n\n<p>If the only time you are going to use your <code>connect()</code> and <code>close()</code> methods are going to be in the class, you should make them private. Which probably should be the case anyways. Generally you want full control of any instances of a database, which means making all calls to it within your control, and the best way to ensure this is to make it private. Allowing a user to possibly control its state is asking for trouble. If you need to open another database, which is the only reason I can think of for making it public, then you should simply create a new object for it. This will also make having these methods static quite unnecessary.</p>\n\n<p>Why are you declaring <code>$dbh</code> static? Just make it a private variable and call it with <code>$this</code>. Maybe there is a reason for doing it this way, but I wouldn't know it. I tend to steer clear of the static keyword.</p>\n\n<p>Final thoughts. Your variables should be easily identifiable. Yes, I understand what a <code>$dbh</code> is, but it should be clear for those who don't. I would simply call it something like <code>$handle</code> or if I might end up using multiple handles <code>$db_handle</code>. But <code>$dsn</code> and <code>$sth</code> (statement handle?) kind of have me stumped. Make them clear so that people reading your code at a later date will know what they mean. If you don't wish to change the variable names themselves, then at least use PHP Doc notes to describe what they are.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T13:56:59.467", "Id": "11435", "ParentId": "11432", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T11:31:37.710", "Id": "11432", "Score": "1", "Tags": [ "php", "object-oriented", "pdo" ], "Title": "PDO MySQL class" }
11432
<p>I have an application coded in VB.NET that has a bunch of servers in a DataGridView and does a continuous asynchronous ping. If all the servers are up it refreshes great, but if one goes down and starts to time out it takes about 5-10 seconds before the program starts responding again. This program needs to ping all the servers at the same time. I need help with improving the performance of this code.</p> <pre><code>Private Sub cmdStartPing_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStartPing.Click Dim rc, myic As Integer Dim sname As String 'Dim preply As PingReply pinging = 1 cmdStopPing.Select() rc = DGV1.RowCount - 1 If rc &gt; -1 Then bCancel = False Do Until bCancel = True For myic = 0 To rc Application.DoEvents() If bCancel Then bCancel = True DGV1.BackgroundColor = Color.White MsgBox("Pinging Stopped") Exit For End If Try sname = DGV1.Item(0, myic).Value PingHost(sname) If pingresults = "Success" Then DGV1.Rows(myic).Cells(1).Value = "Success" DGV1.Rows(myic).Cells(2).Value = roundtriptime DGV1.Rows(myic).DefaultCellStyle.BackColor = Color.YellowGreen DGV1.Refresh() Else DGV1.Rows(myic).Cells(1).Value = "No Reply" DGV1.Rows(myic).Cells(2).Value = "Timed Out" DGV1.Rows(myic).Cells(3).Value = currentdt DGV1.Rows(myic).DefaultCellStyle.BackColor = Color.Red DGV1.Refresh() End If Catch ex As Exception DGV1.Rows(myic).Cells(1).Value = "No Reply" DGV1.Rows(myic).Cells(2).Value = "Timed Out" DGV1.Rows(myic).Cells(3).Value = currentdt DGV1.Rows(myic).DefaultCellStyle.BackColor = Color.Red DGV1.Refresh() End Try Next Loop Else MsgBox("Please add at least one host to the datagrid to ping.") End If End Sub </code></pre> <p>Stop ping:</p> <pre><code>Private Sub cmdStopPing_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStopPing.Click bCancel = True pinging = 0 End Sub </code></pre> <p>Uses this function to ping:</p> <pre><code>Imports System.Net.NetworkInformation Module AsyncPingHost 'Function PingIPAdress(ByVal IPAdress As String) Function PingHost(ByVal host As String) Dim ping As Ping Dim preply As PingReply ping = New Ping Try preply = ping.Send(host) roundtriptime = preply.RoundtripTime If preply.Status = IPStatus.Success Then pingresults = "Success" Else pingresults = "Failed" End If Catch ex As Exception pingresults = ex.Message End Try End Function </code></pre>
[]
[ { "body": "<p>I have a similar problem (but I have to use PSLoggedOn.Exe which times out in 10-15 seconds).</p>\n\n<p>To mitigate the problem I use WMI to Ping.</p>\n\n<p>I will then do PSLoggedOn only if the result was a valid IPnumber.</p>\n\n<p>WmiPingStatus is perhaps a little less reliable because it is faster.\nBut if You don't get an answer you will get an answer the next loop.</p>\n\n<pre><code> Friend Function WmiPingStatus(computer As String) As String\n Dim searcher As New ManagementObjectSearcher(\"SELECT ProtocolAddress FROM Win32_Pingstatus WHERE Address = '\" &amp; computer &amp; \"'\")\n For Each wmiObj As ManagementObject In searcher.Get()\n For Each prop As PropertyData In wmiObj.Properties\n If prop.Name.Equals(\"ProtocolAddress\", StringComparison.InvariantCultureIgnoreCase) Then Return wmiObj(prop.Name.ToString).ToString\n Next\n Next\n Return \"\"\nEnd Function\n</code></pre>\n\n<p>Your function PingHost is not async but You can do it async if You use :</p>\n\n<p>Await preply = SendAsync(host, Object)</p>\n\n<p>But that is only part of the problem becasue You still have to wait for the answer.\nAsync is allways good because it will use less resources when Waiting.\nAnd while You wait you could perhaps do for example 5 Task in \"Parallell\".\nBut then You still have to wait for the longest query to end.\nSo perhaps WmiPingStatus could be useful also for You</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-28T05:51:18.750", "Id": "29077", "ParentId": "11433", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T13:31:41.293", "Id": "11433", "Score": "2", "Tags": [ ".net", "vb.net", "asynchronous" ], "Title": "Datagrid not refreshing correctly with Async Ping VB .Net" }
11433
<p>Questions:</p> <ol> <li>Is this code secure? (I think that it is, but I'm a newbie so I want to be sure.)</li> <li>Is the <code>get_pass</code> function correct with passing the arguments to the <code>free_memory</code> function?</li> <li>Do I have to delete the pass' buffer with <code>memset</code>?</li> </ol> <p></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;string.h&gt; #include &lt;termios.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netdb.h&gt; #include &lt;netinet/in.h&gt; void get_pass(char **host, char **user, char **pass); void free_memory(char *h, char *u, char *p); int main(){ char *host, *user, *pass; host = (char *) calloc(64, sizeof(char)); /* spazio per max 64 caratteri e inizializzo a 0 (maggior sicurezza) */ if(!host){ fprintf(stdout, "\nErrore di allocazione della memoria\n"); exit(EXIT_FAILURE); }; user = (char *) calloc(64, sizeof(char)); if(!user){ fprintf(stdout, "\nErrore di allocazione della memoria\n"); exit(EXIT_FAILURE); }; pass = (char *) calloc(64, sizeof(char)); if(!pass){ fprintf(stdout, "\nErrore di allocazione della memoria\n"); exit(EXIT_FAILURE); }; /* Immissione di hostname, username e password. * Controllo inoltre i 'return code' dei vari fscanf e, se non sono 0, esco. * Per evitare buffer overflow imposto limite massimo a 64 caratteri */ fprintf(stdout,"--&gt; Inserisci hostname (max 64 caratteri): "); if(fscanf(stdin, "%63s", host) == EOF){ fprintf(stdout, "\nErrore, impossibile leggere i dati\n"); free_memory(host,user,pass); exit(EXIT_FAILURE); } fprintf(stdout,"\n--&gt; Inserisci username (max 64 caratteri): "); if(fscanf(stdin, "%63s", user) == EOF){ fprintf(stdout, "\nErrore, impossibile leggere i dati\n"); free_memory(host,user,pass); exit(EXIT_FAILURE); }; fprintf(stdout, "\n--&gt; Inserisci password (max 64 caratteri): "); get_pass(&amp;host,&amp;user,&amp;pass); /* Stampo a video le informazioni immesse */ fprintf(stdout, "\n\nHost: %s\nUser: %s\nPass: %s\n\n", host,user,pass); free_memory(host,user,pass); return EXIT_SUCCESS; } void get_pass(char **host, char **user, char **pass){ /* Grazie a termios.h posso disabilitare l'echoing del terminale (password nascosta) */ struct termios term, term_orig; tcgetattr(STDIN_FILENO, &amp;term); term_orig = term; term.c_lflag &amp;= ~ECHO; tcsetattr(STDIN_FILENO, TCSANOW, &amp;term); /* Leggo la password e controllo il 'return code' di fscanf */ if(fscanf(stdin, "%63s", *pass) == EOF){ fprintf(stdout, "\nErrore, impossibile leggere i dati\n"); tcsetattr(STDIN_FILENO, TCSANOW, &amp;term_orig); free_memory(*host, *user, *pass); exit(EXIT_FAILURE); }; /* Reimposto il terminale allo stato originale */ tcsetattr(STDIN_FILENO, TCSANOW, &amp;term_orig); } void free_memory(char *h, char *u, char *p){ /* Libero la memoria occupata */ free(h); free(u); free(p); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T04:37:47.737", "Id": "18382", "Score": "0", "body": "What do you mean by \"secure code\" and why do you think your code is secure?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T06:41:13.917", "Id": "18384", "Score": "0", "body": "I mean that my code is not vulnerable to buffer overflow...i think that my code is secure because _i think_ that i've done all the checks...but i'm a newbie so i'm not so sure xD" } ]
[ { "body": "<p>I'm not sure it's exactly insecure, but I'd consider it excessively verbose and repetitive. Given that your <code>user</code>, <code>host</code> and <code>pass</code> are all small, fixed-size, and allocated for the duration of a single function, dynamic allocation seems to gain little (and cost quite a bit of verbosity) with them. I think I'd write something like this:</p>\n\n<pre><code>void getprompt(char *string, size_t max, char const *prompt) { \n char buffer[16];\n\n sprintf(buffer, \"%%%ds\", max-1);\n printf(\"%s\", prompt);\n if (scanf(buffer, string) == EOF) {\n printf(\"\\nErrore, impossibile leggere i dati\\n\"); \n exit(EXIT_FAILURE);\n } \n}\n\nint main(){\n char host[64], user[64], pass[64];\n\n getprompt(host, sizeof(host), \"--&gt; Inserisci hostname (max 64 caratteri): \");\n getprompt(user, sizeof(user), \"\\n--&gt; Inserisci username (max 64 caratteri): \");\n\n printf(\"\\n--&gt; Inserisci password (max 64 caratteri): \");\n get_pass(&amp;host,&amp;user,&amp;pass);\n\n /* Stampo a video le informazioni immesse */\n printf(\"\\n\\nHost: %s\\nUser: %s\\nPass: %s\\n\\n\", host,user,pass);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>There also seems to be no reason to pass <code>host</code> or <code>user</code> to <code>get_pass</code> -- it doesn't really use them (and logically, shouldn't). I'd probably write it as a wrapper around <code>getprompt</code> -- do the <code>tcsetattr</code>, call <code>getprompt</code>, then undo the <code>tcsetattr</code>. Although you have matched the sizes correctly in this case, your <code>get_pass</code> has implicit knowledge of the size of <code>pass</code>; it works as-is, but is relatively fragile, so in the long term it would be fairly easy for somebody to create a hole by adjusting the size in <code>get_pass</code> but not in <code>main</code> (or vice versa).</p>\n\n<p>I'd also consider changing <code>getprompt</code> to return a <code>bool</code> indicating success/failure rather than having it directly exit the program. Along with the suggested change to <code>getpass</code>, that would turn your <code>main</code> into something like:</p>\n\n<pre><code>int main() {\n char host[64], user[64], pass[64];\n\n if (getprompt(host /* ... */) &amp;&amp;\n getprompt(user /* ... */) &amp;&amp;\n get_pass(pass /* ... */) \n {\n printf(\"\\n\\nHost: %s\\nUser: %s\\nPass: %s\\n\\n\", host, user, pass);\n }\n return EXIT_SUCCESS;\n};\n</code></pre>\n\n<p>Bottom line: I don't see any obvious security holes in the code as it stands, but it strikes me as excessively verbose and rather fragile. It's unnecessarily difficult to be certain that it's correct now, and likely to get broken in the long term even if it is all correct now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T21:40:48.703", "Id": "18352", "Score": "0", "body": "wow O.O i don't know what to say :O i still have much to learn and understand...let's start from allocation. You have said that _\"Given that your user, host and pass are all small, fixed-size, and allocated for the duration of a single function\"_ but i thought that with calloc i can made dynamic allocation so haven't to know _how long is a string_ . I've used 64 chars because i have to put a \"maximum value\"...isn't it? Or i can go out of memory..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T21:57:17.963", "Id": "18354", "Score": "0", "body": "@polslinux: `malloc`/`calloc`/`realloc` *allow* you to allocate different sizes when needed, but right now your code only allocates one specific size -- and if that's what you're going to do, there's little reason to use them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T21:59:09.960", "Id": "18356", "Score": "0", "body": "And how can i allocate something dynamically without going out of memory?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T22:01:51.907", "Id": "18357", "Score": "0", "body": "@polslinux: I'm not quite sure exactly what you're asking here..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T22:09:13.800", "Id": "18361", "Score": "0", "body": "nothing...nothing...i have to study more ;(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T15:11:41.743", "Id": "18596", "Score": "0", "body": "I agree that it's an improvement not to use the heap for such small buffers, however note that if you `scanf` with `%64d` into a buffer of 64 `char`s, and you enter a string of length 64, you will end up with a non-zero-terminated string. (Just tested to confirm.) This is exactly the opposite of the \"secure\" coding that was being asked about. (Generally I would say that use of `scanf` is a big red flag that something bad is likely to be going on, because it's pretty hard to use its clunky interface correctly.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T15:14:34.143", "Id": "18598", "Score": "0", "body": "@asveikau: Good point. Fixed. But yes, `fgets` is *probably* a better choice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T15:16:05.917", "Id": "18600", "Score": "0", "body": "I think you also need to zero out that last byte, from your code nobody is ever initializing these things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T15:16:48.210", "Id": "18601", "Score": "0", "body": "@asveikau: no -- scanf *does* zero-terminate the string." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T20:07:12.720", "Id": "11449", "ParentId": "11438", "Score": "6" } }, { "body": "<p>A few more comments to add to JC's:</p>\n\n<ul>\n<li><p>Your use of <code>fscanf</code> in <code>get_pass</code> prevents the user from using a pass phrase containing spaces. <code>fgets</code> might be a better choice.</p></li>\n<li><p>The GNU equivalent of your <code>get_pass</code> function (<a href=\"http://www.gnu.org/software/libc/manual/html_node/getpass.html\">http://www.gnu.org/software/libc/manual/html_node/getpass.html</a>) uses <code>TCSAFLUSH</code> not <code>TCSANOW</code>. Not sure whether this has any security implications.</p></li>\n<li><p>There might be a <code>getpass()</code> on your system (OS-X has one)</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T06:40:15.867", "Id": "18383", "Score": "0", "body": "Thanks! I've replaced my get_pass with the GNU one! :) ps: i can input password with space..i've tried!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T07:14:54.750", "Id": "18385", "Score": "0", "body": "PS: getpass function is obsolete :( http://man7.org/linux/man-pages/man3/getpass.3.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T14:06:14.870", "Id": "18393", "Score": "0", "body": "password with space - using fscanf? I compiled your get_pass and tried it just to be sure yesterday and it does not input spaces (as expected). \"getpass function is obsolete\": oops!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T14:50:48.770", "Id": "18395", "Score": "0", "body": "O.o i'm sorry XD i've tried the other code (with getpass)!! You're right it doesn't accept spaces xD" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T22:54:23.447", "Id": "11462", "ParentId": "11438", "Score": "6" } }, { "body": "<p>In addition to what has already been said, never typecast the result of malloc/calloc in C. That is dangerous practice. Read <a href=\"http://c-faq.com/malloc/mallocnocast.html\" rel=\"nofollow noreferrer\">this</a> and <a href=\"https://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc\">this</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T14:11:00.813", "Id": "11593", "ParentId": "11438", "Score": "2" } } ]
{ "AcceptedAnswerId": "11449", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T16:07:43.760", "Id": "11438", "Score": "6", "Tags": [ "c", "security", "memory-management" ], "Title": "Memory management with password retrieval" }
11438
<p>I've programmed a minimal parallel workers queue in Ruby, and I wanted to know if it's correct, and if there are simpler ways of implementing it.</p> <p>I'm aware of the existence of MonitorMixin, but it won't save any code, I think.</p> <p>The design is kept intentionally trivial (e.g. it uses Thread.abort_on_exception).</p> <pre><code># Usage: # # queue = ParallelWorkersQueue.new( &lt;threads&gt; ) # queue.push { &lt;operation_1&gt; } # queue.push { &lt;operation_2&gt; } # queue.join # class ParallelWorkersQueue def initialize( slots ) @max_slots = slots @free_slots = slots @mutex = Mutex.new @condition_variable = ConditionVariable.new Thread.abort_on_exception = true end def push( &amp;task ) @mutex.synchronize do while @free_slots == 0 @condition_variable.wait( @mutex ) end @free_slots -= 1 end Thread.new do yield @mutex.synchronize do @free_slots += 1 @condition_variable.signal end end end def join @mutex.synchronize do while @free_slots &lt; @max_slots @condition_variable.wait( @mutex ) end end end end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T20:40:18.470", "Id": "18431", "Score": "0", "body": "Independently of the improvements, there is bug, actually. If an error is raised when **yield**ing, the following code is not executed - so the latter must be wrapped in an ensure block." } ]
[ { "body": "<p>I would prefer to use <code>Queue</code> in Erlang style (message passing), it looks cleaner. You can even pass something more useful than <code>:done</code> back, e.g. creating parallel map.</p>\n\n<pre><code>require \"thread\"\n\nPOOL_SIZE = 5\n\ntasks = (0..99).map { |i| lambda { puts \"Processing #{i}\"; sleep 1 } }\n\nmessage_queue = Queue.new\n\nstart_thread = \n lambda do\n Thread.new(tasks.shift) do |task|\n task[]\n message_queue.push(:done)\n end\n end\n\ntasks_left = tasks.length\n\n[tasks_left, POOL_SIZE].min.times do\n start_thread[]\nend\n\nwhile tasks_left &gt; 0\n message_queue.pop\n tasks_left -= 1\n start_thread[] unless tasks_left &lt; POOL_SIZE\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T18:59:36.530", "Id": "11441", "ParentId": "11440", "Score": "1" } }, { "body": "<p>Like @Victor Moroz, I'm also a fan of <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/thread/rdoc/Queue.html\" rel=\"nofollow\">Queue</a>. I also prefer to keep the threads around: it's a bit more efficient, but more important, the code is simpler:</p>\n\n<pre><code>require 'thread'\n\nclass ParallelWorkersQueue\n\n def initialize(slots)\n @work = Queue.new\n @threads = slots.times.map do\n Thread.new do\n while (work = @work.deq) != :stop\n work[]\n end\n end\n end\n end\n\n def join\n @threads.each do\n @work.enq(:stop)\n end\n @threads.each(&amp;:join)\n end\n\n def push(&amp;task)\n @work.enq(task)\n end\n\nend\n</code></pre>\n\n<p>Example of its use:</p>\n\n<pre><code>pwq = ParallelWorkersQueue.new(2)\n5.times do |i|\n pwq.push do\n puts i\n end\nend\npwq.join\n\n# =&gt; 0\n# =&gt; 1\n# =&gt; 2\n# =&gt; 3\n# =&gt; 4\n</code></pre>\n\n<p>Replace <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/thread/rdoc/Queue.html\" rel=\"nofollow\">Queue</a> with <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/thread/rdoc/SizedQueue.html\" rel=\"nofollow\">SizedQueue</a> if you wish to limit the amount of work that can be awaiting a worker thread.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:08:47.987", "Id": "11442", "ParentId": "11440", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T18:21:41.103", "Id": "11440", "Score": "2", "Tags": [ "ruby", "multithreading" ], "Title": "Correctness of a minimal parallel workers queue in Ruby" }
11440
<p>I'm doing some homework and am just curious if everything I've done looks good and/or if you'd suggest I modify something to keep with "javaese."</p> <pre><code>import java.util.Scanner; import java.util.Random; public class rockpaperscissors { public static void main (String[] args) { int cChoice; // variable for computers choice (R/P/S) int pChoice = 0; // Holds converted choice (R=1, P=2, S=3) int cScore = 0, pScore = 0, tie = 0, rounds = 0; // Initialised variables for score keeping (c = computer, p = player) plus keeps track of number of rounds played String loop="yes"; // Starts our loop Scanner input = new Scanner(System.in); // Creates scanner object Random rgen = new Random(); System.out.println("Hello, for this exercise we're going to be playing everyone's favourite game, Rock-Paper-Scissors!"); while (loop.equals("yes")) // This loop keeps our game going only while our string.loop is equal to 'yes' { cChoice=rgen.nextInt(3)+1; System.out.println("Please make your selection: R - Rock. P - Paper. S - Scissors"); String hInput = input.nextLine(); // variable for players choice (R/P/S) String hChoice = hInput.toUpperCase(); //Converts to Upper case in case user did not if (hChoice.equals("R") || hChoice.equals("P") || hChoice.equals("S")) // Ensures player has entered the correct choice for the game to continue { System.out.println(""); if (hChoice.equals("R")) // This converts pChoice to the numeric value for "Rock" { pChoice = 1; } if (hChoice.equals("P")) // This converts pChoice to the numeric value for "Rock" { pChoice = 2; } if (hChoice.equals("S")) // This converts pChoice to the numeric value for "Rock" { pChoice = 3; } if (pChoice == cChoice) // Takes care of Ties { System.out.println("Tie Game!"); System.out.println(""); tie++; rounds++; } else // Accounts for scoring for non-tie scenarios { if (cChoice==1 &amp;&amp; pChoice==3) // Computer picks Rock and player has Scissors - adds point to score and rounds { System.out.println("Computer picked Rock!"); System.out.println("Rock beats Scissors!"); System.out.println("**Computer Wins!**"); System.out.println(""); cScore++; rounds++; } if (cChoice==1 &amp;&amp; pChoice==2) // Computer picks Rock and player has Paper - adds point to score and rounds { System.out.println("Computer picked Rock!"); System.out.println("Paper beats Rock!"); System.out.println("**Player Wins!**"); System.out.println(""); pScore++; rounds++; } if (cChoice==2 &amp;&amp; pChoice==3) // Computer picks Paper and player has Scissors - adds point to score and rounds { System.out.println("Computer picked Paper!"); System.out.println("Scissors beats Paper!"); System.out.println("**Player Wins!**"); System.out.println(""); pScore++; rounds++; } if (cChoice==2 &amp;&amp; pChoice==1) // Computer picks Paper and player has Rock - adds point to score and rounds { System.out.println("Computer picked Paper!"); System.out.println("Paper beats Rock!"); System.out.println("**Computer Wins!**"); System.out.println(""); cScore++; rounds++; } if (cChoice==3 &amp;&amp; pChoice==1) // Computer picks Scissors and player has Rock - adds point to score and rounds { System.out.println("Computer picked Scissors!"); System.out.println("Rock beats Scissors!"); System.out.println("**Player Wins!**"); System.out.println(""); pScore++; rounds++; } if (cChoice==3 &amp;&amp; pChoice==2) // Computer picks Scissors and player has Paper - adds point to score and rounds { System.out.println("Computer picked Scissors!"); System.out.println("Scissors beats Paper!"); System.out.println("**Computer Wins!**"); System.out.println(""); cScore++; rounds++; } } } else // end the game { System.out.println ("Sorry, you didn't pick Rock, Paper, or Scissors. The game will end now."); System.out.println ("Here are the final scores after " + rounds +" rounds:"); System.out.println ("You\tComputer\tTies"); System.out.println (" "+ pScore +"\t " + cScore + "\t\t " + tie); loop = "no"; // terminates the while loop keeping the game going } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T18:57:45.483", "Id": "18333", "Score": "0", "body": "Looks good could be shortened but if you are just starting and learning this is fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:00:13.270", "Id": "18334", "Score": "0", "body": "truth - didn't know that existed. I'll check that out next time.\nJonH - Still learning, yeah :) Just for curiosities sake, how would you shorten it? \nThanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:01:01.337", "Id": "18335", "Score": "0", "body": "@Numpty - a lot of if conditions could be shortened up, also make use of `switch` statements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:03:39.157", "Id": "18336", "Score": "1", "body": "Remember Java Coding Conventions for class nameing... and the while has a boolean condition for continuation, think, what will be a shorter booleaan expresion than equals() ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:17:49.913", "Id": "18337", "Score": "0", "body": "Use `else if` for tests against hChoice. Your way makes unnecessary checks and is more error-prone in general." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:29:21.353", "Id": "18338", "Score": "0", "body": "You should achieve a massive reduction in code size by etracting those messages about who wins in a method, supplying the variable parts of the message as arguments." } ]
[ { "body": "<p>Once you have working code, it is time to refactor.</p>\n\n<p>For example, once the computer makes a choice, print \"Computer picked %s\" to announce the choie. This is better than repeating the same code in multiple sections (because it makes the code shorter, easier-to-understand, easier-to-test, and easier-to-maintain).</p>\n\n<p>Also, consider precomputing the comparison logic into a <em>HashMap</em> or a 3-by-3 table.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T18:59:26.827", "Id": "11445", "ParentId": "11444", "Score": "4" } }, { "body": "<p>Naming can make code much more readable e.g if you use computerChoice and playerChoice rather than cChoice and pChoice, it's immediately more obvious what the variables are supposed to contain.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:07:59.247", "Id": "18340", "Score": "0", "body": "I figured it was pretty evident, and I've also got:\n int cChoice; // variable for computers choice (R/P/S)\n int pChoice = 0; // Holds converted choice (R=1, P=2, S=3)\nAt the top, is that not sufficient?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:14:50.917", "Id": "18341", "Score": "0", "body": "Comments are fine but good variable names are important too" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T20:21:42.667", "Id": "18348", "Score": "1", "body": "@Numpty names like `cChoice` force you to think or check the comment, introducing a tiny mental burden. These burdens add up, making code harder to understand. For instance, `hInput` confuses me - I couldn't figure out what the h stands for... furthermore `cChoice` may confuse some people into thinking it is a `char` (type information used to be encoded into the first characters of a variable name in the past). It's worth taking the time to choose good names." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:04:47.467", "Id": "11446", "ParentId": "11444", "Score": "1" } }, { "body": "<p>Refactoring parts into meaningful methods is also worthwhile, for example the line:-</p>\n\n<pre><code>if (hChoice.equals(\"R\") || hChoice.equals(\"P\") || hChoice.equals(\"S\")) // Ensures player has entered the correct choice for the game to continue\n</code></pre>\n\n<p>Could be refactored to:-</p>\n\n<pre><code>if (isValidChoice(hChoice))\n{\n... \n}\n\nprivate boolean isValidChoice(String choice)\n{\n return choice.equals(\"R\") || choice.equals(\"P\") || choice.equals(\"S\");\n}\n</code></pre>\n\n<p>This makes the code more readable.</p>\n\n<p>This type of refactoring is outlined in <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\">Clean Code</a>, which incidentally is an excellent book.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:09:28.310", "Id": "11447", "ParentId": "11444", "Score": "1" } }, { "body": "<p>You're using the variable 'loop' which has a type of String as a boolean, so just make it a boolean.</p>\n\n<p>By convention, class names should be uppercase.</p>\n\n<p>You have the following comment:</p>\n\n<blockquote>\n <p><code>// This converts pChoice to the numeric value for \"Rock\"</code></p>\n</blockquote>\n\n<p>Remember, code is written for programmers to read, and anyone that knows how to read code understands what that code does; so try not to document the what, aim to document the why. Also you've repeated it erroneously two additional times.</p>\n\n<p>You convert the input of 'R', 'P', or 'S' to ints: There's no reason to do that you could just compare the strings. A better way to do this all together would probably be to use an enum to represent player choices.</p>\n\n<pre><code> public enum Choices {\n Rock(\"R\"),\n Paper(\"P\"),\n Scissors(\"S\");\n\n // ....\n }\n</code></pre>\n\n<p>This opens up some other options for cleaning up your comparison cases further along in the program.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:13:54.180", "Id": "18343", "Score": "0", "body": "Yeah, that seems like a better way (per Strawberry). I've fixed the class name :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:32:13.357", "Id": "18344", "Score": "0", "body": "re: your edits - I've never used that before. Need to do some more reading. Thanks again" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T19:09:44.800", "Id": "11448", "ParentId": "11444", "Score": "3" } }, { "body": "<p>For your perusal, I took the liberty to clean up and simplify your code a bit.</p>\n\n<pre><code>public class RockPaperScissors\n{\n static int cScore, pScore, tie, rounds;\n\n enum RPS {\n R(\"Rock\", \"S\"), P(\"Paper\", \"R\"), S(\"Scissors\", \"P\");\n private final String beats, name;\n RPS(String name, String beats) { this.beats = beats; this.name = name; }\n int compare(RPS other) { return other == this? 0 : other == valueOf(beats)? 1 : -1; }\n String fullName() { return name; }\n }\n\n public static void main (String[] args) {\n final Scanner input = new Scanner(System.in);\n final Random rgen = new Random();\n System.out.println(\"Hello, for this exercise we're going to be playing everyone's favourite game, Rock-Paper-Scissors!\");\n while (true) {\n final RPS playerChoice, compChoice = RPS.values()[rgen.nextInt(3)];\n System.out.println(\"Please make your selection: R - Rock. P - Paper. S - Scissors\");\n try { playerChoice = RPS.valueOf(input.nextLine().toUpperCase()); }\n catch (Exception e) {\n System.out.println(\n \"Sorry, you didn't pick Rock, Paper, or Scissors. The game will end now.\\n\" +\n \"Here are the final scores after \" + rounds +\" rounds:\\nYou\\tComputer\\tTies\\n\" +\n \" \"+ pScore +\"\\t \" + cScore + \"\\t\\t \" + tie);\n return;\n }\n System.out.println(\"\\nComputer picked \" + compChoice.fullName() + \"!\");\n switch (playerChoice.compare(compChoice)) {\n case 0:\n System.out.println(\"Tie Game!\\n\");\n tie++;\n break;\n case -1:\n System.out.println(compChoice.fullName() + \" beats \" + playerChoice.fullName() + \"!\");\n System.out.println(\"**Computer Wins!**\\n\");\n cScore++;\n break;\n case 1:\n System.out.println(playerChoice.fullName() + \" beats \" + compChoice.fullName() + \"!\");\n System.out.println(\"**Player Wins!**\\n\");\n pScore++;\n }\n rounds++;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T20:12:35.580", "Id": "18347", "Score": "0", "body": "Hah, I have some learnin' to do apparently. That's significantly shorter (and easier to follow). Neat :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T20:08:41.890", "Id": "11450", "ParentId": "11444", "Score": "8" } }, { "body": "<p>To determine the outcome of a round, you have logic that depends on values. The \"logic\" basically checks all of the values and then determines the outcome.</p>\n\n<p>Such a strategy (while effective immediately) is a fragile one over time, any change in the data demands searching and updating any blocks of code that decide based on values of the data. So encapsulate the logic.</p>\n\n<pre><code>// this could be a class, abstract class, or enum, it doesn't need to be an interface\n// but Choices should probably know if they beat other Choices.\npublic interface Choice {\n\n public boolean beats(Choice other) {\n ...\n }\n\n}\n</code></pre>\n\n<p>So many people have commented on <code>Choice</code> that I'll just avoid adding extra comments past this; however, I do want to talk about the <code>Score</code> which is another \"thing\" that exists in your program, yet there is no corresponding object.</p>\n\n<pre><code>public class Score {\n\n private int games;\n\n private int wins;\n\n public Score() {\n games = 0;\n wins = 0;\n }\n\n public void update(Choice human, Choice computer) {\n games++;\n if (human.beats(computer)) {\n wins++;\n }\n }\n\n}\n</code></pre>\n\n<p>reduces your \"in the loop code to\"</p>\n\n<pre><code>Score score = new Score();\nwhile (playing) {\n Choice human = getChoice();\n Choice computer = Choices.getRandomChoice();\n score.update(human, computer);\n playing = getContinue();\n}\n</code></pre>\n\n<p>revisting the intial complaint</p>\n\n<blockquote>\n <p>To determine the outcome of a round, you have logic that depends on\n values. The \"logic\" basically checks all of the values and then\n determines the outcome.</p>\n</blockquote>\n\n<p>You can see that the new structure (which doesn't functionally do anything differently than the old structure) lacks a top-level logic that checks based on the low level data. Choices now know if they beat each other, and Scores basically update themselves based on asking the Choices. </p>\n\n<p>In the event that you needed to make a Rock-Paper-Scissor derivative, <a href=\"http://www.momsminivan.com/rock-paper-scissors-lizard-spock.html\" rel=\"nofollow\">like Rock-Paper-Scissors-Lizard-Spock</a>, you could simply modify the Choices and not need to touch how scoring works (or go searching through all of your code to see if it impacted external logic).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T22:07:52.550", "Id": "18359", "Score": "0", "body": "Thanks for taking the time to go over all of that. Also, nice RPSLS reference :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T21:08:15.313", "Id": "11452", "ParentId": "11444", "Score": "4" } } ]
{ "AcceptedAnswerId": "11450", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T18:55:56.310", "Id": "11444", "Score": "12", "Tags": [ "java", "game", "homework", "rock-paper-scissors" ], "Title": "Does my Rock Paper Scissors game look good?" }
11444
<p>This is the simplest possible implementation.</p> <p>The two lists will contain at max, 3-5 elements, so the size of lists is not a matter of concern.</p> <p>Any recommendation on how can I make this pretty?</p> <pre><code>private ListsHolder findDiffOfLists(List&lt;MyObject&gt; objsFromDB, List&lt;MyObjRequest&gt; objsFromRequest) { ListsHolder holder = this.new ListsHolder(); //An object holding two lists for(MyObjRequest req_obj : objsFromRequest){ boolean isAdded = false; for(MyObject db_obj : objsFromDB){ if(isSameObj(db_obj, req_obj)){ db_obj.setVal(req_obj.getVal()); //Set new value holder.matchingObjList.add(db_obj); isAdded = true; break; } } if(!isAdded){ holder.newObjList.add(req_obj); //If element does not exist } } return holder; } private boolean isSameObj(MyObject db_obj, MyObjRequest req_obj) { return req_obj.getMatch().equals(db_obj.getMatch()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T15:07:42.900", "Id": "18570", "Score": "0", "body": "It there an hierarchical relation between MyObject and MyObjectRequest?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T17:09:50.827", "Id": "18571", "Score": "0", "body": "no there is no relation between the two objects. They are completely different, just have some values common." } ]
[ { "body": "<p>I would create this method:</p>\n\n<pre><code>private MyObject findMatch(List&lt;MyObject&gt; objsFromDB, MyObjRequest req_obj){\n for(MyObject db_obj : objsFromDB){\n if(isSameObj(db_obj, req_obj)){\n return db_obj;\n }\n }\n return null;\n}\n</code></pre>\n\n<p>and refactor accordingly.</p>\n\n<p>Beyond that the only suggestion I would have is perhaps some better variable names (at least use a single naming style; if you don't already have one, use this: <a href=\"http://www.oracle.com/technetwork/java/codeconventions-135099.html#367\" rel=\"nofollow\">http://www.oracle.com/technetwork/java/codeconventions-135099.html#367</a>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T21:39:46.117", "Id": "18351", "Score": "0", "body": "I have proper styles in my actual code, had to obfuscate the code before posting here :) But I agree, I will update my question. Btw, returning `null` is a good practice?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T01:03:14.983", "Id": "18379", "Score": "0", "body": "I am not actually a java developer, but I don't see why it would be bad. Certainly it would not be as bad as doing extra work (iterating over the rest of the loop) when you don't need to." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T21:38:23.340", "Id": "11453", "ParentId": "11451", "Score": "2" } }, { "body": "<p>My suggestion would be to move the <code>isSameObj</code> inside the <code>MyObject</code> class as it deals with the attributes inside that object. You can override the <code>equals</code> method of <code>MyObject</code> so that the <code>equals</code> method in <code>MyObject</code> will be like</p>\n\n<pre><code>boolean equals(MyObject target){\n return this.getMatch().equals(target.getMatch());\n}\n</code></pre>\n\n<p>and the original code will become like </p>\n\n<p><code>if(db_obj.equals(req_obj))</code> instead of <code>if(isSameObj(db_obj, req_obj))</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T01:07:27.380", "Id": "18380", "Score": "2", "body": "In other words see: Law of Demeter (req_obj.getMatch().equals() is a violation)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T21:44:54.957", "Id": "11456", "ParentId": "11451", "Score": "2" } }, { "body": "<p>I would use a variation of Bill Barry's answer. Don't really see the need to return the object, when we already know it. It's a simple test function, which means you expect to get true or false from it:</p>\n\n<pre><code>private boolean isMatch(List&lt;MyObject&gt; objsFromDB, MyObjRequest req_obj){\n for(MyObject db_obj : objsFromDB){\n if(isSameObj(db_obj, req_obj)){\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>This way you don't have to have another check to see if the value returned by the function is NULL or not.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T07:00:09.503", "Id": "11468", "ParentId": "11451", "Score": "1" } } ]
{ "AcceptedAnswerId": "11453", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T20:56:48.760", "Id": "11451", "Score": "3", "Tags": [ "java" ], "Title": "An elegant way to find diff of two list of objects in Java" }
11451
<p>Just wondering if my </p> <pre><code>else {return false;} </code></pre> <p>statements are superfluous... do I just need one <code>return true;</code> here?</p> <pre><code>function has_access() { if ( is_user_logged_in() ) { $role = get_current_user_role(); $admins = array( 'Administrator', 'Agent', 'Contributor', ); if (in_array($role, $admins)) { return true; } else { return false; } } else { return false; } } </code></pre>
[]
[ { "body": "<p>I'd replace the conditions with guard clauses. (<a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\">Flattening Arrow Code</a>)</p>\n\n<pre><code>function has_access() {\n if ( !is_user_logged_in() ) {\n return false;\n }\n $role = get_current_user_role();\n $admins = array(\n 'Administrator',\n 'Agent',\n 'Contributor',\n );\n\n if (in_array($role, $admins)) {\n return true;\n }\n return false;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T21:53:44.257", "Id": "11458", "ParentId": "11455", "Score": "8" } }, { "body": "<p>This is really pointless:</p>\n\n<pre><code>if (in_array($role, $admins)) {\n return true;\n} else {\n return false;\n}\n</code></pre>\n\n<p>when you can just call</p>\n\n<pre><code>return in_array($role, $admins);\n</code></pre>\n\n<p>So:</p>\n\n<pre><code>function has_access() {\n if (!is_user_logged_in()) {\n return false;\n }\n\n $role = get_current_user_role();\n $admins = array(\n 'Administrator',\n 'Agent',\n 'Contributor',\n );\n\n return in_array($role, $admins);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-06T18:19:59.587", "Id": "124977", "ParentId": "11455", "Score": "3" } } ]
{ "AcceptedAnswerId": "11458", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T21:43:40.107", "Id": "11455", "Score": "1", "Tags": [ "php", "authorization" ], "Title": "Checking authorization by role" }
11455
<p>can someone read through this script really quick and verify that I didn't miss anything... I'm not getting any errors in my IDE so just have to make sure the structure is correct</p> <pre><code>&lt;?php require_once '/usr/local/cpanel/3rdparty/lib/php/Mail.php'; $db_server = 'localhost'; $db_user = '-----'; $db_pass = '-----'; $dbc = mysql_connect ($db_server, $db_user, $db_pass); if (!$dbc) { die(mysql_error()); header ('Location: /contact'); exit; } if ($_POST['contactsent'] != 'yes') { header ('Location: /contact'); exit; } else { if (is_array($_POST)) { foreach ($_POST as $key =&gt; $value) { $_POST[$key] = mysql_real_escape_string(stripslashes($value)); } } $RequestType = $_POST["RequestType"]; $ConsumerBusiness = $_POST["ConsumerBusiness"]; $GlobalLocation = $_POST["GlobalLocation"]; $FirstName = strtolower(str_replace("'","''",$_POST["FirstName"])); $FirstName = strtoupper(substr($FirstName,0,1)).substr($FirstName,1); $LastName = strtolower(str_replace("'","''",$_POST["LastName"])); $LastName = strtoupper(substr($LastName,0,1)).substr($LastName,1); $Email = strtolower(str_replace("'","''",$_POST["Email"])); $Title = strtolower(str_replace("'","''",$_POST["Title"])); $Title = strtoupper(substr($Title,0,1)).substr($Title,1); $Company = strtolower(str_replace("'","''",$_POST["Company"])); $Company = strtoupper(substr($Company,0,1)).substr($Company,1); $Address = strtolower(str_replace("'","''",$_POST["Address"])); $Address = strtoupper(substr($Address,0,1)).substr($Address,1); $City = strtolower(str_replace("'","''",$_POST["City"])); $City = strtoupper(substr($City,0,1)).substr($City,1); $State = $_POST["State"]; $Zip = $_POST["Zip"]; $Phone = $_POST["Phone"]; $F = $_POST["F"]; $ProductDesc = $_POST["ProductDesc"]; $Comment = $_POST["Comment"]; if ($GlobalLocation == "Canada"): $SendTo="canadainfo@------.com"; elseif ($GlobalLocation == "Central America"): $SendTo="customer.service@------.com.pa"; elseif ($GlobalLocation == "Europe"): $SendTo="marketing@-----.uk"; elseif ($GlobalLocation == "Mexico"): $SendTo="ventas@------.com.mx"; else: $SendTo="info@------.com"; endif; function dbSet($fields, $source = array()) { $set=''; if (!source) $source = &amp;$_POST; foreach ($fields as $field) { if (isset($source[$field])) { $set.="`$field`='".mysql_real_escape_string($source[$field])."', "; } } return substr($set, 0, -2); } // INSERT INTO DATABASE mysql_select_db("new_contact",$dbc) or die("Could not select new_contact"); $fields = explode(" ", "RequestType ConsumerBusiness GlobalLocation FirstName LastName Email Title Company Address City State Zip Phone F ProductDesc Comment"); $query = "INSERT INTO new_contact SET ".dbSet($fields, $_POST); mysql_query($query); // SETUP EMAIL $Bodycopy = "This information was submitted via the ------.com website and sent to you because of the location identified by the user. &lt;br&gt;If this has reached you in error, please forward this email to info@------.com"; $Bodycopy. "&lt;br&gt;----------------------------------------------------------------------------------------------&lt;br&gt;&lt;br&gt;"; if ($RequestType != "") $Bodycopy. "What kind of information do you need? : " .$RequestType. "&lt;br&gt;"; if ($ConsumerBusiness != "") $Bodycopy. "What type of customer or vendor are you? : " .$ConsumerBusiness. "&lt;br&gt;"; if ($GlobalLocation != "") $Bodycopy. "Global Location : " .$GlobalLocation. "&lt;br&gt;"; if ($Company != "") $Bodycopy. "Company : " .$Company. "&lt;br&gt;"; if ($FirstName != "") $Bodycopy. "First Name : " .$FirstName. "&lt;br&gt;"; if ($LastName != "") $Bodycopy. "Last Name : " .$LastName. "&lt;br&gt;"; if ($Title != "") $Bodycopy. "Title : " .$Title. "&lt;br&gt;"; if ($Email != "") $Bodycopy. "Email : " .$Email. "&lt;br&gt;"; if ($Address != "") $Bodycopy. "Address : " .$Address. "&lt;br&gt;"; if ($City != "") $Bodycopy. "City : " .$City. "&lt;br&gt;"; if ($State != "") $Bodycopy. "State : " .$State. "&lt;br&gt;"; if ($Zip != "") $Bodycopy. "Zip/Postal Code : " .$Zip. "&lt;br&gt;"; if ($Phone != "") $Bodycopy. "Phone : " .$Phone. "&lt;br&gt;"; if ($F != "") $Bodycopy. "F : " .$F. "&lt;br&gt;"; if ($ProductDesc != "") $Bodycopy. "UPC or product description : " .$ProductDesc. "&lt;br&gt;"; $Bodycopy. "&lt;br&gt;----------------------------------------------------------------------------------------------&lt;br&gt;&lt;br&gt;"; if ($Comment != "") $Bodycopy. "Comments : &lt;br&gt;" .$Comment. "&lt;br&gt;"; $Bodycopy. "&lt;br&gt;&lt;br&gt;"; $Bodycopy. $IP = $_SERVER["remote_addr"]; // PROCESS EMAIL // mail server info... $from = $SendTo; $to = "Do Not Reply &lt;donotreply@------&gt;"; $subject = "Website Contact : " . $GlobalLocation; $body = $Bodycopy; $host = "mail.------"; $port = "25"; $username = "donotreply@-------"; $password = "-------"; $headers = array ('From' =&gt; $from, 'To' =&gt; $to, 'Subject' =&gt; $subject); $smtp = Mail::factory('smtp', array ('host' =&gt; $host, 'auth' =&gt; true, 'port' =&gt; $port, 'username' =&gt; $username, 'password' =&gt; $password)); $mail = $smtp-&gt;send($to, $headers, $body); if (PEAR::isError($mail)) { echo("&lt;p&gt;" . $mail-&gt;getMessage() . "&lt;/p&gt;"); } else { echo("&lt;p&gt;Message successfully sent!&lt;/p&gt;"); } // MAKE SURE DB CONN IS CLOSED mysql_close($dbc); // REDIRECT TO THANK YOU PAGE header ('Location: /index.php?option'); exit(); } ?&gt; </code></pre>
[]
[ { "body": "<p>Although it'll lenghten your code quite a bit, in my opinion it's worth checking if the $_POST variables are set (using isset), to avoid any exceptions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T10:49:31.553", "Id": "11470", "ParentId": "11466", "Score": "2" } }, { "body": "<p>I don't know about real quick. What you have doesn't really compliment a quick review. First off this is procedural code, which is fine if you are just getting started, don't let anyone tell you otherwise. But procedural code is not \"quickly\" read. I will suggest that once you have a firm grasp on the language, you should definitely take a look at OOP, but not before. You may notice me throwing this OOP (Object Oriented Programming) term around a lot. I tell a lot of people that I am against pushing OOP. No, not against OOP, just against pushing it. I won't tell you to stop what you are doing and learn OOP and no one else should either. Far from it. You need a solid understanding of the language first. Whenever I mention OOP I am merely pointing out that doing those suggestions now will prepare you for it and will make more sense as you progress into OOP. So take my OOP talk with a grain of salt, follow the suggestions, but don't go out and learn it just because I mentioned it. Now on to the review. I will read your code and write my thoughts as I have them, so you will be able to follow along in your own code. There is only one spot where I jump, but after that it should all be in order.</p>\n\n<p><strong>Review</strong></p>\n\n<p>The first problem I have with your code is that it is very redundant and inefficient. When you tell a program to <code>die()</code> or <code>exit</code> or go to a different <code>header()</code>, you are telling it to stop immediately, and, if applicable, process the argument between the parenthesis. Yet you have code after that and it will not process because you've already told it to stop. Rewrite your <code>mysql_connect()</code> like so:</p>\n\n<pre><code>$dbc = mysql_connect ($db_server, $db_user, $db_pass) or die(mysql_error());\n// OR, if you want the header, remove the \"or die\" from above and use the following\nif ( ! $dbc) { header ('Location: /contact'); }\n</code></pre>\n\n<p>You'll notice I did not use the <code>mysql_error()</code> in that second instance. That is because if you load the header it will send you to a different page and you will never see it. If you want to see it on the new page, I would suggest passing it as a GET parameter. Also, careful where you throw out those <code>header()</code>'s. Headers can not be called after information has already been sent to the browser. If possible, I would suggest setting up a function to hold all of the statements that set a new header so that it is all in one place.</p>\n\n<p><strong>Checking and Sanitizing POST</strong></p>\n\n<p>As mikeythemissile said, you should be checking your globals. And not just that they are set. You should be sanitizing them as well. If you have PHP version >= 5.2, check out <code>filter_input()</code>. NEVER trust user input. Always sanitize, scrub, and blast the hell out of it in any way that you can. It is better to be overly cautious than not at all, especially when dealing with SQL. Google SQL injection, its a real thing and can cause all sorts of problems for you.</p>\n\n<p>Why are you checking if POST is an array? Of course it is, it should never not be an array. What you really want to check is if it is being used, which, if it isn't, would have thrown errors before this point. You should always check unreliable variables or arrays (GET, POST, etc...) before using them. So I would start by checking my POST like so.</p>\n\n<pre><code>if($_SERVER['REQUEST_METHOD'] == \"POST\") {//could also use isset($_POST)\n //here's an example of that filter_input method\n if(filter_input(INPUT_POST, 'contactsent', FILTER_VALIDATE_BOOLEAN) { header(Location: /contact'); }\n else {\n $new_array = array();//don't use the POST array after you have already gotten what you need from it, put it in a new array\n foreach($_POST as $key =&gt; $value) {\n $new_array[$key] = mysql_real_escape_string(stripslashes($value));\n }\n }\n}\n</code></pre>\n\n<p>I would not crunch through POST blindly like that either. You've provided an array later in your script, <code>$fields</code>, that should serve as a list of items to check. This is where I jump, by the way. Loop over the <code>$fields</code> array to get the keys to search for in the POST array. First, I would change the way you get your <code>$fields</code> array. <code>explode()</code> is an ingenious way to get an array if the data you are trying to convert is dynamic and comes in that form already. However, you have manually typed these fields, so why bother with the extra processing power required to explode it? Just make it an array.</p>\n\n<pre><code>$fields = array(\n 'RequestType',\n 'ConsumerBusiness',\n 'GlobalLocation',\n 'FirstName',\n 'LastName',\n 'Email',\n 'Title',\n 'Company',\n 'Address',\n 'City',\n 'State',\n 'Zip',\n 'Phone',\n 'F', //What is this, make you variables clear and understandable all the rest are\n 'ProductDesc',\n 'Comment'\n);\n</code></pre>\n\n<p>Now that you have this array, you can go back and do so many cool things with it. Such as getting only what you need from the POST array and ignoring everything else.</p>\n\n<pre><code>$new_array = array();\nforeach($fields as $field) {\n $new_array[$field] = filter_input(INPUT_POST, $field, FILTER_SANITIZE_STRING | FILTER_SANITIZE_STRIPPED);//another example of filter_input\n}\n</code></pre>\n\n<p>You can also use that same array to clean up your <code>dbSet()</code> function.</p>\n\n<pre><code>$set = '';\nforeach($new_array as $field =&gt; $value) {\n $set .= \"`$field`='\" . mysql_real_escape_string($value) . \"', \";\n}\n</code></pre>\n\n<p>Now, I'm not saying this code is 100%, this is just to give you ideas of how to use your code intelligently. Make your code work for you, don't work for your code. Expand upon this and you will see immediate improvement in your coding.</p>\n\n<p><strong>Repetitive Code</strong></p>\n\n<p>I really dislike this wall of variables. I would see about getting rid of it if you can. If possible try to make these changes while iterating over them with the <code>$fields</code> array or something. There is no reason for there to be this many copies of the same information. Also, why are you not using <code>ucfirst()</code>? That is obviously what you are trying to do with that strtoupper substring mess. Use the functions provided by PHP. In almost all cases they have a function to do what you want, so search for it before you reinvent it. The documentation is, pardon the repitition, well documented and easily navigable. I also would not convert a string to lowercase if not necessary, such as the email address.</p>\n\n<pre><code>$FirstName = strtolower(str_replace(\"'\",\"''\",$_POST[\"FirstName\"]));//Not sure what you are doing here so I left it.\n$FirstName = ucfirst($FirstName);\n</code></pre>\n\n<p>Don't use repetitive if/else statements, use switch statements instead. They are proven faster and are cleaner, not to mention easily extendable.</p>\n\n<pre><code>switch($GlobalLocation) {\n case 'Canada':\n $SendTo=\"canadainfo@------.com\";\n break;\n case 'Central America': \n $SendTo=\"customer.service@------.com.pa\";\n break;\n etc...\n}\n</code></pre>\n\n<p><strong>Functions</strong></p>\n\n<p>This function,<code>dbSet()</code>, just came out of no where. Because you are doing procedural code, you should make life easier on yourself and others who might eventually take over your code. Make it as easy to read as possible. The first step to this goal is placing your code logically. If you have custom functions, you should group them all together, preferably at the beginning of your program before you start your procedural code. Since you already know about require/include, I would suggest moving them to another file and requiring/including it at the very beginning. That's one of the first steps towards learning OOP, learning to separate your code, albeit in a not so OOP way, but still important...</p>\n\n<p>Also, the <code>dbSet()</code> function is redundant. You already did <code>mysql_real_escape_string()</code> and <code>stripslashes</code> to the POST array in the foreach loop earlier. You will find that you repeat yourself a lot while writing procedural code. The best cure for this is to start breaking your procedural code up into functions. Functions are the first step to learning OOP.</p>\n\n<p><strong>Concatenating Variables</strong></p>\n\n<p>You are not concatenating your variables properly. To append data to the end of a variable use <code>.=</code>. If you just use the concatenate operator <code>.</code> it will not change the variable, it will only add it to the local memory for that instance. In other words, if you were to echo it directly <code>echo $Bodycopy . 'extrastuff';</code> you would get the desired results, but since you are doing multiple instances, you will need to append it first <code>$Bodycopy .= 'extrastuff';</code>. So change the way you concatenate all of your <code>$Bodycopy</code> variables to <code>.=</code>. Also, check out heredoc, or nowdoc for long strings such as these.</p>\n\n<p><strong>If Statements</strong></p>\n\n<p>Even if it is only one line. Please, for the love of god, use braces <code>{}</code>. I know it is not necessary. I know it knocks off 2 bits of file size per statement. I know a lot of people do it. But please, DON'T. It makes reading your code so much harder without those braces and doesn't harm anything to add them. I hate that PHP allows this and really wish they would remove it in future releases. It teaches bad coding habits.</p>\n\n<p><strong>More Repetition</strong></p>\n\n<p>The first two chunks under <code>//mail server info</code> is redundant. Remove all of those variables and just set them in the $headers array. Then, if you don't want to use the array reference (<code>$headers['To']</code>) you can use <code>extract()</code> to convert all of the array references to variables.</p>\n\n<p><strong>Exit</strong></p>\n\n<p>See comment, you can ignore this section...</p>\n\n<blockquote class=\"spoiler\">\n <p> Lastly, stop using <code>exit</code>. Every single place you have used it, it is unnecessary. If you find yourself needing to stop your code like this, especially this frequently, you are doing something wrong. Mostly this extends from long procedural script and can be cured by OOP, but, in the mean time, if you just clean up your code and write it a bit more logically, you will notice that they are not necessary.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T18:45:23.673", "Id": "19016", "Score": "0", "body": "TIL: using exit after a header is actually good practice, so you can ignore that last comment. I was wrong." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T18:43:58.917", "Id": "11484", "ParentId": "11466", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T03:02:57.400", "Id": "11466", "Score": "1", "Tags": [ "php" ], "Title": "Verify $_POST script will work correctly" }
11466
<p>This is a custom effect for jQuery tools that enable caching for ajaxed tabs. Please advice on anything that I can improve. Note that I'm not sure where to put the loading indicator, so, at least have a look at that.</p> <pre><code>$.tools.tabs.addEffect("ajax_cache", function(tabIndex, done) { //check if content already loaded //if yes, display it, and hide the rest //if no, send ajax request var panes_cont = this.getPanes().eq(0); var dest_pane = panes_cont.find("#tabindex_"+tabIndex); if(dest_pane.length &gt; 0){ panes_cont.children().hide(); dest_pane.show(); } else { panes_cont.children().hide(); panes_cont.append("&lt;img id='tab_loading' src='/graphics/loading.gif' /&gt;"); var new_pane = $('&lt;div&gt;').attr('id', 'tabindex_'+tabIndex).load(this.getTabs().eq(tabIndex).attr("href"), function(){ panes_cont.find("#tab_loading").remove(); panes_cont.append(new_pane.show()); }); } done.call(); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T22:11:47.567", "Id": "18438", "Score": "0", "body": "Instead of giving the loading image an id and then traversing for it, you should make it a cached jquery object." } ]
[ { "body": "<p>From a once over : </p>\n\n<ul>\n<li>Whether the content is loaded or not, you call <code>panes_cont.children().hide();</code>, you might as well centralize that 1 call </li>\n<li>There is too much going on in the creation of <code>new_pane</code>, it ought to be split up.</li>\n<li>lowerCamelCasing is good for you, also write out things. <code>cont</code> keeps reminding me of <code>continue</code> whereas you probably mean <code>content</code></li>\n<li>I prefer the line of comment on top of the function</li>\n<li>There is no need to check <code>length &gt; 0</code>, you can simply check for <code>length</code></li>\n<li>As Bill Barry pointed out, caching the loader image is more efficient</li>\n<li>Most recent js standards suggest to put strings in single quotes, whichever way you go, you should be consistent for easy reading.</li>\n</ul>\n\n<p>All the above together gives this:</p>\n\n<pre><code>//check if pane already loaded, if so, display it, otherwise send ajax\n$.tools.tabs.addEffect(\"ajax_cache\", function(tabIndex, done)\n{\n var allPanes = this.getPanes().eq(0).hide(),\n targetPane = allPanes.find(\"#tabindex_\"+tabIndex);\n\n if(targetPane.length)\n {\n targetPane.show();\n } \n else \n {\n var loaderImage = allPanes.append('&lt;img id=\"tab_loading\" src=\"/graphics/loading.gif\"/&gt;'),\n newPane = $('&lt;div&gt;').attr('id', 'tabindex_'+tabIndex),\n URL = this.getTabs().eq(tabIndex).attr('href');\n\n newPane.load(URL, function(){\n loaderImage.remove();\n allPanes.append(newPane.show());\n });\n }\n done.call();\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T23:52:03.047", "Id": "40645", "ParentId": "11467", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T04:16:15.907", "Id": "11467", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "jQueryTools plugin custom effect for caching ctabs" }
11467
<p>I'm writing a form that contains 2 ListViews with a set of 4 buttons. 2 move all the items from one to the other in each direction, the other move only selected items in each direction.</p> <p>Nothing fancy or complicated.</p> <p>However I'm feeling like I could write the MoveItem method in a more elegant way and was wondering if any would mind taking a look and advising me.</p> <pre><code>private void MoveItem(ListView source, ListView dest, bool all) { if (all) { foreach (ListViewItem item in source.Items) { source.Items.Remove(item); dest.Items.Add(item); } } else { foreach (ListViewItem item in source.SelectedItems) { source.Items.Remove(item); dest.Items.Add(item); } } } </code></pre> <p>Any suggestions would be thankfully recived</p>
[]
[ { "body": "<p>Before thinking about how to write this in a more elegant way, you should first ask yourself: is this code actually correct? The “problem” with that code is that you're iterating the collection you're modifying. Quite often (for example in the case of <code>List&lt;T&gt;</code>), that's not allowed and your <code>foreach</code> would throw an exception. Fortunately for you, the enumerator of <code>ListViewItemCollection</code> iterates over a <em>snapshot</em> of the collection of the items, so your code will actually work fine (although I didn't find this behavior documented anywhere).</p>\n\n<p>Now, if you want to refactor code like this, just have a look at what's the same and what's different. You can notice that the only different thing in the two branches is the source of the <code>foreach</code>. So, just create a local variable for it, set it correctly and then have common code that iterates it:</p>\n\n<pre><code>private static void MoveItem(ListView source, ListView dest, bool all)\n{\n var items = all ? source.Items : source.SelectedItems;\n\n foreach (ListViewItem item in items)\n {\n source.Items.Remove(item);\n dest.Items.Add(item);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T12:20:41.210", "Id": "18390", "Score": "0", "body": "So would I be correct in thinking that with a normal list that doesn't create a snapshot the best solution would be to create my own copy of the items and then add/remove them? That refactoing was just what I was trying to do and failing as `SelectedItems` and `Items` are different types that don't inherit from a common base class but do implement `IList`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T12:21:42.297", "Id": "18391", "Score": "0", "body": "Yeah, exactly. And the easiest way to create that snapshot is using `ToArray()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T14:56:37.100", "Id": "18396", "Score": "0", "body": "Does this work? Modifying a list while looping over it don't cause an exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T15:02:08.273", "Id": "18397", "Score": "0", "body": "@mmdemirbas, like I said, in this specific case it *does* work, because `ListViewItemCollection` creates a snapshot before you start iterating and then you iterate over that snapshot. Because of that, it's safe and it does work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:23:02.340", "Id": "18404", "Score": "0", "body": "If you need to iterate and change, you can either repeatedly use-and-remove the first item until the list is empty, or do a `for(int i=list.Count-1; i>=0; i--) { ... }`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T22:06:28.010", "Id": "18437", "Score": "1", "body": "I would say that even though it does work and is safe, the code looks like it is modifying an existing collection and is thus better written with an explicit snapshot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T22:21:13.827", "Id": "18439", "Score": "0", "body": "@BillBarry, I agree. When I first looked at the code, I thought it's incorrect and it surprised me it actually work. Surprising code is not good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-09T21:14:05.667", "Id": "176171", "Score": "1", "body": "How does this work? My code won't compile because it doesn't know what `items` should be. `Type of conditional expression cannot be determined because there is no implicit conversion between 'ListView.ListViewItemCollection' and 'ListView.SelectedListViewItemCollection'` .NET 4.0" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T11:42:26.120", "Id": "11472", "ParentId": "11469", "Score": "5" } }, { "body": "<p>Easier:</p>\n\n<p>item.Remove &lt;-- will remove item from the ListView it is currently assigned\nDestinationList.Items.Add(item);</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-20T14:21:31.170", "Id": "26371", "ParentId": "11469", "Score": "1" } } ]
{ "AcceptedAnswerId": "11472", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T10:40:28.103", "Id": "11469", "Score": "5", "Tags": [ "c#", "winforms" ], "Title": "Moving List View items from one list to another" }
11469
<p>I'd like to know if this is the right syntax for using cookies. I haven't yet tested this code with cookies being used.</p> <p>I'm using a jQuery Plugin called <a href="http://luis-almeida.github.com/jPages/" rel="nofollow">jPages</a> to display pages on my (one page) website, it has a lot of options and it's very flexible. </p> <p>The jPages plugin has an option to start from a different page per say, and a callback function to find what page you are currently on.</p> <p>I'm using <code>localStorage</code> to store the last page that a visitor has been on so that it can be retrieved when they return. I've tested this method and it works perfectly.</p> <p>I'm using Modernizr to test for <code>localStorage</code> support in browsers, and if <code>localStorage</code> is not supported I use cookies to try and achieve the same experience.</p> <p>Here's the part of my code that does that:</p> <pre><code>var set_data = function(cluster) { if (!localStorage.getItem("Page")) { if (!localStorage.setItem("Page", JSON.stringify(cluster))) { log("Current Page: Stored"); } else { log("Current Page: Store Failed"); } } else { localStorage.removeItem("Page"); if (!localStorage.setItem("Page", JSON.stringify(cluster))) { log("Current Page: Stored"); } else { log("Current Page: Store Failed"); } } } var get_data = function() { if (localStorage.getItem("Page")) { var last_page = JSON.parse(localStorage.getItem("Page")) log("Last Page: " + last_page); return last_page; } else { log("Last Page: Inexistent"); return 1; } } var set_last_page = function(cluster) { if (Modernizr.localstorage) { var data = cluster; set_data(data); } else { var data = JSON.stringify(cluster); create_cookie("Page", data, 365); } } var get_current_page = function() { if (Modernizr.localstorage) { var data = get_data(); } else { var data = JSON.parse(read_cookie("Page")); } return data; } var create_cookie = function(name, value, days) { var date; var expires; if (days) { date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = name + "=" + value + expires + "; path=/"; } var read_cookie = function(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); var i; var c; for (i = 0; i &lt; ca.length; i++) { c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } </code></pre> <p>The <code>localStorage</code> part works, but I'm not sure if I'm doing the cookie part correctly.</p> <p><strong>If someone can tell me if this is the right syntax for using cookies, I would appreciate it.</strong></p>
[]
[ { "body": "<p>At the expense of having a little more code, I would use a <a href=\"https://gist.github.com/2398893/d6327b3ca7b7c50d3f4f784e06bac76cf649fe0f\" rel=\"nofollow\">localStorage polyfill</a> <a href=\"https://developer.mozilla.org/en/DOM/Storage#localStorage\" rel=\"nofollow\">[2]</a>.</p>\n\n<p>With that code in place you no longer need to keep the create and read cookie methods. You also don't need the code wrapping <code>get_data</code> and <code>set_data</code>. Your resulting code would look something like this:</p>\n\n<pre><code>set_last_page = function(cluster) {\n if (!localStorage.getItem(\"Page\")) {\n if (!localStorage.setItem(\"Page\", JSON.stringify(cluster))) {\n log(\"Current Page: Stored\");\n } else {\n log(\"Current Page: Store Failed\");\n }\n } else {\n localStorage.removeItem(\"Page\");\n if (!localStorage.setItem(\"Page\", JSON.stringify(cluster))) {\n log(\"Current Page: Stored\");\n } else {\n log(\"Current Page: Store Failed\");\n }\n }\n}\n\nget_current_page = function() {\n if (localStorage.getItem(\"Page\")) {\n var last_page = JSON.parse(localStorage.getItem(\"Page\"))\n log(\"Last Page: \" + last_page);\n return last_page;\n } else {\n log(\"Last Page: Inexistent\");\n return 1;\n }\n}\n</code></pre>\n\n<p>From here I would make a few changes:</p>\n\n<ol>\n<li>You don't need to check for existence or remove an item from storage to change it. </li>\n<li>The logging code is unnecessary.</li>\n<li>Using <code>JSON.stringify</code> and <code>JSON.parse</code> is considerable overkill for converting between a string and a number.</li>\n</ol>\n\n<p>Taking care of these would leave me with this code:</p>\n\n<pre><code>set_last_page = function(cluster) {\n localStorage.setItem(\"Page\", cluster+'');\n}\n\nget_current_page = function() {\n return +(localStorage.getItem(\"Page\") || 1); \n //localStorage.getItem(\"Page\") will return either \n // a number &gt;= 1 (as a string), undefined or null \n //so '|| 1' will take care of the latter cases\n}\n</code></pre>\n\n<p>Finally, I dislike the fact you are initializing these variables as function expressions (statements) and don't end them with semicolons (either add the semis or make them function declarations). I would also rename things to be more consistent and in line with my preferred naming conventions for javascript:</p>\n\n<pre><code>function setPage(page) {\n localStorage.setItem('page', page+'');\n}\n\nfunction getPage() {\n return +(localStorage.getItem('page') || 1); \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T19:15:48.823", "Id": "18422", "Score": "0", "body": "I did not knew that the `localStorage` behaves the same way as cookies when it comes to overwrite, so this means I do not need to remove it each time I have a new values for it ? I'm doing the logging because I'm testing now and I like seeing in the console if there's something happening, after I'm done with the testing I remove all the console outputs. And about JSON, I've read that it's best to use it, as the polyfill does too. And I like having the variables as expressions rather than just simple functions :) But that's just me I guess. Thanks for the response, I appreciate it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T19:18:51.697", "Id": "18423", "Score": "0", "body": "Oh, so, if I use the polyfill, I'll end up using only those last two functions by your description, right ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T21:52:09.260", "Id": "18436", "Score": "0", "body": "@Roland, correct (you only nee those last two functions, and it behaves the same way as cookies)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T19:01:14.230", "Id": "11486", "ParentId": "11471", "Score": "1" } } ]
{ "AcceptedAnswerId": "11486", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T11:07:05.683", "Id": "11471", "Score": "1", "Tags": [ "javascript" ], "Title": "Is this correct way to use cookies from a syntax point of view?" }
11471
<h1>Description</h1> <p>I'm writing a program that makes changes to a few Python source files--creating some, and appending content to others. Since some changes depend on others, I check frequently to make sure everything is going smoothly (try importing the modified file, etc). I would like to revert any and all changes my program has made if it encounters a problem.</p> <p>I decided the best way of going about doing this would be to use an Action class, with methods to perform and reverse the changes (like migrations in Django's South, or Rails migrations). An ActionManager class performs each action in turn, and if any fail, reverts them in the reverse order. </p> <h1>Dilemma</h1> <p>The code I wrote appears to be working fine. However, I have three problems with it:</p> <ol> <li><p>The section marked <code>???</code> in the code below seems like it is faulty. Are there any conditions where this would break? If so, is there a better way?</p></li> <li><p>I am not 100% sure all changes will be reversed if, say, an exception occurs. If possible, I want to make sure all changes are reverted even if the program is interrupted midway. I believe my exception handling is flimsy at best, faulty at worst. Any advice appreciated.</p></li> <li><p>The API is atrocious. Specifying a manager every time an action is initialized seems tedious, and so does calling <code>super</code> in every action method. Is there a more elegant solution?</p></li> </ol> <p>Any and all advice on the above or anything else in the source below is appreciated.</p> <h1>Code</h1> <h2>Base Classes</h2> <pre><code>#-*- coding: utf-8 -*- import errno import os import shutil import tempfile class FileAction(object): """A reversible action performed on the filesystem.""" def __init__(self, mgr, origfile): self.manager = mgr self.manager.pending_actions.append(self) self.origfile = origfile def execute(self): """Perform action. Return a Boolean indicating whether action was successful or not. """ filename = os.path.basename(self.origfile) # ??? - Append object id to filename in order to make sure # two actions can modify the same file without colliding. action_id = str(id(self)) dst = os.path.join(self.manager.tmpdir, filename + action_id) if os.path.isfile(dst): raise OSError( errno.EPERM, 'File already exists at {0}.'.format(dst)) return False else: shutil.copy2(self.origfile, dst) self.tmpfile = dst return True def revert(self): """Undo action.""" shutil.copy2(self.tmpfile, self.origfile) def cleanup(self): """Remove any temporary files.""" try: os.remove(self.tmpfile) except: raise return False else: return True class FileActionManager(object): def __init__(self): """Create temporary directory used by actions.""" self.executed_actions = [] self.pending_actions = [] def execute(self): """Perform all actions, return Boolean indicating their success.""" self.tmpdir = tempfile.mkdtemp() for action in self.pending_actions: is_success = action.execute() self.pending_actions.remove(action) self.executed_actions.append(action) if not is_success: self.revert() return False return self.cleanup() def revert(self): return all([a.revert() for a in reversed(self.executed_actions)]) def cleanup(self): """Remove all temporary files.""" is_success = all([a.cleanup() for a in self.executed_actions]) try: os.rmdir(self.tmpdir) except: raise return False else: if is_success: self.executed_actions = [] self.pending_actions = [] return is_success </code></pre> <h2>Sample Usage</h2> <pre><code>#!/usr/bin/env python #-*- coding: utf-8 -*- import time from actionmanager import FileAction, FileActionManager class AppendTimestampAction(FileAction): def execute(self): if super(AppendTimestampAction, self).execute(): with open(self.origfile, 'a') as f: f.write(str(time.time()) + '\n') return True return False class FailingAction(FileAction): def execute(self): super(FailingAction, self).execute() return False def main(): target_file = 'target.txt' mgr = FileActionManager() AppendTimestampAction(mgr, target_file) AppendTimestampAction(mgr, target_file) mgr.execute() # =&gt; file includes two timestamps AppendTimestampAction(mgr, target_file) FailingAction(mgr, target_file) mgr.execute() # =&gt; file has timestamp appended, but is then reverted due to failure if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>A common way to do this sort of thing is with the <a href=\"http://en.wikipedia.org/wiki/Command_pattern\" rel=\"nofollow\">Command pattern</a>, implementing Undo.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T16:05:48.460", "Id": "18401", "Score": "0", "body": "Thanks for the link! So, based on the Python example in the wiki article, in my case the action would be the `Receiver`, and the manager is the `Invoker`, and I would make another class with an undo method to act as the `Client`, correct? I suppose I sort of indadvertedly implemented something like this pattern, as I'm \"keep[ing] a stack of the most recently executed commands\". How would I better adapt my program to this pattern, and what would be the benefits?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T16:20:13.777", "Id": "18403", "Score": "0", "body": "He's already using the command pattern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T13:19:55.423", "Id": "18525", "Score": "1", "body": "@modocache, sorry for the delayed response. The answers to your first questions are yes. I didnt see it that clearly when I posted my answer. If you have the opportunity, consider renaming the method/class names to model the design pattern. I think Winston helped answering your last question. If you naturally designed the code to follow the pattern, then that's usually a sign that you are doing things correctly. When I started learning about patterns, there were many that I recognized as having used/implemented without realizing it :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T15:35:59.463", "Id": "11475", "ParentId": "11473", "Score": "2" } }, { "body": "<pre><code>#-*- coding: utf-8 -*-\n\nimport errno\nimport os\nimport shutil\nimport tempfile\n\n\nclass FileAction(object):\n \"\"\"A reversible action performed on the filesystem.\"\"\"\n\n def __init__(self, mgr, origfile):\n</code></pre>\n\n<p>I'd avoid abbrevations like <code>mgr</code> and <code>origfile</code> just use the full names</p>\n\n<pre><code> self.manager = mgr\n self.manager.pending_actions.append(self)\n self.origfile = origfile\n\n def execute(self):\n \"\"\"Perform action.\n\n Return a Boolean indicating whether action\n was successful or not.\n \"\"\"\n filename = os.path.basename(self.origfile)\n # ??? - Append object id to filename in order to make sure\n # two actions can modify the same file without colliding.\n</code></pre>\n\n<p><code>id</code> is guaranteed to be unique for living objects. The only way you get could a collision is if an object was destroyed. But that won't happen in your case here. However, <code>id</code> is a performance problem on some alternative versions of python, such as PyPy. I'd keep a count on your manager object, and use that to assign numbers.</p>\n\n<pre><code> action_id = str(id(self))\n dst = os.path.join(self.manager.tmpdir, filename + action_id)\n\n if os.path.isfile(dst):\n raise OSError(\n errno.EPERM, 'File already exists at {0}.'.format(dst))\n return False\n</code></pre>\n\n<p>You seem confused about how exceptions work. You can either have an exception or a return value, you can't have both. The exception skips the rest of the function, the return will never be executed</p>\n\n<pre><code> else:\n shutil.copy2(self.origfile, dst)\n self.tmpfile = dst\n\n return True\n\n def revert(self):\n \"\"\"Undo action.\"\"\"\n shutil.copy2(self.tmpfile, self.origfile)\n\n def cleanup(self):\n \"\"\"Remove any temporary files.\"\"\"\n try:\n os.remove(self.tmpfile)\n except:\n raise\n</code></pre>\n\n<p>Don't catch exceptions just to reraise it. </p>\n\n<pre><code> return False\n else:\n return True\n</code></pre>\n\n<p>This code is equivalant to</p>\n\n<pre><code>os.remove(self.tmpfile)\nreturn True \n</code></pre>\n\n<p>However, you probably don't actually need to return anything. Just use exceptions to indicate errors.</p>\n\n<pre><code>class FileActionManager(object):\n def __init__(self):\n \"\"\"Create temporary directory used by actions.\"\"\"\n self.executed_actions = []\n self.pending_actions = []\n\n def execute(self):\n \"\"\"Perform all actions, return Boolean indicating their success.\"\"\"\n self.tmpdir = tempfile.mkdtemp()\n\n for action in self.pending_actions:\n is_success = action.execute()\n</code></pre>\n\n<p>You don't handle the exceptions this might throw. In fact, is_success will never actually be False since in those cases exceptions are thrown.</p>\n\n<pre><code> self.pending_actions.remove(action)\n</code></pre>\n\n<p>You shouldn't modify a list while you are executing over it. You might want to do something like:</p>\n\n<pre><code>while self.pending_actions:\n action = self.pending_actions.pop(0)\n ...\n</code></pre>\n\n<p>That way iteration is safe, and the objects are removed from the list naturally</p>\n\n<pre><code> self.executed_actions.append(action)\n</code></pre>\n\n<p>If the action failed, should you record it as executed and then try to revert it?</p>\n\n<pre><code> if not is_success:\n self.revert()\n return False\n\n return self.cleanup()\n\n def revert(self):\n return all([a.revert() for a in reversed(self.executed_actions)])\n</code></pre>\n\n<p>Using an expression like this for side-effects is confusing. List comprehensions are usually not used for performing actions. </p>\n\n<pre><code> def cleanup(self):\n \"\"\"Remove all temporary files.\"\"\"\n is_success = all([a.cleanup() for a in self.executed_actions])\n\n try:\n os.rmdir(self.tmpdir)\n except:\n raise\n return False\n</code></pre>\n\n<p>Again, this doesn't work.</p>\n\n<pre><code> else:\n if is_success:\n self.executed_actions = []\n self.pending_actions = []\n return is_success\n</code></pre>\n\n<p>The biggest point is that you clearly don't understand how exceptions operate. You'll want to review that. </p>\n\n<p>While the command pattern is a useful implementation technique, its an annoying api. A better api would look something like</p>\n\n<pre><code>with FileTransaction() as transaction:\n with transaction.open(\"foo.txt\",\"a\") as foo:\n foo.write(\"Something to append\")\n with transaction.open(\"bar.txt\") as bar:\n bar.write(\"new content\")\n\n raise Exception(\"Oops!\")\n</code></pre>\n\n<p>Where the open method looks something like</p>\n\n<pre><code>def open(filename, mode):\n action = FileAction(filename, mode)\n action.pre_execute() # makes the temporary copy of the file\n self.actions.append(action)\n return open(filename, mode)\n</code></pre>\n\n<p>By making your FileTransaction() object a context manager, you can detect when you leave the if block in an exception. In that case, go through <code>self.actions</code> and revert all the changes. If you leave without an exception, commit all the changes.</p>\n\n<p>Don't use <code>return True</code> or <code>return False</code> to indicate errors. Only use exceptions to indicate failures.</p>\n\n<p>I decided to take a stab at implementing my approach. Here is what results:</p>\n\n<pre><code>import tempfile\nimport os.path\nimport shutil\n\nclass FileModification(object):\n def __init__(self, transaction, filename):\n self.transaction = transaction\n self.filename = filename\n self.backup_path = None\n\n def execute(self):\n self.backup_path = self.transaction.generate_path()\n shutil.copy2(self.filename, self.backup_path)\n\n def rollback(self):\n shutil.copy2(self.backup_path, self.filename)\n\n def commit(self):\n os.remove(self.backup_path)\n\nclass FileCreation(object):\n def __init__(self, transaction, filename):\n self.transaction = transaction\n self.filename = filename\n\n def execute(self):\n pass\n\n def commit(self):\n pass\n\n def rollback(self):\n os.remove(self.filename)\n\nclass FileTransaction(object):\n\n def __init__(self):\n self.log = []\n self.counter = 0\n self.temp_directory = tempfile.mkdtemp()\n\n def generate_path(self):\n self.counter += 1\n return os.path.join(self.temp_directory, str(self.counter))\n\n def rollback(self):\n for entry in self.log:\n entry.rollback()\n\n def commit(self):\n for entry in self.log:\n entry.commit()\n\n def __enter__(self):\n return self\n\n def __exit__(self, error_type, error_value, error_traceback):\n if error_type is None:\n self.commit()\n else:\n self.rollback()\n\n def open(self, filename, mode):\n if os.path.exists(filename):\n modification = FileModification(self, filename)\n else:\n modification = FileCreation(self, filename)\n modification.execute()\n self.log.append(modification)\n return open(filename, mode)\n</code></pre>\n\n<p>A few things could still use some help here:</p>\n\n<ol>\n<li>What if an exception is raised by a rollback or commit method?</li>\n<li>What if the user calls os.chdir()?</li>\n<li>What if the user neglects to close a file until have the transaction has been rolled back or comitted?</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T16:46:49.047", "Id": "11478", "ParentId": "11473", "Score": "2" } } ]
{ "AcceptedAnswerId": "11478", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T14:21:13.380", "Id": "11473", "Score": "1", "Tags": [ "python", "design-patterns" ], "Title": "Performing a chain of mutually dependent actions, and reversing in case of failure" }
11473
<p>I have many-to-many mapping with extra columns in the join table. The table structure looks like this:</p> <pre><code>table vendor{vendor_id, vendor_name, vendor_password, etc...} table student{student_id, student_name, student_password, etc..} table test{test_id, test_subject, test_price,test_level, etc..} </code></pre> <p>Relations as follows:</p> <pre><code>vendor to test --&gt; many-to-many student to test --&gt; many-to-many </code></pre> <p>The link:</p> <pre><code>table vendor_student_test{vendor_id, student_id, test_id, purchasedDate, assignedDate, writtenDate, result} </code></pre> <p>I've created POJO classes as follows:</p> <p><strong>Vendor.java</strong></p> <pre><code>public class Vendor { private Long vendorId; private String vendorName; private String vendorPassword; private Set&lt;VendorStudentTest&gt; tests; private boolean isVendorActivate; public boolean isVendorActivate() { return isVendorActivate; } public void setVendorActivate(boolean isVendorActivate) { this.isVendorActivate = isVendorActivate; } public Set&lt;VendorStudentTest&gt; getTests() { return tests; } public void setTests(Set&lt;VendorStudentTest&gt; tests) { this.tests = tests; } public Long getVendorId() { return vendorId; } public void setVendorId(Long vendorId) { this.vendorId = vendorId; } public String getVendorName() { return vendorName; } public void setVendorName(String vendorName) { this.vendorName = vendorName; } public String getVendorPassword() { return vendorPassword; } public void setVendorPassword(String vendorPassword) { this.vendorPassword = vendorPassword; } } </code></pre> <p><strong>Student.java</strong></p> <pre><code>public class Student { private Long studentId; private String studentName; private String studentPassword; private Set&lt;VendorStudentTest&gt; tests; public Set&lt;VendorStudentTest&gt; getTests() { return tests; } public void setTests(Set&lt;VendorStudentTest&gt; tests) { this.tests = tests; } public Long getStudentId() { return studentId; } public void setStudentId(Long studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentPassword() { return studentPassword; } public void setStudentPassword(String studentPassword) { this.studentPassword = studentPassword; } } </code></pre> <p><strong>Test.java</strong></p> <pre><code>public class Test{ private Long testId; private String testSubject; private int testTotalNoOfQuestions; private double testPrice; public Long getTestId() { return testId; } public void setTestId(Long testId) { this.testId = testId; } public String getTestSubject() { return testSubject; } public void setTestSubject(String testSubject) { this.testSubject = testSubject; } public int getTestTotalNoOfQuestions() { return testTotalNoOfQuestions; } public void setTestTotalNoOfQuestions(int testTotalNoOfQuestions) { this.testTotalNoOfQuestions = testTotalNoOfQuestions; } public double getTestPrice() { return testPrice; } public void setTestPrice(double testPrice) { this.testPrice = testPrice; } public int getTestLevel() { return testLevel; } public void setTestLevel(int testLevel) { this.testLevel = testLevel; } public Set&lt;Question&gt; getTestQuestions() { return testQuestions; } public void setTestQuestions(Set&lt;Question&gt; testQuestions) { this.testQuestions = testQuestions; } private int testLevel; private Set&lt;Question&gt; testQuestions; } </code></pre> <p><strong>VendorStudentTest.java</strong></p> <pre><code>public class VendorStudentTest { private VendorStudentTestPK vendorStudentTestPK; private Date assignedDate; private Date purchasedDate; private Date writtenDate; private double result; public VendorStudentTestPK getVendorStudentTestPK() { return vendorStudentTestPK; } public void setVendorStudentTestPK(VendorStudentTestPK vendorStudentTestPK) { this.vendorStudentTestPK = vendorStudentTestPK; } public Date getAssignedDate() { return assignedDate; } public void setAssignedDate(Date assignedDate) { this.assignedDate = assignedDate; } public Date getPurchasedDate() { return purchasedDate; } public void setPurchasedDate(Date purchasedDate) { this.purchasedDate = purchasedDate; } public Date getWrittenDate() { return writtenDate; } public void setWrittenDate(Date writtenDate) { this.writtenDate = writtenDate; } public double getResult() { return result; } public void setResult(double result) { this.result = result; } } </code></pre> <p><strong>VendorStudentTestPK.java</strong></p> <pre><code>public class VendorStudentTestPK { private Vendor vendor; private Student student; private Test test; public VendorStudentTestPK() { super(); // TODO Auto-generated constructor stub } public VendorStudentTestPK(Vendor vendor, Student student, Test test) { super(); this.vendor = vendor; this.student = student; this.test = test; } public Vendor getVendor() { return vendor; } public void setVendor(Vendor vendor) { this.vendor = vendor; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public Test getTest() { return test; } public void setTest(Test test) { this.test = test; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((student == null) ? 0 : student.hashCode()); result = prime * result + ((test == null) ? 0 : test.hashCode()); result = prime * result + ((vendor == null) ? 0 : vendor.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof VendorStudentTestPK)) return false; VendorStudentTestPK other = (VendorStudentTestPK) obj; if (student == null) { if (other.student != null) return false; } else if (!student.equals(other.student)) return false; if (test == null) { if (other.test != null) return false; } else if (!test.equals(other.test)) return false; if (vendor == null) { if (other.vendor != null) return false; } else if (!vendor.equals(other.vendor)) return false; return true; } } </code></pre> <p>Hibernate mapping files as follows:</p> <p><strong>vendor.hbm.xml</strong></p> <pre><code>&lt;class name="Vendor" table="vendor"&gt; &lt;id name="vendorId" type="long" column="vendor_id"&gt; &lt;generator class="increment"/&gt; &lt;/id&gt; &lt;property name="vendorName" column="vendor_name" type="string"/&gt; &lt;property name="vendorPassword" column="vendor_password" type="string"/&gt; &lt;set name="tests" table="vendor_student_test" inverse="true" lazy="true" fetch="select"&gt; &lt;key&gt; &lt;column name="vendor_id" not-null="true" /&gt; &lt;/key&gt; &lt;one-to-many class="VendorStudentTest" /&gt; &lt;/set&gt; &lt;/class&gt; </code></pre> <p><strong>vendor_student_test.hbm.xml</strong></p> <pre><code>&lt;class name="Vendor" table="vendor"&gt; &lt;composite-id name="vendorStudentTestPK" class="com.onlineexam.model.VendorStudentTestPK"&gt; &lt;key-property name="vendorId" column="vendor_id" type="java.lang.Long" /&gt; &lt;key-property name="studentId" column="student_id" type="java.lang.Long" /&gt; &lt;key-property name="testId" column="test_id" type="java.lang.Long" /&gt; &lt;/composite-id&gt; &lt;many-to-one name="vendor" class="Vendor" insert="false" update="false"/&gt; &lt;many-to-one name="student" class="Student" insert="false" update="false"/&gt; &lt;many-to-one name="test" class="Test" insert="false" update="false"/&gt; &lt;/class&gt; </code></pre> <p><strong>student.hbm.xml</strong></p> <pre><code>&lt;class name="Student" table="student"&gt; &lt;id name="studenId" type="long" column="student_id"&gt; &lt;generator class="increment"/&gt; &lt;/id&gt; &lt;property name="studentName" column="student_name" type="string"/&gt; &lt;property name="studentPassword" column="student_password" type="string"/&gt; &lt;set name="tests" table="vendor_student_test" inverse="true" lazy="true" fetch="select"&gt; &lt;key&gt; &lt;column name="student_id" not-null="true" /&gt; &lt;/key&gt; &lt;one-to-many class="VendorStudentTest" /&gt; &lt;/set&gt; &lt;/class&gt; </code></pre> <p><strong>test.hbm.xml</strong></p> <pre><code>//this is mapped to other table </code></pre> <p>I am new to hibernate. Is this correct mapping?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T06:18:21.910", "Id": "26081", "Score": "0", "body": "I think you will find the solution in this link http://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T10:38:57.633", "Id": "26082", "Score": "0", "body": "thaks alot Anil Kumar, but have to do with hbm mappings, can u tell me above mapping is correct or not?" } ]
[ { "body": "<p>I'm not familiar with Hibernate mappings, so just some other notes about the code:</p>\n\n<ol>\n<li><p>Calling a class <code>Test</code> could be a disadvantage later. Build frameworks/tools could recognize your class erroneously as a JUnit test class. Although this might be the proper term in your domain I would still consider using a synonym.</p></li>\n<li><p>It's confusing that some fields are at the end of the class, like these:</p>\n\n<pre><code>private int testLevel;\nprivate Set&lt;Question&gt; testQuestions;\n</code></pre>\n\n<p>(<a href=\"http://www.oracle.com/technetwork/java/codeconventions-141855.html#1852\" rel=\"nofollow noreferrer\">Java Coding Conventions, 3.1.3 Class and Interface Declarations</a>)</p></li>\n<li><p>Instead of </p>\n\n<pre><code>boolean isVendorActivate;\n</code></pre>\n\n<p>I'd consider an enum. Enums are easier to read (you don't have to remember what true or false means) and later you might have other states which only need a new enum value (it's easier to extend).</p></li>\n<li><pre><code>double result;\n</code></pre>\n\n<p>Are you sure that you want to use floating point values here? Floating point numbers are not precise, consider using a <code>BigDecimal</code>.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/3730019/843804\">Why not use Double or Float to represent currency?</a></li>\n<li><em>Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required</em></li>\n</ul></li>\n<li><p>About the comment:</p>\n\n<pre><code>public VendorStudentTestPK() {\n super();\n // TODO Auto-generated constructor stub\n}\n</code></pre>\n\n<p>If you have something to do then do it, otherwise remove the comment. It's just noise. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p><code>VendorStudentTestPK</code> implements <code>hashCode</code> and <code>equals</code> and they call <code>Student</code>'s, <code>Test</code>'s and <code>Vendor</code>'s <code>hashCode</code>/<code>equals</code> but none of these classes implements <code>hashCode</code> nor <code>equals</code>. Are you sure that they shouldn't have <code>hashCode</code> and <code>equals</code>?</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T17:04:43.423", "Id": "42880", "ParentId": "11474", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T14:48:44.307", "Id": "11474", "Score": "4", "Tags": [ "java", "beginner", "hibernate" ], "Title": "Many-to-many hibernate mapping if link table is having extra columns mappings" }
11474
<p>The following method is designed to display what we owe to a vendor based on 5 buckets. Basically, an aged trial balance (totals only). It also needs to be able to display the data based on any date. It shows me what the trial balance would have looked like on April 1st. By default it displays based on the date that it is run. The <code>if</code> and <code>elif</code> branching "smells".</p> <pre><code>def _get_balances(self,ref_date=None): if not ref_date: ref_date = datetime.date.today() totals = [Decimal('0.0'),Decimal('0.0'),Decimal('0.0'),Decimal('0.0'),Decimal('0.0')] for invoice in self.invoices: if invoice.date: payments = Decimal('0.0') for payment in invoice.payments: if payment.check.date &lt;= ref_date: payments += payment.amount invoice_total = invoice.amount - payments if invoice.date &gt;= ref_date - relativedelta(days=29): totals[0] += invoice_total elif invoice.date &lt;= ref_date - relativedelta(days=30) and \ invoice.date &gt;= ref_date - relativedelta(days=43): totals[1] += invoice_total elif invoice.date &lt;= ref_date - relativedelta(days=44) and \ invoice.date &gt;= ref_date - relativedelta(days=47): totals[2] += invoice_total elif invoice.date &lt;= ref_date - relativedelta(days=48) and \ invoice.date &gt;= ref_date - relativedelta(days=59): totals[3] += invoice_total elif invoice.date &lt;= ref_date - relativedelta(days=60): totals[4] += invoice_total return tuple(totals) </code></pre>
[]
[ { "body": "<p>I wrote methods for determining if the date falls within the desired range. This doesn't really solve the cluster of <code>if else</code> statements, but it is more readable. </p>\n\n<p>I also used a few built-in Python functions, <code>filter</code> and <code>reduce</code>. These are tailor-made for handling these kinds of boiler-plate tasks. </p>\n\n<p>I also changed <code>if ref_date</code> to <code>if ref_date is None</code>. Quoted from <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a></p>\n\n<blockquote>\n <p>beware of writing <code>if x</code> when you really mean <code>if x is not None</code></p>\n</blockquote>\n\n<p>Finally, I replaced your list initialization for <code>totals</code> to according to <a href=\"https://stackoverflow.com/questions/521674/initializing-a-list-to-a-known-number-of-elements-in-python\">this</a> SO question.</p>\n\n<pre><code>def _get_balances(self,ref_date=None):\n if ref_date is None:\n ref_date = datetime.date.today()\n totals = [Decimal('0.0')] * 5\n for invoice in self.invoices:\n if invoice.date is not None:\n payments = filter(lambda: payment.check.date &lt;= ref_date)\n total_amount_paid = reduce(lambda: total, payment: payment.amount + total, payments, 0)\n invoice_total = invoice.amount - total_amount_paid \n if self.__invoice_date_is_before(invoice.date, ref, date, 29):\n totals[0] += invoice_total\n elif self.__invoice_date_is_between(invoice.date, ref_date, 30, 43):\n totals[1] += invoice_total\n elif iself.__invoice_date_is_between(invoice.date, ref_date, 44, 47):\n totals[2] += invoice_total\n elif self.__invoice_date_is_between(invoice.date, ref_date, 48, 59):\n totals[3] += invoice_total\n elif self.__invoice_date_is_after(invoice.date, ref_date, 60):\n totals[4] += invoice_total\n return tuple(totals)\n\ndef __invoice_date_is_between(self, invoice_date, ref_date, start_of_period, end_of_period):\n return invoice_date &lt;= ref_date - relativedelta(days=start_of_period) and \\\n invoice_date &gt;= ref_date - relativedelta(days=end_of_period)\n\ndef __invoice_date_is_after(self, invoice_date, ref_date, end_of_period):\n return invoice_date &lt;= ref_date - relativedelta(days=end_of_period):\n\ndef __invoice_date_is_before(self, invoice_date, ref_date, start_of_period):\n return invoice_date &gt;= ref_date - relativedelta(days=start_of_period)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T18:51:56.607", "Id": "11485", "ParentId": "11479", "Score": "4" } }, { "body": "<p>Firstly, everything John Thomas Evans said.</p>\n\n<p>However, </p>\n\n<pre><code> payments = Decimal('0.0')\n for payment in invoice.payments:\n if payment.check.date &lt;= ref_date:\n payments += payment.amount\n</code></pre>\n\n<p>I'd write it as:</p>\n\n<pre><code> payments = [payment.amount for payment in invoice.payments if payment.check.date &lt;= ref_date]\n payments = sum(payments, Decimal(\"0\"))\n</code></pre>\n\n<p>And for your big mess of ifs...</p>\n\n<pre><code>days_before_reference_date = (ref_date - invoice.date).days\nsections = [30, 44, 48, 60]\nsection = bisect.bisect_right(sections, days_before_reference_date)\ntotals[section] += invoice_total\n</code></pre>\n\n<p>Basically, sections contains the starting points for the different buckets. We use <code>bisect</code> to detect which bucket our given value would fall into.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T20:41:26.993", "Id": "11488", "ParentId": "11479", "Score": "2" } } ]
{ "AcceptedAnswerId": "11485", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:51:26.770", "Id": "11479", "Score": "1", "Tags": [ "python", "finance" ], "Title": "Accounts payable buckets (Current,30,44,48,60)" }
11479
<p>Looking to optimize this method so it will run quicker, but can't seem to find anything. WOrking in .NET 3.5. ExcludedWords and NewCodes are both HashSet of strings.</p> <pre><code> private bool isValid(String code) { String pattern = "[a-zA-Z]{3}"; if (chkLessThan2Letters.Checked &amp;&amp; Regex.IsMatch(code, pattern)) { return false; } foreach (string s in excludedWords) { if (code.Contains(s)) { return false; } } if (newCodes.Contains(code)) { return false; } return true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:13:53.067", "Id": "18405", "Score": "3", "body": "How long is it currently taking? How long does it need to take for you to have sufficiently optimized it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:13:59.370", "Id": "18406", "Score": "0", "body": "@Tudor -The method runs a lot of times in my application. If there is a bottleneck, I think its here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:14:44.673", "Id": "18407", "Score": "12", "body": "You think? Stop guessing. Get a profiler and measure where the actual bottleneck is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:15:41.663", "Id": "18408", "Score": "0", "body": "@Servy -Depends on the user's input. The excluded words are loaded from a text file before this method is ever called, and is usually at least 300 strings. newCodes gets larger and larger until an outer loop reaches a user specified number." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:15:51.613", "Id": "18409", "Score": "3", "body": "What kind of collection is `newCodes`? Using a `HashSet<string>` here will be beneficial." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:20:17.307", "Id": "18410", "Score": "0", "body": "Does most of the data return true? Does it return false? If false, is it usually because of which return statement? They should be in order of how likely they are to happen, or if equal probability, in ascending order of runtime, so that you get the most out of the short circuting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:20:55.590", "Id": "18411", "Score": "1", "body": "Since the test `newCodes.Contains` should be very fast, you could do that one first and save time on average." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:22:17.837", "Id": "18412", "Score": "0", "body": "Also, use `string` vs `String` :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:25:39.630", "Id": "18413", "Score": "0", "body": "@payo it's nothing different, just an alias :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:25:42.280", "Id": "18414", "Score": "0", "body": "@payo They'll both be converted to the same thing at compile time, it won't affect how it runs at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:28:52.700", "Id": "18415", "Score": "0", "body": "If this is truly your \"complex\" `RegEx` expression, you could just do `if (code.All(char.IsLetter) && code.Length == 3)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:30:49.420", "Id": "18416", "Score": "0", "body": "@Servy & mattytommo I know it [String alias] makes no dif, i just find it ugly. it's just a comment :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T18:02:26.587", "Id": "18417", "Score": "0", "body": "@icemanind -I don't think that would work, because I'm checking to see if my new code contains a string of 3 characters in a row. The string is almost always longer than that." } ]
[ { "body": "<p>Before you optimize this, make sure that it actually needs optimization and that you're not wasting your time. Have you checked that this is a performance bottleneck in your application?</p>\n\n<p>One way to optimize this is to store your excluded words in a datastructure like a <a href=\"http://en.wikipedia.org/wiki/Trie\" rel=\"nofollow\">Trie</a>. This will let you see if some word in in the trie potentially faster than iterating through a list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T18:12:59.810", "Id": "18418", "Score": "0", "body": "Can this work if I don't have pairs? I only have 1 datum, the new word. There is no key associated with it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T18:13:55.067", "Id": "18419", "Score": "0", "body": "yeah. You can just make the key=new word, value=true. You don't really care about the value, you just want the improved lookup performance." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:15:19.527", "Id": "11482", "ParentId": "11481", "Score": "2" } }, { "body": "<p>Assuming this is really your bottleneck, a few options:</p>\n\n<ol>\n<li><p>Create your Regex ahead of time and precompile it.</p></li>\n<li><p>If excludedWords doesn't change while you're running, try creating a long OR Regex, like <code>(badWord1|badWord2|xyz)</code> and precompiling it. This should create a fairly efficient search-tree that will be faster than performing a repeated Contains call.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T18:03:47.770", "Id": "18420", "Score": "0", "body": "Would a longer OR Regex work with more than 500 items? At what point is there too many items? How could I precompile the regex?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T19:14:09.820", "Id": "18421", "Score": "0", "body": "@MAW74656, for compilation, use [this constructor](http://msdn.microsoft.com/en-us/library/h5845fdz.aspx) and pass in `RegexOptions.Compiled`. You'll want to keep that instance around and use it for all your matching. As far as length, I believe it should work fine for over 500 items, but I recommend trying it out. A long Regex might take a little while to compile when you first construct it, but performance once constructed should be quite good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T19:53:17.123", "Id": "18425", "Score": "0", "body": "-What about 5 million? I'm not just being difficult, I'd like to ability to efficiency handle large lists." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T20:05:01.177", "Id": "18426", "Score": "0", "body": "@MAW74656, I haven't used a Regex on that scale, but it wouldn't be hard for you to try. I suspect the compilation time would be somewhat long, but the compiled performance would be significantly better than a brute-force repeated Contains search." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T20:14:44.523", "Id": "18429", "Score": "0", "body": "So, I can simply loop through excluded words and use a stringbuilder to manually build the regex?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T21:06:51.843", "Id": "18434", "Score": "0", "body": "@MAW74656, yes, that should work." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:20:30.963", "Id": "11483", "ParentId": "11481", "Score": "2" } }, { "body": "<p>This could help:</p>\n\n<pre><code> private static readonly Regex matchCode = new Regex(\"[a-zA-Z]{3}\", RegexOptions.Compiled);\n\n private bool IsValid(string code)\n {\n if (this.chkLessThan2Letters.Checked &amp;&amp; matchCode.IsMatch(code))\n {\n return false;\n }\n\n if (this.excludedWords.Any(code.Contains))\n {\n return false;\n }\n\n return !this.newCodes.Contains(code);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T19:47:07.427", "Id": "18424", "Score": "0", "body": "What does `this.excludedWords.Any(code.Contains)` do different than what I have?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T20:08:03.067", "Id": "18427", "Score": "0", "body": "It takes it out of your hands and puts it into the hands of LINQ which likely employs various optimizations internally." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T20:10:45.580", "Id": "18428", "Score": "0", "body": "But its the same effect? If it finds any excluded words within code it will return true?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T20:40:34.437", "Id": "18432", "Score": "1", "body": "@MAW74656 yes. That code is equivalent to: `this.excludedWords.Any(word => code.Contains(word))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T21:50:19.200", "Id": "18435", "Score": "0", "body": "@MAW74656 yes, the effect is identical to your original `foreach` loop with the `Contains`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T19:14:45.160", "Id": "11487", "ParentId": "11481", "Score": "1" } }, { "body": "<p>I was going to make this a comment to Dan's answer, but it started getting quite long (and I wanted to try and actually code it to see if I remembered how).</p>\n\n<p>Assuming <code>excludedWords</code> is big and doesn't change between builds of the application (or if it does you have the ability to replace a single dll), you should build a dll containing the compiled regex representing it to get a much better search then you would if you used that linq expression.</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Reflection;\nusing System.Reflection.Emit;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace RegexLibAssemblyBuilder \n{\n public class RegexCompilationTest \n {\n public static IEnumerable&lt;string&gt; ExcludedWords() {...}\n\n public static void Main() \n {\n //build pattern\n var excludedWordsRegex = new StringBuilder();\n bool first = true;\n\n foreach (var word in ExcludedWords()) \n {\n if (!first) \n {\n excludedWordsRegex.Append(\"|\");\n }\n excludedWordsRegex.Append(Regex.Escape(word));\n first = false;\n }\n\n // Define regular expression here\n var expr = new RegexCompilationInfo(excludedWordsRegex.ToString(),\n RegexOptions.None,\n \"ExcludedWordsRegex\",\n \"Utilities.RegularExpressions\",\n true);\n\n //add other assembly attributes you want just like this\n ConstructorInfo ctor = typeof(System.Reflection.AssemblyTitleAttribute).GetConstructor(new[] { typeof(string) });\n CustomAttributeBuilder[] attBuilder = { new CustomAttributeBuilder(ctor, new object[] { \"General-purpose library of compiled regular expressions\" }) };\n\n Regex.CompileToAssembly(new[] { expr }, new AssemblyName(\"RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null\"), attBuilder);\n }\n }\n}\n</code></pre>\n\n<p>Then in code you could use it like this (after linking your project to this new assembly):</p>\n\n<pre><code>private static readonly Regex excludedWords= new ExcludedWordsRegex();\n\nprivate bool IsValid(string code)\n{\n if (this.chkLessThan2Letters.Checked &amp;&amp; matchCode.IsMatch(code))\n {\n return false;\n }\n\n if (excludedWords.IsMatch(code))\n {\n return false;\n }\n...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T20:41:14.920", "Id": "18618", "Score": "0", "body": "-Should this perform differently than just buidling the regex in memory? Does the extra dll help performance?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T13:12:39.483", "Id": "18644", "Score": "0", "body": "This has the same performance as building the regex in memory when it is used, but it moves the initialization time of the regex out to a compile time task instead of a first time hit during runtime." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T21:36:56.327", "Id": "18679", "Score": "0", "body": "Ok, then I don't want to use that, because the exclusion file changes at runtime, the user can chose the one they want to use, then it stays the same for the entire run and all the iterations of the loops." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T22:48:08.600", "Id": "11492", "ParentId": "11481", "Score": "0" } }, { "body": "<p>I am basing my answer on Jesse's. It would be unwise to throw away some of his optimizations. The only improvement I can offer is not using Regex but doing the equivalent check manually, because it is such a simple regex. If you have to use a different one, then this will not work. Note that I also made the methods static, made them take every parameter explicitly, thus making this code more \"functional\". Also, it looks less like Java because method starts with a capital letter and I use <code>string</code> instead of <code>String</code>. You are probably storing stuff as a HashSet but I am taking Collection as an input. Firstly, I was not sure which exact container you have. Secondly, this should not affect the speed, but if you prefer to do it differently, then you may do so.</p>\n\n<pre><code> // using System.Linq;\n private static bool IsValidCode(string code, bool checkLessThanTwoLetters, ICollection&lt;string&gt; excludedWords, ICollection&lt;string&gt; newCodes)\n {\n // TODO: The naming is confusing but all I did was re-factored the code.\n if (checkLessThanTwoLetters &amp;&amp; ContainsThreeLetterCode(code: code))\n {\n return false;\n }\n\n if (excludedWords.Any(code.Contains))\n {\n return false;\n }\n\n return !newCodes.Contains(code);\n }\n\n // I updated this method thanks to a comment by Bill.\n private static bool ContainsThreeLetterCode(string code)\n {\n if (code == null || code.Length != 3)\n {\n return false;\n }\n\n int ctr = 0;\n foreach(char ch in code)\n {\n ctr = Char.IsLetter(ch) ? ctr + 1 : 0;\n if (ctr == 3)\n {\n return true;\n }\n }\n\n return false;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T00:48:28.973", "Id": "18441", "Score": "0", "body": "The regex matches any string with at least 3 letters, not exactly 3 letters, but yes a simple method would be better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T01:02:07.683", "Id": "18442", "Score": "0", "body": "@Bill Barry, I am not so sure. I checked the pattern using http://www.regexplanet.com/advanced/java/index.html and Pot would match while Potato would not. I know Regex has a ton of options, but the way I read it was - the letter MUST repeat three times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T01:22:09.007", "Id": "18443", "Score": "0", "body": "Firstly the tags on this question suggest C#, but more importantly, the regex is not bound by either `^` or `$`. Thus it can match anywhere in the string. If you want, here is a silverlight app that will test .NET regular expressions; try it yourself: http://regexhero.net/tester/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T18:27:19.483", "Id": "18456", "Score": "0", "body": "@Bill Barry, thanks for the link. I updated my code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T23:59:26.810", "Id": "11493", "ParentId": "11481", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:11:51.680", "Id": "11481", "Score": "0", "Tags": [ "c#", "optimization", ".net" ], "Title": "How to optimize this validation method?" }
11481
<p>The common <a href="http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/">FizzBuzz</a> implementation I saw is using a check for % 15 for printing "FizzBuzz"</p> <p>Would you let me know if there is anything wrong / better with this approach?</p> <pre><code>public class FizzBuzz { public static void main(String[] args) { for (int i = 1; i &lt;= 100; i++) { boolean fizzOrBuzz = false; if (i % 3 == 0) { System.out.print("Fizz"); fizzOrBuzz = true; } if (i % 5 == 0) { System.out.print("Buzz"); fizzOrBuzz = true; } if (fizzOrBuzz) { System.out.println(); } else { System.out.println(String.valueOf(i)); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T23:01:59.533", "Id": "18440", "Score": "1", "body": "Your version is optimized for the computer. Winston's version is optimized for the human. Got to trust a compiler that it can do a good job at re-shuffling and optimizing the code. Also, it is possible that a single io statement will work faster than two separate ones. You should race your version against the other one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T17:21:39.180", "Id": "24587", "Score": "0", "body": "I'll tell you why I like my version better (only for the interview context) 1) maintainability - you can externalize Fizz and Buzz as strings, you don't need to externalize FizzBuzz 2) DRY, a user writing the above code is thinking in terms of not repeating oneself, which I like" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T15:35:58.903", "Id": "24838", "Score": "1", "body": "+1 but, use a *StringBuilder* and not 100 * System.out.println(..), and, *Integer.valueOf(i)*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T21:05:48.677", "Id": "24861", "Score": "0", "body": "@cl-r thanks, I will keep it at the original so the comments will still make sense, thanks for the feedback" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-11T20:51:01.773", "Id": "183819", "Score": "0", "body": "FizzBuzzEnterpriseEdition is the best implementation there is: https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition ;D" } ]
[ { "body": "<p>It looks fine. <code>String.valueOf()</code> is unnecessary, <code>System.out.println(i)</code> would print the same but it is still OK. This test is used only to make sure that the interviewee can write code as the linked site says:</p>\n\n<blockquote>\n <p>This sort of question won’t identify great programmers, but it will identify the weak ones. \n And that’s definitely a step in the right direction.</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T21:19:37.600", "Id": "11490", "ParentId": "11489", "Score": "6" } }, { "body": "<p>Let's compare your version to the <code>% 15</code> version:</p>\n\n<pre><code>public class FizzBuzz {\n public static void main(String[] args) {\n for (int i = 1; i &lt;= 100; i++) {\n if (i % 15 == 0) {\n System.out.println(\"FizzBuzz\")\n } else if (i % 3 == 0) {\n System.out.println(\"Fizz\");\n } else if (i % 5 == 0) {\n System.out.println(\"Buzz\");\n } else {\n System.out.println(String.valueOf(i));\n }\n }\n }\n}\n</code></pre>\n\n<p>The <code>% 15</code> version is simpler and easier to read. This version neatly delineates the problem into the 4 different cases, and handles each case. In contrast, your version introduces a boolean logic flag (which I consider to be a significant anti-pattern) and a not entirely intuitive dependence on the order of the if statements. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T19:29:21.933", "Id": "24854", "Score": "6", "body": "15 is a \"magic number\" here. I'd suggest using `(3 * 5)` instead. The compiler should convert it to 15..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T20:46:23.483", "Id": "24859", "Score": "1", "body": "@Ron - So is, `\"FizzBuzz\"`, by this criteria. Not that you're _wrong_ necessarily, but for these types of 'trivia' questions, the necessity of declaring everything is usually relaxed slightly. For instance, strictly speaking, for production-level code, **all** the numbers and strings referenced/printed here should be captured as named constants." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-05T17:06:24.820", "Id": "24882", "Score": "0", "body": "@X-Zero, would you capture the 3 as a constant, what would you call it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-05T17:33:36.333", "Id": "24884", "Score": "0", "body": "@Winston - The general problem with this is it's basically a 'contrived' example, so it can be hard to get _good_ names for this. Especially as what the test has is essentially 'multiple' checks - continuing to decompose this would likely result in some sort of array/table structure (yeah... I know... heading to outer-space architecture). So, `MATCH` maybe? `CONDITION`? Urgh. Which is why these kinds of conventions are relaxed for these kinds of tests; the test is for basic coding ability, not (necessarily) full abstraction skills." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-27T16:16:35.687", "Id": "365647", "Score": "1", "body": "I would move if-for-15 inside if-for-5, if you can't divide a number by 3, certainly can't divide by 15, save 4/5 of checks for all numbers" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T21:39:45.580", "Id": "11491", "ParentId": "11489", "Score": "29" } }, { "body": "<p>Here's a version that's (IMHO) a little better for humans than yours and better for computers as well:</p>\n\n<pre><code>public class FizzBuzz {\n public static void main(String[] args) {\n for (int i = 1; i &lt;= 100; i++) {\n String value;\n switch (i % 15) {\n case 3:\n case 6:\n case 9:\n case 12: // divisible by 3, print Fizz\n value = \"Fizz\";\n break;\n case 5:\n case 10: // divisible by 5, print Buzz\n value = \"Buzz\";\n break;\n case 0: // divisible by 3 and by 5, print FizzBuzz\n value = \"FizzBuzz\";\n break;\n default: // else print the number\n value = Integer.toString(i);\n }\n System.out.println(value);\n }\n }\n}\n</code></pre>\n\n<p>The comments provide information to humans (but they could still see it on their own) and there's only one <code>System.out.println</code> call per <code>i</code>.</p>\n\n<p><strong>EDIT:</strong> This is another way to fizz-buzz (focus: DRY):</p>\n\n<pre><code>public class FizzBuzz {\n public static void main(String[] args) {\n final String EMPTY = \"\";\n for (int i = 1; i &lt;= 100; i++) {\n String value = EMPTY;\n if (i % 3 == 0) value += \"Fizz\";\n if (i % 5 == 0) value += \"Buzz\";\n if (value == EMPTY) value += i;\n System.out.println(value);\n }\n }\n}\n</code></pre>\n\n<p><strong>EDIT 2:</strong> yet another, using <code>StringBuilder</code>, DRY as well:</p>\n\n<pre><code>public class FizzBuzz {\n public static void main(String[] args) {\n StringBuilder builder = new StringBuilder(1000);\n for (int i = 1; i &lt;= 100; i++) {\n final int length = builder.length();\n if (i % 3 == 0) builder.append(\"Fizz\");\n if (i % 5 == 0) builder.append(\"Buzz\");\n if (length == builder.length()) builder.append(i);\n builder.append('\\n');\n }\n System.out.println(builder);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T15:40:36.763", "Id": "24839", "Score": "2", "body": "StringBuilder seems a faster approach than += in this case" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T19:32:07.953", "Id": "24855", "Score": "0", "body": "@EranMedan - Are you sure of this? `StringBuilder` is good because `N` appends doesn't lead to `N` allocations, however here `N` is at most 2, which is a small enough number that it likely won't make a difference, and it's quite likely to be 1, which means no difference at all (or maybe worse, as `StringBuilder` probably does an extra allocation for that 1 append)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T21:04:39.990", "Id": "24860", "Score": "0", "body": "@asveikau - you are probably right, I guess this will be over optimization to find out exactly which is faster :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-05T07:56:12.583", "Id": "24865", "Score": "1", "body": "I'm aware of StringBuilder - which I use all the time in String heavy code - and thought along the lines of [asveikau](http://codereview.stackexchange.com/users/4029/asveikau). `+=` is less \"noisy\" (also the reason for my avoidance of `Integer.toString()`) and it won't make much of a difference as there's at most two concatenations. Btw.: I'd have used StringBuilder like this: declare before the loop, initialize with capacity set to `8`, cleared and reuse per iteration. Creating it inside the loop wouldn't improve much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-06T15:10:02.663", "Id": "24951", "Score": "0", "body": "see above for another version using `StringBuilder` - but only one call to `System.out.println(...)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-27T16:36:09.647", "Id": "365654", "Score": "0", "body": "if edit 1 you dont have to do += here right? - if (value == EMPTY) value += i;" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T17:03:25.917", "Id": "15152", "ParentId": "11489", "Score": "3" } }, { "body": "<p>They are certainly not perfects, but I've tried some ways to optimize the test, here the result (I have had numbers to keep trace of good responses) , and I use a StringBuilder to avoid initialization of output IO:</p>\n\n<pre><code>package exercices;\n\nimport java.util.Hashtable;\n\nimport org.memneuroo.outils.communs.utilitaires.EnvPrm;\n\npublic class FizzBuzz {\n // time for cum with nbIter=30 &gt; 300; 30 ~= 3000\n static final int nbIter = 30;\n static final String sep = \"_\";\n\n static long ifNested() {\n final StringBuilder sb = new StringBuilder();\n final long t = System.nanoTime();\n for (int i = 0; i &lt; nbIter; i++) {\n sb.append(//\n i % 15 == 0 //\n ? \"FizzBuzz\" //\n : (i % 3 == 0 //\n ? \"Fizz\"//\n : (i % 5 == 0//\n ? \"Buzz\" //\n : i)));// sb.append(sep);\n }\n final long totT = System.nanoTime() - t;\n System.out.format(\"ifNested\\t%20d\\n\", totT);\n // sb.append(EnvPrm.NEWLINE); System.out.println(sb.toString());\n return totT;\n }\n\n static long stringPlus() {\n final StringBuilder sb = new StringBuilder();\n final long t = System.nanoTime();\n for (int i = 0; i &lt; nbIter; i++) {\n String x = \"\";\n x += (i % 3 == 0) ? \"Fizz\" : \"\";\n x += (i % 5 == 0) ? \"Buzz\" : \"\";\n if (x.isEmpty()) { // MODIF\n x += Integer.toString(i);\n }\n sb.append(x);// sb.append(sep);\n }\n final long totT = System.nanoTime() - t;\n System.out.format(\"stringPlus\\t%20d\\n\", totT);\n // sb.append(EnvPrm.NEWLINE); System.out.println(sb.toString());\n return totT;\n }\n\n static long withIf() {\n final StringBuilder sb = new StringBuilder();\n final long t = System.nanoTime();\n for (int i = 0; i &lt; nbIter; i++) {\n if (i % 3 == 0) {\n sb.append(\"Fizz\");\n if (i % 5 == 0) {\n sb.append(\"Buzz\");\n }\n } else if (i % 5 == 0) {\n sb.append(\"Buzz\");\n } else {\n sb.append(i);\n }// sb.append(sep);\n }\n final long totT = System.nanoTime() - t;\n System.out.format(\"withIf\\t\\t%20d\\n\", totT);\n // sb.append(EnvPrm.NEWLINE);System.out.println(sb.toString());\n return totT;\n }\n\n static long withArray() {\n final String[] lis = {\"FizzBuzz\", \"\", \"\", \"Fizz\", \"\", \"Buzz\", \"Fizz\",\n \"\", \"\", \"Fizz\", \"Buzz\", \"\", \"Fizz\", \"\", \"\",};\n final StringBuilder sb = new StringBuilder();\n final long t = System.nanoTime();\n for (int i = 0; i &lt; nbIter; i++) {\n final String pos = lis[i % 15];\n sb.append(((0 == pos.length()) ? i : pos));// sb.append(sep);\n }\n final long totT = System.nanoTime() - t;\n System.out.format(\"withArray\\t%20d\\n\", totT);\n // sb.append(EnvPrm.NEWLINE); System.out.println(sb.toString());\n return totT;\n }\n\n static long withTable() {\n final Hashtable&lt;Integer, String&gt; ht = new Hashtable&lt;&gt;(8);\n ht.put(0, \"FizzBuzz\");\n ht.put(3, \"Fizz\");\n ht.put(5, \"Buzz\");\n ht.put(6, \"Fizz\");\n ht.put(9, \"Fizz\");\n ht.put(10, \"Buzz\");\n ht.put(12, \"Buzz\");\n final StringBuilder sb = new StringBuilder();\n final long t = System.nanoTime();\n for (int i = 0; i &lt; nbIter; i++) {\n final String s = ht.get(i % 15);\n // MODIF\n // http://www.developpez.net/forums/d1196563-2/java/general-java/if-null-object-if-objet-null/#post6561766\n // sb.append((null == s ? i : s));// sb.append(sep);\n if (null == s) {\n sb.append(i);\n } else {\n sb.append(s);\n }\n }\n final long totT = System.nanoTime() - t;\n System.out.format(\"withTable\\t%20d\\n\", totT);\n // sb.append(EnvPrm.NEWLINE); System.out.println(sb.toString());\n return totT;\n\n }\n\n static int recursive(final StringBuilder sb, final int n) {\n if (0 == n) {\n return 1;\n }\n if (n % 3 == 0) {\n sb.insert(0, \"Fizz\");\n if (n % 5 == 0) {\n sb.insert(0, \"Buzz\");\n }\n } else if (n % 5 == 0) {\n sb.insert(0, \"Buzz\");\n } else {\n sb.insert(0, n);\n }\n return n + recursive(sb, n - 1);\n }\n\n static long recursive() {\n final StringBuilder sb = new StringBuilder(\"\");\n final long t = System.nanoTime();\n recursive(sb, nbIter);\n final long totT = System.nanoTime() - t;\n System.out.format(\"recursive\\t%20d\\n\", totT);\n sb.append(EnvPrm.NEWLINE);\n System.out.println(sb.toString());\n return totT;\n }\n\n /*** @param args */\n public static void main(final String[] args) {\n long cum = 0L, cum2 = 0L;\n for (int i = 0; i &lt; 5; i++) {\n System.out.println(\"------ \" + i + \" -----\");\n final long totSb = stringPlus();\n final long totIn = ifNested();\n final long totWi = withIf();\n final long totWa = withArray();\n final long totWt = withTable();\n final long totRe = recursive();\n System.out.format(\"... stringPlus/withIf :%5d\\n\", (totSb * 100)\n / totWi);\n System.out.format(\"... ifNested/withIf :%5d\\n\", (totIn * 100)\n / totWi);\n System.out.format(\"... withArray/withIf :%5d\\n\", (totWa * 100)\n / totWi);\n System.out.format(\"... withTable/withIf :%5d\\n\", (totWt * 100)\n / totWi);\n System.out.format(\"... recursive/withIf :%5d\\n\", (totRe * 100)\n / totWi);\n cum += totIn + totSb + totWi + totWa + totWt + totRe;\n System.out.println(\"CUMUL (SECOND) == \" + cum / 100000000 + \".\"\n + cum % 100000000 + \"\\t , diff: \" + (cum - cum2));\n cum2 = cum;\n }\n }\n}\n</code></pre>\n\n<p>And the output :</p>\n\n<pre><code>------ 0 -----\nstringPlus 529397\nifNested 643657\nwithIf 27657\nwithArray 43581\nwithTable 40788\nrecursive 87441\n12Fizz4BuzzFizz78FizzBuzz11Fizz1314BuzzFizz1617Fizz19BuzzFizz2223FizzBuzz26Fizz2829BuzzFizz\n\n... stringPlus/withIf : 1914\n... ifNested/withIf : 2327\n... withArray/withIf : 157\n... withTable/withIf : 147\n... recursive/withIf : 316\nCUMUL (SECOND) == 0.1372521 , diff: 1372521\n------ 1 -----\nstringPlus 345295\nifNested 88280\nwithIf 88279\nwithArray 88838\nwithTable 101689\nrecursive 93308\n12Fizz4BuzzFizz78FizzBuzz11Fizz1314BuzzFizz1617Fizz19BuzzFizz2223FizzBuzz26Fizz2829BuzzFizz\n\n... stringPlus/withIf : 391\n... ifNested/withIf : 100\n... withArray/withIf : 100\n... withTable/withIf : 115\n... recursive/withIf : 105\nCUMUL (SECOND) == 0.2178210 , diff: 805689\n------ 2 -----\nstringPlus 380216\nifNested 36597\nwithIf 20953\nwithArray 60063\nwithTable 91352\nrecursive 111467\n12Fizz4BuzzFizz78FizzBuzz11Fizz1314BuzzFizz1617Fizz19BuzzFizz2223FizzBuzz26Fizz2829BuzzFizz\n\n... stringPlus/withIf : 1814\n... ifNested/withIf : 174\n... withArray/withIf : 286\n... withTable/withIf : 435\n... recursive/withIf : 531\nCUMUL (SECOND) == 0.2878858 , diff: 700648\n------ 3 -----\nstringPlus 489168\nifNested 29613\nwithIf 22070\nwithArray 27099\nwithTable 27378\nrecursive 91911\n12Fizz4BuzzFizz78FizzBuzz11Fizz1314BuzzFizz1617Fizz19BuzzFizz2223FizzBuzz26Fizz2829BuzzFizz\n\n... stringPlus/withIf : 2216\n... ifNested/withIf : 134\n... withArray/withIf : 122\n... withTable/withIf : 124\n... recursive/withIf : 416\nCUMUL (SECOND) == 0.3566097 , diff: 687239\n------ 4 -----\nstringPlus 143035\nifNested 24025\nwithIf 15924\nwithArray 23187\nwithTable 26819\nrecursive 87162\n12Fizz4BuzzFizz78FizzBuzz11Fizz1314BuzzFizz1617Fizz19BuzzFizz2223FizzBuzz26Fizz2829BuzzFizz\n\n... stringPlus/withIf : 898\n... ifNested/withIf : 150\n... withArray/withIf : 145\n... withTable/withIf : 168\n... recursive/withIf : 547\nCUMUL (SECOND) == 0.3886249 , diff: 320152\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-05T08:22:56.597", "Id": "24866", "Score": "1", "body": "StringBuilder is based on a `char[16]`. You should set the initial capacity to a value larger than the String you want to create - or you worsen the performance, as StringBuilder has to grow (allocate new `char[]`, copy old data). You should also be aware of how [`System.nanoTime()`](stas-blogspot.blogspot.com/2012/02/what-is-behind-systemnanotime.html) works and the issues it has. And I'd advise you to do a lot more iterations. I think you mainly measure the time for `System.out.println()` right now, the other operations probably take very little time compared to a system call." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-19T18:44:24.103", "Id": "62718", "Score": "1", "body": "Tell me, have you ever heard of the concept *over-engineering*...?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-12T16:43:01.967", "Id": "184034", "Score": "2", "body": "@Max I do, but is this site is done for some researches or not? Is for comfortable eyes, or to try to understand how some ways are better ? So you can choose and compare the faster, the easy to read, or interrogate the code to find missing optimization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-16T13:50:27.490", "Id": "204366", "Score": "0", "body": "See [Rules for optimization](http://c2.com/cgi/wiki?RulesOfOptimization). IMHO Winston Ewert provided the best answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-27T16:21:32.250", "Id": "365648", "Score": "0", "body": "explain math in withTable code please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-28T19:50:40.157", "Id": "365937", "Score": "0", "body": "@KalpeshSoni - It is not a math answer, but Java code sample, no abstraction but algorithm application" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-28T20:10:32.163", "Id": "365940", "Score": "0", "body": "never mine I read the other answer by @arne and understood" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T15:26:53.913", "Id": "15322", "ParentId": "11489", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T21:01:25.847", "Id": "11489", "Score": "16", "Tags": [ "java", "interview-questions", "fizzbuzz" ], "Title": "FizzBuzz implementation" }
11489
<p>Is there a better way to do this?</p> <pre><code>function Person(name) { this._type='Person'; this.name=name; this.hello = function(){ alert('Hello '+this.name); }; } function object_to_instance(key, value) { if (!value.hasOwnProperty('_type')) return value; var obj= eval('new '+value._type+'()'); for (var property in value) obj[property]=value[property]; return obj; } var people = [new Person('Harry'), new Person('Sally')]; var people_json = JSON.stringify(people); var new_people = JSON.parse(people_json, object_to_instance); new_people[0].hello(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T01:32:50.087", "Id": "18444", "Score": "0", "body": "instead of eval you could do: `var obj = new window[value._type](value.name);` (I think you could at least; I don't use classes in js)." } ]
[ { "body": "<p>Instead of <code>eval</code>, you could create a <code>Person</code> constructor that accepts an object:</p>\n\n<pre><code>function Person(arg)\n{\n if (typeof arg === 'string')\n {\n var name = arg;\n this._type='Person';\n this.name=name;\n }\n else if (typeof arg === 'object')\n {\n var value = arg;\n for (var prop in value)\n {\n if (value.hasOwnProperty(prop))\n {\n this[prop] = value[prop];\n }\n }\n }\n}\n\n// Move Person.hello() into the prototype\nPerson.prototype.hello = function()\n{\n alert('Hello '+this.name);\n};\n</code></pre>\n\n<p>Then use the <code>_type</code> to choose a constructor based on a predefined set of classes, rather than a (potentially) unsafe <code>eval</code>:</p>\n\n<pre><code>var classes =\n{\n Person: Person\n /* other potential classes to deserialize from here as well */\n};\n\nfunction object_to_instance(key, value)\n{\n if (!value._type) return value;\n return new classes[value._type](value);\n}\n\nvar people = [new Person('Harry'), new Person('Sally')];\nvar people_json = JSON.stringify(people);\nvar new_people = JSON.parse(people_json, object_to_instance);\nnew_people[0].hello();\n</code></pre>\n\n<ul>\n<li>Basic demo: <a href=\"http://jsfiddle.net/mattball/VfRJn\" rel=\"nofollow\">http://jsfiddle.net/mattball/VfRJn</a></li>\n<li>Using multiple classes: <a href=\"http://jsfiddle.net/mattball/VfwRv\" rel=\"nofollow\">http://jsfiddle.net/mattball/VfwRv</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T03:54:18.903", "Id": "11497", "ParentId": "11494", "Score": "2" } } ]
{ "AcceptedAnswerId": "11497", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T00:58:26.073", "Id": "11494", "Score": "2", "Tags": [ "javascript", "json" ], "Title": "Loading a pseudo-class instance from JSON" }
11494
<p>In a Mako template partial I accept an argument (<code>step</code>) that can be an instance of <code>Step</code> class, a <code>dict</code> or <code>None</code>. Can I in some way avoid repetition or do the check in other more 'pythonic' way? Or how could I gracefully avoid checking types at all?</p> <pre><code>&lt;%include file="_step.mako" args="step=step" /&gt; </code></pre> <p>and then in <code>_step.mako</code>:</p> <pre><code>&lt;%page args="step"/&gt; &lt;%! from package.models.recipe import Step %&gt; &lt;% if isinstance(step, Step): number = step.number time_value = step.time_value text = step.text elif type(step) is dict: number = step['number'] time_value = step['time_value'] text = step['text'] else: number = 1 time_value = '' text = '' %&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T16:23:08.797", "Id": "18453", "Score": "1", "body": "actually, the most pythonic way would be to avoid passing different types to this partial." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T18:58:43.517", "Id": "18457", "Score": "0", "body": "@WinstonEwert I wolud gladly avoid that, but how can I maintain a single template that is rendering a form sometimes empty and sometimes repopulated (with dict or instance of a class)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T19:21:08.137", "Id": "18458", "Score": "0", "body": "you shouldn't. You should change the rest of your code so its consistently passes the same thing to this template." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T20:05:27.973", "Id": "18461", "Score": "0", "body": "@WinstonEwert like create a dummy (empty) dict for none, valid or invalid data and pass that dict to the template? You know, I started with such a design but faced a problem: if I repopulate invalid data - it can only be a dict (I do not allow creating instances from invalid data) and if its valid - it is an instance and I have access to its attributes. So if I want to access its attributes in the template I have to check (or `try`) if its an instance. But if I unify the the type of object passed to the template, and it can only be a dict, I guess, no attributes like methods, can be used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T20:17:26.430", "Id": "18466", "Score": "0", "body": "Why do you need to populate this form with invalid data? Shouldn't you just not tolerate invalid data?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T20:32:15.100", "Id": "18467", "Score": "0", "body": "Ok, I have a `step` entity that requires a _number_ and _text_ and an optional _time value_. A user enters number and time value but leaves the text field empty. When I redirect after failed `step` creation I want to repopulate number and time value fields and mark the empty text field with error message." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T21:33:37.520", "Id": "18468", "Score": "0", "body": "ah, I see. What web framework are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T22:49:41.707", "Id": "18470", "Score": "0", "body": "Pyramid, but it's kind of fundamental question for me - I faced the same problem while on Zend Framework. Maybe it's because I don't utilize tools like Deform (and Zend_Form) that do the render-validate-repopulate job, but that's my style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T23:22:34.740", "Id": "18471", "Score": "1", "body": "You may find it useful to look into some of those projects, just to see how they solve this problem. Basically, they would have a `StepForm` class which can hold invalid/blank/valid data. The class would have methods to convert to/from an actual Step object. In some ways, its not dissimilar to always using a dictionary. But you get some benefits of using an object as well. You don't have to go for the whole form generation technique these libraries go for, but the separation between model and form objects has been widely adopted and seems to work well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T23:32:00.953", "Id": "18472", "Score": "0", "body": "Right! I am definetely close to stepping through Deform code for the final answers. Thanks for your attention Winston!" } ]
[ { "body": "<p>1.I assume <code>if type(step) is dict:</code> should be <code>elif type(step) is dict:</code>.</p>\n\n<p>2.<code>isinstance</code> is preferable than <code>type</code> because <code>isinstance</code> caters for inheritance, while checking for equality of type does not (it demands identity of types and rejects instances of subtypes).</p>\n\n<p>3.You also can apply duck-typing. </p>\n\n<pre><code>try:\n number = step.number\nexcept AttributeError:\n try:\n number = step['number']\n except KeyError:\n number = 1\n</code></pre>\n\n<p>And these ways are quite pythonic.</p>\n\n<p>4.I suggest you can inherit your <code>Step</code> class from <code>dict</code> then you don't need to check types. Yo will just do</p>\n\n<pre><code>number = step.get('number', 1)\ntime_value = step.get('time_value', '')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T06:24:49.247", "Id": "18447", "Score": "0", "body": "Thanks for the detailed answer! I will apply duck-typing as you described for now and save inheriting `dict` for later experiments - that could finally be a perfect solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T06:41:37.673", "Id": "18448", "Score": "0", "body": "You are welcome. But consider that `number = step.get('number', 1)` is shorter version of `try: number = step['number'] except KeyError: number = 1`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T06:58:01.013", "Id": "18449", "Score": "0", "body": "I will. The Step class is used as a model and an sqlalchemy mapping, thats why I'm afraid messing with it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T16:59:21.030", "Id": "18455", "Score": "0", "body": "I probably wouldn't use inheritance however. Just provide an implementation of the `get()` method and let the ducks do their thing." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T06:00:35.820", "Id": "11499", "ParentId": "11495", "Score": "1" } }, { "body": "<p>I came up with this function (thanks to San4ez):</p>\n\n<pre><code>def failsafe_get(object, name):\n if object:\n try:\n extractor = attrgetter(atrr_path)\n result = extractor(object)\n except AttributeError:\n try:\n result = object[atrr_path]\n except (KeyError, TypeError):\n result = None\n else:\n result = None\n return result\n</code></pre>\n\n<p>Now I can use it in a template like this:</p>\n\n<pre><code>&lt;div class=\"number\"&gt;${failsafe_get(ingredient, 'unit.abbr')}&lt;/div&gt;\n</code></pre>\n\n<p>No repetition, but maybe performance issue.</p>\n\n<p>UPD. I've implemented <code>operator.attrgetter</code> so now I can give dotted notation for a name.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T07:16:15.693", "Id": "18450", "Score": "0", "body": "I would check `name is None` out of `try-except` block" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T16:29:08.180", "Id": "18454", "Score": "0", "body": "@San4ez I am actually checking if `object` is `None`, providing `name` always a `str`. Corrected the code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T07:05:32.393", "Id": "11500", "ParentId": "11495", "Score": "0" } } ]
{ "AcceptedAnswerId": "11499", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T02:35:26.960", "Id": "11495", "Score": "1", "Tags": [ "python" ], "Title": "How to (and should I) avoid repetition while assigning values from different sources?" }
11495
<p>I created this as part of an interview process of graduate programming job. Submitted the code to them, and I was called for an interview. </p> <p>This is the assignment brief: <a href="http://knight-path.sourceforge.net/puzzle.html" rel="nofollow">http://knight-path.sourceforge.net/puzzle.html</a>, however I was told I can accept the input and produce the output in whatever form I think is most effective, and I have to display an OOP understanding as well.</p> <p>I am a beginner in Java and haven't code in it for a while (2 years since my last Java programming subject in uni), thus was curious on areas of improvements. I would like to be evaluated on my OOP, design pattern, and overall code quality.</p> <pre><code>import java.util.Scanner; import java.util.LinkedList; public class Board { private final int BOARD_WIDTH = 8; private final int BOARD_HEIGHT = 8; private LinkedList&lt;Square&gt; squares = new LinkedList(); public Board() { this.build(); } private void build() { this.squares.clear(); for (int y = 1; y &lt;= BOARD_HEIGHT; y++) { for (int x = 1; x &lt;= BOARD_WIDTH; x++) { this.squares.add(new Square(x, y, new Blank())); } } } public void play() { this.printWelcome(); while (true) { // build or re-build board from previous play this.build(); // prompt and validates move input, then creates a move object Move move = null; while (move == null) { try { move = new Move(this.readMove(), this); } catch (IllegalArgumentException e) { System.out.println("ERROR: " + e.getMessage() + " Please try again."); } } // set our source square with a knight piece, solve move, and print our boards + solutions move.getSource().setPiece(new Knight()); LinkedList&lt;LinkedList&lt;Square&gt;&gt; solutions = getKnightTravailsSolutions(move); this.print(solutions); } } private String readMove() { Scanner scanner = new Scanner(System.in); System.out.println(); System.out.println(); System.out.println("======================================================================================="); System.out.print("MOVES: "); return scanner.nextLine(); } public Square getSquare(int x, int y) { for (Square square: squares) { if (square.matches(x, y)) return square; } return null; } // ------------------------------------------------------------------------------------------------ // KNIGHT TRAVAILS FUNCTIONS // ------------------------------------------------------------------------------------------------ public LinkedList&lt;LinkedList&lt;Square&gt;&gt; getKnightTravailsSolutions(Move move) { // breadth-first search implementation // return a list of shortest path solution, each solution contains a list of squares it travels LinkedList&lt;LinkedList&lt;Square&gt;&gt; solutions = new LinkedList(); LinkedList&lt;LinkedList&lt;Square&gt;&gt; queue = new LinkedList(); LinkedList&lt;Square&gt; visited = new LinkedList(); boolean solutionFound = false; // initialize first path, our very first path is the source square of the move // this is technically a path, imagine in a case where our source and destination is the same square LinkedList&lt;Square&gt; firstPath = new LinkedList(); firstPath.add(move.getSource()); queue.add(firstPath); while (!queue.isEmpty()) { LinkedList&lt;Square&gt; currentPath = queue.removeFirst(); Square currentSquare = currentPath.getLast(); if (currentSquare == move.getDestination()) { solutions.add(currentPath); solutionFound = true; } if (!solutionFound) { for (Square nextLegalSquare: this.getKnightNextLegalMoves(currentSquare)) { if (!visited.contains(nextLegalSquare)) { LinkedList&lt;Square&gt; nextPath = new LinkedList(); nextPath.addAll(currentPath); nextPath.add(nextLegalSquare); queue.addLast(nextPath); } } } if (!visited.contains(currentSquare)) visited.add(currentSquare); } return solutions; } private LinkedList&lt;Square&gt; getKnightNextLegalMoves(Square source) { // brute force search to find next legal squares to all squares on board // returns a list of possible next move squares given a source square LinkedList&lt;Square&gt; nextMoves = new LinkedList(); for (Square destination: squares) { int xMoveDistance = destination.getX() - source.getX(); int yMoveDistance = destination.getY() - source.getY(); // since a knight hops over other pieces, we just need to ensure no piece exist within our destination square // and, whether we moved 2 then 1 space or 1 then 2 spaces if ((destination.getPiece().isBlank()) &amp;&amp; (Math.abs(xMoveDistance * yMoveDistance) == 2)) { nextMoves.add(destination); } } return nextMoves; } // ------------------------------------------------------------------------------------------------ // PRINTING FUNCTIONS // ------------------------------------------------------------------------------------------------ private void printWelcome() { System.out.println(); System.out.println(); System.out.println("======================================================================================="); System.out.println("The Knight's Travails Challenge"); System.out.println("======================================================================================="); System.out.println(); System.out.println("Welcome! :) I accept two squares identified by algebraic chess notation."); System.out.println("The first square is the starting position and the second square is the ending position."); System.out.println("I will then find the shortest sequence of valid moves to take a Knight piece from the"); System.out.println("starting position to the ending solution."); System.out.println(); System.out.println("Example input would be: A8 B7"); } private void print(LinkedList&lt;LinkedList&lt;Square&gt;&gt; solutions) { if (solutions.isEmpty()) { System.out.println(" SOLUTION #1: No solution exists"); } else { for (LinkedList&lt;Square&gt; solution: solutions) { System.out.println(this.getBoardLine(solution)); System.out.println(" SOLUTION #" + ((int)solutions.indexOf(solution) + 1) + ": " + this.getSolutionLine(solution)); } } } public String getSolutionLine(LinkedList&lt;Square&gt; solution) { String line = ""; if (solution.getFirst() == solution.getLast()) { line += "No travel required"; } else { for (Square square: solution) { if (square != solution.getFirst()) line += square.toChessNotation() + " "; } } return line; } private String getBoardLine(LinkedList&lt;Square&gt; solution) { String line = "\n"; line += this.getBoardTopLine() + "\n"; line += this.getBoardMiddleLine() + "\n"; for (int y = 1; y &lt;= this.BOARD_HEIGHT; y++) { for (int x = 1; x &lt;= this.BOARD_WIDTH; x++) { Square square = this.getSquare(x, y); if (!square.getPiece().isBlank()) { line += " | " + square.getPiece().toChessNotation(); } else if (solution.contains(square)) { line += " | " + solution.indexOf(square); } else { line += " | " + square.getPiece().toChessNotation(); } } line += " | " + y + "\n"; line += this.getBoardMiddleLine() + "\n"; } return line; } private String getBoardMiddleLine() { String line = " "; for (int i = 0; i &lt; this.BOARD_WIDTH; i++) { line += "+---"; } line += ""; return line; } private String getBoardTopLine() { String line = " "; char startChar = 'a'; for (int i = 0; i &lt; this.BOARD_WIDTH; i++) { line += " " + startChar + " "; startChar++; } return line; } } </code></pre> <p>Other classes:</p> <pre><code>public class Move { private Square source, destination; public Move(String moveInput, Board board) { if (moveInput == null || moveInput.length() != 5 || moveInput.charAt(2) != ' ') { throw new IllegalArgumentException("Invalid input."); } int fromX = (int)moveInput.toUpperCase().charAt(0) - '@'; int fromY = (int)moveInput.toUpperCase().charAt(1) - '0'; int toX = (int)moveInput.toUpperCase().charAt(3) - '@'; int toY = (int)moveInput.toUpperCase().charAt(4) - '0'; // check whether the squares are actually exists // e.g given input "a9 a1", square "a9" might not be exist in 8x8 board if ((board.getSquare(fromX, fromY) == null) || (board.getSquare(toX, toY)) == null) { throw new IllegalArgumentException("Invalid input."); } this.source = board.getSquare(fromX, fromY); this.destination = board.getSquare(toX, toY); } public Square getSource() { return this.source; } public Square getDestination() { return this.destination; } public String toChessNotation() { String line = this.getSource().toString() + " " + this.getDestination().toString(); return line; } } public class Square { private int x, y; private Piece piece; public Square(int x, int y, Piece piece) { this.x = x; this.y = y; this.piece = piece; } public int getX() { return this.x; } public int getY() { return this.y; } public Piece getPiece() { return this.piece; } public void setPiece(Piece piece) { this.piece = piece; } public String toChessNotation() { return (char)(this.x + 64) + "" + (this.y); } public boolean matches(int x, int y) { return (this.x == x &amp;&amp; this.y == y); } } public abstract class Piece { public Piece() {} public abstract PieceType getPieceType(); public abstract String toChessNotation(); public boolean isKnight() { return getPieceType() == PieceType.KNIGHT; } public boolean isBlank() { return getPieceType() == PieceType.BLANK; } } public enum PieceType { KNIGHT, BLANK; } public class Blank extends Piece { public PieceType getPieceType() { return PieceType.BLANK; } public String toChessNotation() { return " "; } } public class Knight extends Piece { public PieceType getPieceType() { return PieceType.KNIGHT; } public String toChessNotation() { return "N"; } } public class Main { public static void main(String[] args) { Board board = new Board(); board.play(); } } </code></pre>
[]
[ { "body": "<p>I personally wouldn't do things like <code>this.build();</code> but just <code>build();</code>... although that's a matter of taste. IMO <code>this</code> doesn't clarify anything but just adds noise to the code.</p>\n\n<hr>\n\n<p>I don't see any reason why your <code>squares</code> is a linked list. A matrix of <code>Piece</code> would suffice and it represents the purpose of <code>squares</code> better in my opinion. It would also simplify it all, since <code>getSquare()</code> would be a matter of querying the matrix indices instead of performing a search. It would also be more robust since you can have several squares with the same <code>x</code> and <code>y</code>. You're forcing it when you build the loop, but still...</p>\n\n<p>I would not remove <code>Square</code> completely, but I would keep it as a little bean for <code>getKnightTravailsSolutions</code>, <code>Move</code>, etc. <strong>ONLY</strong> representing the actual square (not the piece in it.)</p>\n\n<hr>\n\n<p>I would also move the <code>play()</code> (and related methods like <code>printWelcome()</code>, <code>readMove()</code>, etc.) out of <code>Board</code>. It has too many responsibilities: it not only is a board, but it also plays itself and carries the main program logic. Why? It fits better in your class <code>Main</code> (which I would call something like <code>KnightsTravails</code> to fit better its new purpose.</p>\n\n<p>It's clear you massed too much functionality because you had to separate it with things like this:</p>\n\n<pre><code>// ---...\n// KNIGHT TRAVAILS FUNCTIONS\n// ---...\n</code></pre>\n\n<hr>\n\n<p>Your <code>public enum PieceType</code> belongs to <code>Piece</code> just as <code>Piece.Type</code>.</p>\n\n<hr>\n\n<p>I see no reason why your notations are strings. Characters would be enough and it represents better the notion of one piece = one character in chess notation.</p>\n\n<hr>\n\n<p>I also see no reason to extend concrete pieces such as <code>Blank</code> and <code>Knight</code> since they're not encapsulating very much and just disseminate code all over the place. IMO I would just instance <code>Piece</code>s (that is, making it non-abstract) specifying WHICH piece in the constructor. To implement notation I would do like this:</p>\n\n<pre><code>private enum Type {\n BLANK (' '),\n ...\n KNIGHT ('N');\n\n private final char notation;\n Type(char notation) { this.notation = notation; }\n private char notation() { return notation; }\n}\n</code></pre>\n\n<p>It would make sense to extend in their own classes if you were actually adding specific logic to each piece (like movement types and so) but you're not doing so. Some would argue your approach offers better extensibility and reusability so your approach might be valid.</p>\n\n<hr>\n\n<p>Not sure if Java lets you do this (I think so, but can't check it) <code>moveInput.charAt(2)</code> could be written more succint as <code>moveInput[2]</code>. The same applies for many of your strings.</p>\n\n<hr>\n\n<p>What's going on in <code>getKnightNextLegalMoves</code>? Why would you bruteforce all over your board?</p>\n\n<p>If you have a source, you just have to check in <code>[1,2]; [1,-2]; [-1,2]; [-1,-2]; [2,1]; [2,-1]; [-2,1]; [-2,-1]</code>.</p>\n\n<hr>\n\n<p>Regarding <code>getKnightTravailsSolutions</code>:</p>\n\n<ol>\n<li>Although you must instance your <code>queue</code> as a <code>LinkedList</code> (or any other class implementing <code>Queue</code>), I would prefer to specify its type as the interface, i.e.: <code>Queue&lt;LinkedList&lt;Square&gt;&gt; queue = new LinkedList&lt;LinkedList&lt;Square&gt;&gt;();</code> It is more clear that it's a queue and will protect you from doing weird non-queue things. Use the queue interface (i.e. <code>poll()</code> and <code>offer()</code>) instead of <code>removeFirst()</code> and <code>addLast()</code>.</li>\n<li>It might make more sense for <code>visited</code> to be a <code>Set</code> instead (since you're enforcing it anyways when checking in <code>contains(currentSquare)</code>.</li>\n<li>This is not very important, but your <code>visited.add(currentSquare);</code> could be inside the <code>if (!solutionFound)</code> since you don't need to care about visited once you're on your last step.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T22:35:57.373", "Id": "18469", "Score": "0", "body": "Oh, I just realized you bruteforce over the board when checking for knight's possible moves because it's better, since looking up those 8 squares takes 8 searches over the board. See why it is so convoluted?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T05:24:47.043", "Id": "18476", "Score": "1", "body": "Thank you for spending time with my code and write an extensive evaluation, what a great resources! (1) Yes, I ran into the same thinking previously about using matrix instead of LinkedList for squares, but then I thought how would I store Piece? Then again, I realised I don't need to store Piece in squares to solve the actual Knight Travails problem. So, you are right LinkedList wasn't appropriate. (2) The reason I did addAll is because I can't think anything elegant to do backtracking on the breadth search function... any suggestion? Once again, thank you for your time!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T15:47:26.633", "Id": "18486", "Score": "0", "body": "@StellaLie about (2) you're completely right. I was a bit in a hurry so didn't notice the inner for loop. Removed it from the answer. About (1), I don't understand... How would you store piece? In the matrix! `Piece[][] board = new Piece[8][8];`. Although, as you just said, you don't even need pieces here but booleans (blank/horse), I kept the answer as close to your solution as possible (thus keeping `Piece`.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T21:13:08.043", "Id": "18497", "Score": "1", "body": "Bang `Piece[][] board = new Piece[8][8];`!! You are right! I completely forgot we can actually store object in an array... I'm learning heaps from this post. Thanks a lot!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T14:30:19.377", "Id": "11504", "ParentId": "11496", "Score": "3" } } ]
{ "AcceptedAnswerId": "11504", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T03:05:26.803", "Id": "11496", "Score": "3", "Tags": [ "java", "design-patterns", "object-oriented" ], "Title": "Knight's Travails solution" }
11496
<p>I recently wrote my first C# app that's goal it to take a drive letter and output a CSV list of some basic information. <code>TOTALSPACE,FREESPACE,STATUS</code>.</p> <p>I've been wondering If it would be possible to make this application even faster. Got any good suggestions?</p> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.IO; namespace drivespace { class Program { static void Main(string[] args) { //"PATHTOEXE\drivespace.exe" drive-C: foreach (String arg in args) { String[] parts = arg.Split('-'); if (parts[0].Equals("drive")) { long toalspace = 0; long freespace = 0; string status = "NOTFOUND"; foreach (DriveInfo drive in DriveInfo.GetDrives()) { if (drive.Name == parts[1] + ":\\") { if (drive.IsReady) { toalspace = drive.TotalSize; freespace = drive.TotalFreeSpace; status = "READY"; } else { status = "NOTREADY"; } break; } } //TOTALSPACE,FREESPACE,STATUS Console.WriteLine(toalspace.ToString() + "," + freespace.ToString() + ',' + status); } } } } } </code></pre> <p><a href="https://github.com/keverw/drivespace" rel="nofollow">https://github.com/keverw/drivespace</a> is the Github page, it might have some more useful info.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T02:57:43.093", "Id": "18475", "Score": "0", "body": "I'm assuming that `DriveInfo` is a `class`..... Possibly provide us with that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T23:17:44.217", "Id": "18499", "Score": "0", "body": "Program.cs is the whole program." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T00:17:42.523", "Id": "18501", "Score": "0", "body": "But `DriveInfo` isn't built into c#" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T04:15:38.780", "Id": "18506", "Score": "0", "body": "It's part of System.IO, http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T12:33:16.397", "Id": "18521", "Score": "0", "body": "Oh sorry for my cluelessness" } ]
[ { "body": "<p>It is possible to make the application faster (but I am not sure that you will notice the difference unless you call the application with many arguments and have many drives). The main problem with the code is that you iterate through all the arguments, and for each argument you iterate through all the drives until you find the matching drive-letter. </p>\n\n<p>So if the the application is called with an unknown drive-letter 10 times (as in <code>\"PATHTOEXE\\drivespace.exe\" drive-X drive-X drive-X drive-X ...</code> and if you have 15 drives mounted, then <code>DriveInfo.GetDrives()</code> will be called 10 times and the line <code>if (drive.Name == parts[1] + \":\\\\\")</code> will be executed 150 times. To avoid this you could store the drive information in a dictionary and then just lookup the matching drive in near constant time.</p>\n\n<p>Notice below that I have changed the format of the arguments to the application to <code>DriveSpace.exe C D X</code> to avoid the parsing of the individual argument.</p>\n\n<pre><code>using System;\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\n\nnamespace Drivespace\n{\n class Program\n {\n static void Main(string[] args)\n {\n var allDrives = DriveInfo.GetDrives().ToDictionary(drive =&gt; drive.Name);\n\n foreach (String arg in args)\n {\n DriveInfo driveInfo;\n if (allDrives.TryGetValue(arg + @\":\\\", out driveInfo))\n {\n if (driveInfo.IsReady)\n {\n WriteOutput(driveInfo.TotalSize, driveInfo.TotalFreeSpace, \"READY\");\n }\n else\n {\n WriteOutput(0, 0, \"NOTREADY\");\n }\n }\n else\n {\n WriteOutput(0, 0, \"NOTFOUND\");\n }\n }\n }\n\n private static void WriteOutput(long totalSize, long freeSpace, string status)\n {\n Console.WriteLine(String.Format(\"{0},{1},{2}\", totalSize, freeSpace, status));\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T19:15:26.710", "Id": "11571", "ParentId": "11498", "Score": "2" } }, { "body": "<p>Here's a really squished down version of the code that should run a bit quicker too.</p>\n\n<pre><code> private static void Main(string[] args)\n {\n // \"PATHTOEXE\\drivespace.exe\" drive-C\n var driveInfo = DriveInfo.GetDrives().ToDictionary(drive =&gt; drive.Name);\n\n foreach (var drive in args\n .Select(arg =&gt; arg.ToUpperInvariant().Split('-'))\n .Where(parts =&gt; (parts.Length == 2) &amp;&amp; parts[0].Equals(\"DRIVE\") &amp;&amp; driveInfo.ContainsKey(parts[1] + \":\\\\\"))\n .Select(parts =&gt; driveInfo[parts[1] + \":\\\\\"]))\n {\n // TOTALSPACE,FREESPACE,STATUS\n Console.WriteLine(\n (drive.IsReady ? drive.TotalSize : 0L) + \",\" +\n (drive.IsReady ? drive.TotalFreeSpace : 0L) + \",\" +\n (drive.IsReady ? \"READY\" : \"NOTREADY\"));\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T19:56:58.700", "Id": "11572", "ParentId": "11498", "Score": "2" } }, { "body": "<p>To take Jesse C. Slicer's answer a bit further.. I cleaned up the code to use constants and string.Format... It makes more sense from an architectural stand point. Sealing the class is also a performance boost for JIT, but the benefit should be minimal at best. As stated in this other stack overflow post, it's more of a late result type of performance enhancement. You more than likely won't see anything from it.</p>\n\n<pre><code>internal sealed class Program\n {\n private const string READY = \"READY\";\n private const string NOT_READY = \"NOTREADY\";\n private const string DRIVE = \"DRIVE\";\n\n private static void Main(string[] args)\n {\n var driveInfoDictionary = DriveInfo.GetDrives().ToDictionary(d =&gt; d.Name);\n\n foreach (var drive in args\n .Select(arg =&gt; arg.ToUpperInvariant().Split('-'))\n .Where(parts =&gt; (parts.Length == 2) &amp;&amp; parts[0].Equals(DRIVE) &amp;&amp; driveInfoDictionary.ContainsKey(string.Format(\"{0}:\\\\\", parts[1])))\n .Select(parts =&gt; driveInfoDictionary[string.Format(\"{0}:\\\\\", parts[1])]))\n Console.WriteLine(\"{0},{1},{2}\",\n (drive.IsReady ? drive.TotalSize : 0L),\n (drive.IsReady ? drive.TotalFreeSpace : 0L),\n (drive.IsReady ? READY : NOT_READY));\n }\n }\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/2134/do-sealed-classes-really-offer-performance-benefits\">https://stackoverflow.com/questions/2134/do-sealed-classes-really-offer-performance-benefits</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T21:15:43.467", "Id": "18788", "Score": "0", "body": "Better yet, make it a `static` class since there are no instance methods or data." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T19:30:22.603", "Id": "11702", "ParentId": "11498", "Score": "0" } } ]
{ "AcceptedAnswerId": "11572", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T05:29:49.003", "Id": "11498", "Score": "3", "Tags": [ "c#" ], "Title": "Optimize DriveSpace Checker" }
11498
<p>This program downloads a Code Review HTML file and parses it.</p> <p>Could you review my program?</p> <p>Main.java</p> <pre><code>import java.net.URL; public class Main { public static void main(String[] args) throws Exception { final String site1 = "http://codereview.stackexchange.com/questions/"; String site2; String site3; URL url; HtmlGetter htmlGetter = new HtmlGetter(); while(true) { site2 = "69"; site3 = "is-this-implementation-of-shamos-hoey-algorithm-ok"; url = new URL(site1 + site2 + "/" + site3); htmlGetter.setFileName("[" + site2 + "]" + site3 + ".html"); htmlGetter.download(url); htmlGetter.parse(); break; } } } </code></pre> <p>HtmlGetter.java</p> <pre><code>import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.net.URL; import java.util.Scanner; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.io.IOUtils; public class HtmlGetter { private String fileName; public void setFileName(String fileName) { this.fileName = fileName; } public String getFileName() { return fileName; } public void download(URL url) throws Exception { final InputStream in = url.openStream(); final OutputStream out = new FileOutputStream(fileName); IOUtils.copy(in, out); in.close(); out.close(); } public void parse() throws Exception { Scanner scanner = new Scanner(new File(fileName)); String oneLine; String htmlTagRegex = "&lt;(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^&gt;]*)?(\\s)*(/)?&gt;"; while(scanner.hasNextLine()) { oneLine = scanner.nextLine(); if(oneLine.matches(".*&lt;code&gt;.*")) { while(scanner.hasNextLine()&amp;&amp;(!oneLine.matches(".*&lt;/code&gt;.*"))) { oneLine = StringEscapeUtils.unescapeHtml4(oneLine.replaceAll(htmlTagRegex, "")); System.out.println(oneLine); oneLine = scanner.nextLine(); // This cannot handle such kind of a line which has &lt;code&gt; and &lt;/code&gt; together. } System.out.println("-------------------------------------------"); } } } } </code></pre>
[]
[ { "body": "<pre><code>public static void main(String[] args) throws Exception {\n final String site1 = \"http://codereview.stackexchange.com/questions/\";\n String site2;\n String site3;\n</code></pre>\n\n<p>Why do define site1 as a final constant, but delay the other assignments until later? They should really be static finals for the class. Also some clearer names would not go amiss.</p>\n\n<pre><code> URL url;\n</code></pre>\n\n<p>Declare them where they are used, don't declare them ahead of time.</p>\n\n<pre><code> HtmlGetter htmlGetter = new HtmlGetter();\n\n while(true) {\n site2 = \"69\";\n site3 = \"is-this-implementation-of-shamos-hoey-algorithm-ok\";\n url = new URL(site1 + site2 + \"/\" + site3);\n htmlGetter.setFileName(\"[\" + site2 + \"]\" + site3 + \".html\");\n htmlGetter.download(url);\n htmlGetter.parse();\n break;\n</code></pre>\n\n<p>Why do you have a loop if you are just going to break out of it?\n }\n }</p>\n\n<pre><code>public void parse() throws Exception {\n</code></pre>\n\n<p>You shouldn't throw Exception, your specification should really only include the exceptions that'll actually be thrown</p>\n\n<pre><code> Scanner scanner = new Scanner(new File(fileName));\n String oneLine;\n String htmlTagRegex = \"&lt;(/)?([a-zA-Z]*)(\\\\s[a-zA-Z]*=[^&gt;]*)?(\\\\s)*(/)?&gt;\";\n</code></pre>\n\n<p>Parsing HTML by regex is asking for trouble. Instead, you'll find the task much easier if you grab a html parsing library and use that. </p>\n\n<pre><code> while(scanner.hasNextLine()) {\n oneLine = scanner.nextLine();\n if(oneLine.matches(\".*&lt;code&gt;.*\")) {\n</code></pre>\n\n<p>You are just searching for a substring here, there isn't much point in using regex to do that.</p>\n\n<pre><code> while(scanner.hasNextLine()&amp;&amp;(!oneLine.matches(\".*&lt;/code&gt;.*\"))) {\n</code></pre>\n\n<p>If you insist on regex, use a single regex to capture the entire code tag. </p>\n\n<pre><code> oneLine = StringEscapeUtils.unescapeHtml4(oneLine.replaceAll(htmlTagRegex, \"\"));\n System.out.println(oneLine);\n oneLine = scanner.nextLine();\n // This cannot handle such kind of a line which has &lt;code&gt; and &lt;/code&gt; together.\n }\n System.out.println(\"-------------------------------------------\");\n }\n } \n}\n</code></pre>\n\n<p>Using something like jsoup: <a href=\"http://jsoup.org/\" rel=\"nofollow\">http://jsoup.org/</a></p>\n\n<pre><code>Document question = Jsoup.connect(\"http://codereview.stackexchange.com/questions/69\").get();\nElements codes = question.select(\"code\")\nfor(Element code: codes)\n{\n System.out.println(code.text())\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T00:39:00.633", "Id": "11513", "ParentId": "11501", "Score": "3" } } ]
{ "AcceptedAnswerId": "11513", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T08:35:35.267", "Id": "11501", "Score": "2", "Tags": [ "java", "html", "parsing", "regex", "web-scraping" ], "Title": "HTML downloader and parser for CR" }
11501
<p>A little while ago I wrote some jQuery code to make a div flip (similar to the Apple Dashboard). I know there is already code that has this idea from Jon Raasch, but this code positioned divs absolutely, which I did not need for my cause.</p> <p>I just wondered if anyone could give me some advice as to how to tidy this up and make it cleaner.</p> <pre><code>(function ($) { $.fn.extend({ jFlip: function (options) { var defaults = { trigF: '.flipDiv', trigB: '.flipDivBack' }; var o = $.extend({}, defaults, options); return this.each(function () { var f = $('.front'); b = $('.back'); margin = f.width() / 2; width = f.width(); height = f.height(); b.hide().css({ width: '0px', height: '' + height + 'px', marginLeft: '' + margin + 'px', opacity: '0' }); $(o.trigF).on('click', function () { var $this = $(this); $this.parents().closest(f).animate({ width: '0px', height: '' + height + 'px', marginLeft: '' + margin + 'px', opacity: '0' }, { duration: 500 }); window.setTimeout(function () { $this.parents().next(b).animate({ width: '' + width + 'px', height: '' + height + 'px', marginLeft: '0px', opacity: '1' }, { duration: 500 }); }, 500); }); $(o.trigB).on('click', function () { $(this).parents().closest(b).animate({ width: '0px', height: '' + height + 'px', marginLeft: '' +margin + 'px', opacity: '0', display: 'none' }, { duration: 500 }); var $this = $(this).parents().siblings(f); window.setTimeout(function () { $this.stop().animate({ width: '' + width + 'px', height: '' + height + 'px', marginLeft: '0px', opacity: '1' }, { duration: 500 }); }, 500); }); }); } }); })(jQuery); </code></pre> <p>The <code>div</code> structure is this:</p> <pre><code>&lt;div class="widgetBox"&gt; &lt;div class="front"&gt; &lt;p&gt;Front of the div&lt;/p&gt; &lt;button class="flipDiv"&gt;Flip&lt;/button&gt; &lt;/div&gt; &lt;div class="back"&gt; &lt;p&gt;Back of the div&lt;/p&gt; &lt;button class="flipDivBack"&gt;Flip Back&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>And this is the initiation:</p> <pre><code>&lt;script&gt; $(document).ready(function() { $('.widgetBox').jFlip(); }); &lt;/script&gt; </code></pre> <p>The only options as of yet however are trigF and trigB, which allows you to specify the name of your buttons which will flip the div.</p> <p>You can see a jsFiddle of this in action <a href="http://jsfiddle.net/ctRaZ/1" rel="nofollow noreferrer">here</a>.</p>
[]
[ { "body": "<p>Looks cool, nice job!</p>\n\n<p>One this I would say is that the plugin makes too many assumptions about the client's DOM structure. Having fixed selectors like <code>$('.front')</code> and <code>$('.back')</code> within your plugin script is dangerous -- what if I'm working in a page that has a <code>'front'</code> class on the body?</p>\n\n<p>It's best to let the client pass in exactly what DOM elements they want to manipulate. You could, for example, do something like this:</p>\n\n<p>The html:</p>\n\n<pre><code>&lt;div id=\"flipper\"&gt;\n &lt;div data-face=\"front\"&gt;I'm in front!&lt;/div&gt;\n &lt;div data-face=\"back\"&gt;I'm in back!&lt;/div&gt;\n&lt;/div&gt;&lt;!-- end #flipper --&gt;\n</code></pre>\n\n<p>The initialization:</p>\n\n<pre><code>$('#flipper').jFlip();\n</code></pre>\n\n<p>In your plugin script, you now know exactly which elements the client wants to work with:</p>\n\n<pre><code>...\nreturn this.each(function() {\n ...\n $flipper = $(this);\n $front = $flipper.find('[data-face=front]:first');\n $back = $flipper.find('[data-face=back]:first');\n ...\n});\n</code></pre>\n\n<p>Now you don't have to deal with any pesky DOM tree traversal, which carries a risk of finding the wrong element.</p>\n\n<p>A couple other notes:</p>\n\n<ul>\n<li>When you're specifying css attrs with jquery, <code>height:\nsomeNumberVariable</code> works just fine. You don't need to wrap it with\n<code>'' + someNumberVar + 'px'</code></li>\n<li>Why not set the duration as an optional param?</li>\n<li>It would be nice to have a <code>$('#myEl').jsFlip('flip')</code> method. Adding methods like this will add some complexity to your code, but the good news is there are some good plugin patterns out there that you can work off of. IMO, this is the <a href=\"http://alexsexton.com/blog/2010/02/using-inheritance-patterns-to-organize-large-jquery-applications/\">prettiest one</a> I've seen.</li>\n<li>Once you've figured out how to add methods to your plugin, it's fairly simple (and best practice) to add a 'destroy' method, that would unbind all of your event handlers. To do this, you need to <a href=\"http://docs.jquery.com/Namespaced_Events\">namespace</a> your events. </li>\n</ul>\n\n<p>For example:</p>\n\n<p>to bind: <code>$flipBtn.on('click.jFlip', function() { ... })</code></p>\n\n<p>to destroy: <code>$flipBtn.off('.jFlip'); // unbind all events in .jFlip namespace</code></p>\n\n<p>One other thing: this plugin replicates the functionality of <a href=\"http://line25.com/articles/super-cool-css-flip-effect-with-webkit-animation\">existing CSS3 animations</a>, which will always be faster. This plugin is still useful as a fallback for browsers that are not up to speed on CSS3, but it would be best to check for that capability first, and implement with CSS3 if available.</p>\n\n<p>I hope this is helpful. Keep on rocking the plugins!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T08:54:00.287", "Id": "18572", "Score": "0", "body": "Thanks! Really useful advice, will definitely work on this advice! In terms of the CSS3 animations, I completely agree, though most browsers only support 2D animations? This is faux-3D animations but works right down to IE6. This plugin was built off the back of a project which needed the code to be as compatible as possible. But for sure, the part about DOM tree traversal will be used as it is a much cleaner way of doing it, though on your third point about using `.jsFlip('flip')`, Im not sure I understand what you mean?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T11:00:12.343", "Id": "18579", "Score": "0", "body": "Take a look at this on plugin methods: http://goo.gl/Z2MUu. Current versions of Chrome, Safari, and FF support 3d transforms: http://caniuse.com/#search=3dtran. It may be worthwhile to detect the user's browser, then either apply the animations, or add css3 3d transform properties to the .front/.back elements" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T11:27:47.943", "Id": "18581", "Score": "0", "body": "I've just put in the `data-face`, however now it's lost the ability to have multiple instances of the flipping div. Also, I will look at using 3D transforms and using this as a backup, then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T21:07:26.507", "Id": "18678", "Score": "0", "body": "Can you post the updated code to jsfiddle.com? I'll take a look." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T11:02:46.987", "Id": "18699", "Score": "0", "body": "Hi edan, thanks mate. If you look [here](http://jsfiddle.net/ZmLZy/) you can see my problem.\n \nYou click on the top div's `flip` button and it flips the bottom, then it just.. goes a bit crazy!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T15:25:24.737", "Id": "11562", "ParentId": "11502", "Score": "6" } }, { "body": "<p><strong>Note</strong>: I wrote my answer before reading <a href=\"https://codereview.stackexchange.com/a/11562/10860\">edan's answer</a>, which heavily influenced the code in the updated question. As a result my answer is more of an addition to edan's answer rather than being independent and focusing on the author's original code.</p>\n<h2>Creating the Plugin</h2>\n<p>jQuery plugins are usually created with the following syntax, <code>$.fn.pluginName</code>. It is the <a href=\"http://docs.jquery.com/Plugins/Authoring#Getting_Started\" rel=\"nofollow noreferrer\">preferred way</a> because it directly extends <code>jQuery.prototype</code> and is common javascript syntax. By using <code>$.extend</code> you may run into speed issues and other problems.</p>\n<h2>Moving the Default Options</h2>\n<p>I moved your default settings outside of the plugin's function. In addition, I changed the names from <code>['trigF', 'trigB']</code> to <code>['trigger_front', 'trigger_back']</code> so they are a bit more clear.</p>\n<pre><code>// allow global options\n$.fn.divFlip.defaults = {\n trigger_front: '.flipDiv',\n trigger_back: '.flipDivBack',\n duration: 500\n};\n\n// inside of the plugin's function\noptions = $.extend($.fn.divFlip.defaults, options);\n</code></pre>\n<p>Doing this will not break your code and its primary advantage is that whoever uses your plugin can define their own defaults.</p>\n<p>For instance, if I wanted to make the default duration of the plugin 200ms, I could simply run. <code>$.fn.divFlip.defaults.duration = 200;</code></p>\n<h2>Defining the Variables</h2>\n<p>Most of what I changed in your variables were a personal preference.</p>\n<ol>\n<li><p>Your <code>$front</code> and <code>$back</code> variables don't need the <code>:first</code> selector. The markup for the <code>div.widgetBox</code> only has one front and back face. Which means selecting the first one is unnecessary.</p>\n</li>\n<li><p>I added variables for your front and back triggers to help consolidate all of the selectors. It isn't a necessary change, simply how I roll :)</p>\n</li>\n</ol>\n<pre>// find the triggers\n$front_trigger = $front.find(options.trigger_front),\n$back_trigger = $back.find(options.trigger_back),</pre>\n<h2>The Big Change</h2>\n<p>The biggest change that I made to your plugin is the way the animations are handled. <a href=\"http://api.jquery.com/animate/\" rel=\"nofollow noreferrer\">$.fn.animate()</a>'s third parameter allows a callback function that runs after the animation has completed. Which means you didn't need to create a <code>setTimeout</code> to manually show the next face.</p>\n<p>In addition, because you are showing and and hiding alternative faces, I rewrote the function to automatically switch between the front and back.</p>\n<h2>My Final Code (<a href=\"http://jsfiddle.net/BaylorRae/KdrtX/1/\" rel=\"nofollow noreferrer\">View jsFiddle</a>)</h2>\n<p>Here is the code that I came up with in the end. As you can see it is a lot more <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\" title=\"Don't repeat yourself\">DRY</a> and should make it easier to add new features and options later on.</p>\n<pre><code>(function($) {\n\n $.fn.divFlip = function(options) {\n\n // set the default options with the ones specified\n options = $.extend($.fn.divFlip.defaults, options);\n\n return this.each(function() {\n \n // get the main elements\n var $flipDiv = $(this),\n $front = $flipDiv.find('[data-face=front]'),\n $back = $flipDiv.find('[data-face=back]'),\n \n // find the triggers\n $front_trigger = $front.find(options.trigger_front),\n $back_trigger = $back.find(options.trigger_back),\n \n // get the dimensions\n front_width = $front.width(),\n front_height = $front.height(),\n margin = front_width / 2;\n \n // hide the back slide\n $back.css({\n width: 0,\n height: front_height,\n marginLeft: margin,\n opacity: 0\n });\n \n // catch all clicks for the triggers\n $([$front_trigger.get(0), $back_trigger.get(0)]).on('click', function() {\n \n // by default show the back and hide the front slide\n var toShow = $back,\n toHide = $front;\n \n // clicked on the back trigger\n if( this == $back_trigger.get(0) ) {\n toShow = $front;\n toHide = $back;\n }\n \n // hide the visible slide\n toHide.animate({\n width: 0,\n height: front_height,\n marginLeft: margin,\n opacity: 0\n }, options.duration, function() {\n \n // show the hidden slide\n toShow.animate({\n width: front_width,\n height: front_height,\n marginLeft: 0,\n opacity: 1\n }, options.duration);\n });\n });\n });\n };\n\n // allow global options\n $.fn.divFlip.defaults = {\n trigger_front: '.flipDiv',\n trigger_back: '.flipDivBack',\n duration: 500\n };\n\n})(jQuery);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T20:47:37.017", "Id": "11817", "ParentId": "11502", "Score": "1" } } ]
{ "AcceptedAnswerId": "11562", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T11:23:27.383", "Id": "11502", "Score": "4", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "jQuery 'flip' plugin" }
11502
<p>I only recently started coding so I know my code is not very good, but i would really appreciate any help on improving my code.</p> <p>my database table looks like this game_id |title |developer |publisher |genre |release_date |platform </p> <p>rating |image_location |description</p> <p>the first page this page is pretty straightforward your typical search that links to the search page and passes the keywords entered through GET</p> <pre><code>&lt;div id=\"top_search\"&gt; &lt;form name=\"input\" action=\"search.php\" method=\"get\" id=\"search_form\"&gt; &lt;input type=\"text\" id=\"keywords\" name=\"keywords\" size=\"128\" class=\"searchbox\" value=\"$defaultText\"&gt; &amp;nbsp; &lt;select id=\category\" name=\"category\" class=\"searchbox\"&gt; "; createCategoryList(); echo ' &lt;/select&gt; &amp;nbsp; &lt;input type="submit" value="Search" class="button" /&gt; &amp;nbsp; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>the second page is the search page this is where things got complicated for me.Here is what i did i created a buch of links on the left side, each link submits back to the same page but passes 4 variables with them which i use on the third page to create the query.As you can see its not very pretty.</p> <pre><code>&lt;?php session_start(); include("includes/html_codes.php"); include ("includes/search_func.php"); if (isset($_GET['keywords'])){ $keywords = mysql_real_escape_string(htmlentities(trim($_GET['keywords']))); } if (isset($_GET['order'])){ $order = mysql_real_escape_string(htmlentities(trim($_GET['order']))); }else{ $order = ''; } if (isset($_GET['platform'])){ $platform = mysql_real_escape_string(htmlentities(trim($_GET['platform']))); }else{ $platform = ''; } if (isset($_GET['genre'])){ $genre = mysql_real_escape_string(htmlentities(trim($_GET['genre']))); }else{ $genre = ''; } $errors = array(); if(empty($keywords)){ $errors[] = 'Please enter a search term'; }else if(strlen($keywords)&lt;3){ $errors[] = 'Your search term must be at least 3 characters long'; }else if(search_results($keywords) == false){ $errors[] = 'Your search for'.$keywords.' returned no results'; } if(empty($errors)){ $results = search_results($keywords); $results_num = count($results); }else{ foreach($errors as $error){ echo $error, '&lt;br /&gt;'; } } ?&gt; &lt;!DOCTYPE html &gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;Search&lt;/title&gt; &lt;link rel="stylesheet" href="css/main.css"&gt; &lt;link rel="stylesheet" href="css/search.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;?php topBanner(); ?&gt; &lt;div id="wrapper"&gt; &lt;?php headerAndSearchCode(); echo $_SERVER['QUERY_STRING']; echo $keywords; ?&gt; &lt;div id="main_section" class="header"&gt; &lt;?php echo ' &lt;div id="filter_nav"&gt; &lt;ul id="nav_form"&gt; &lt;li&gt;&lt;h3 id="h3"&gt;Genre: &amp;nbsp;&lt;/h3&gt; &lt;li&gt;&lt;a href="search.php?keywords='.$keywords.'&amp;platform='.$platform.'&amp;genre=Fighting&amp;order='.$order.'"&gt;Fighting&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="search.php?keywords='.$keywords.'&amp;platform='.$platform.'&amp;genre=Role-Playing&amp;order='.$order.'"&gt;Role-Playing&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="search.php?keywords='.$keywords.'&amp;platform='.$platform.'&amp;genre=Action&amp;order='.$order.'"&gt;Action&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul id="nav_form"&gt; &lt;li&gt;&lt;h3 id="h3"&gt;Platform: &amp;nbsp;&lt;/h3&gt; &lt;li&gt;&lt;a href="search.php?keywords='.$keywords.'&amp;platform=Playstation 3&amp;genre='.$genre.'&amp;order='.$order.'"&gt;PS3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="search.php?keywords='.$keywords.'&amp;platform=xbox 360&amp;genre='.$genre.'&amp;order='.$order.'"&gt;Xbox 360&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="search.php?keywords='.$keywords.'&amp;platform=Gamecube&amp;genre='.$genre.'&amp;order='.$order.'"&gt;Gamecube&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; '; echo ' &lt;ul id="sorting_form"&gt; &lt;li&gt;&lt;h3 id="h3"&gt;SORT BY: &amp;nbsp;&lt;/h3&gt; &lt;li&gt;&lt;a href="search.php?keywords='.$keywords.'&amp;platform='.$platform.'&amp;genre='.$genre.'&amp;order=title"&gt;Title&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="search.php?keywords='.$keywords.'&amp;platform='.$platform.'&amp;genre='.$genre.'&amp;order=release_date"&gt;Date&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="search.php?keywords='.$keywords.'&amp;platform='.$platform.'&amp;genre='.$genre.'&amp;order=rating"&gt;Rating&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; '; echo '&lt;div id="results"&gt;'; foreach($results as $result ){ echo ' &lt;div id="game_result"&gt; &lt;a href= game_page.php?game_id='.$result['game_id'].'&gt;&lt;img src= '.$result['image_location'].' id="image" /&gt;&lt;/a&gt; &lt;div id="main_title"&gt; &lt;a href= game_page.php?game_id='.$result['game_id'].'&gt;&lt;h2 id="game_title"&gt;'.$result['title'].'&amp;nbsp; &amp;nbsp;&lt;/h2&gt;&lt;/a&gt; &lt;h3 id="platform"&gt;for &amp;nbsp;'.$result['platform'].'&lt;/h3&gt; &lt;/div&gt; &lt;p id=game_description&gt;'.$result['description'].'&lt;/p&gt; &lt;div id="right_side"&gt; &lt;h4 id="rating"&gt;'.$result['rating'].'&lt;/h4&gt; &lt;/div&gt; &lt;hr id="hr"/&gt; &lt;/div&gt; '; } echo '&lt;/div&gt;';;?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p> `</p> <p>page three is where i query the database and get results. Not as bad as page 2</p> <pre><code>function search_results($keywords){ $returned_results = array(); $where = ""; $keywords = preg_split('/[\s]+/', $keywords); $total_keywords = count($keywords); foreach($keywords as $key=&gt;$keyword){ $where .= "title LIKE '%$keyword%'"; if($key != ($total_keywords - 1)){ $where .= " AND "; } } if (isset($_GET['platform']) &amp;&amp; !empty($_GET['platform'])){ $platform = mysql_real_escape_string(htmlentities(trim($_GET['platform']))); $where .= " AND platform='$platform'"; } if (isset($_GET['genre']) &amp;&amp; !empty($_GET['genre'])){ $genre = mysql_real_escape_string(htmlentities(trim($_GET['genre']))); $where .= " AND genre='$genre'"; } if (isset($_GET['order']) &amp;&amp; !empty($_GET['order'])){ $order = mysql_real_escape_string(htmlentities(trim($_GET['order']))); if($where == " ORDER BY $order ASC"){ $where .= " ORDER BY $order DESC"; }else{ $where .= " ORDER BY $order ASC"; } } $results ="SELECT * FROM games WHERE $where "; echo $results; $results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0; if($results_num === 0){ return false; }else{ while($row = mysql_fetch_assoc($results)){ $returned_results[] = array( 'game_id' =&gt; $row['game_id'], 'title' =&gt; $row['title'], 'platform' =&gt; $row['platform'], 'rating' =&gt; $row['rating'], 'image_location' =&gt; $row['image_location'], 'description' =&gt; $row['description'], ); } return $returned_results; } } ?&gt; </code></pre> <p>Things i need help with </p> <ul> <li>being able to remove a chosen filter category</li> <li>easier way to pass variables to the query string</li> <li>better way to structure a filter for mysql</li> <li>any feedback that will help me improve my code</li> </ul> <p>thanks</p>
[]
[ { "body": "<p>here's a quick run down on your script from my perspective. Hopefully it will help you out and make your code a bit more efficient and a little prettier! :)</p>\n\n<p>Whilst admirable that you are attempting to stop SQL injection attacks with <code>mysql_real_escape_string()</code> it is really not the best method to protect yourself. Consider instead using prepared statements with PDO, believe me learning this will save you a lot of time!</p>\n\n<p>You also repeat alot of code, for example this line pops up a lot.\n<code>$keywords = mysql_real_escape_string(htmlentities(trim($_GET[$x])));</code></p>\n\n<p>Why not put it into a function?</p>\n\n<pre><code>function prepVar($var) {\n return mysql_real_escape_string(htmlentities(trim($var)));\n}\n</code></pre>\n\n<p>and then just use</p>\n\n<pre><code>$platform = prepVar($_GET['platform']);\n</code></pre>\n\n<p>Another few pointers on <code>isset</code> and <code>empty</code>. You've explicitly asked for a variable to be set and not empty. (check this article out: <a href=\"http://www.htmlcenter.com/blog/empty-and-isset-in-php/\" rel=\"nofollow\">http://www.htmlcenter.com/blog/empty-and-isset-in-php/</a>)</p>\n\n<p><code>isset</code> will return TRUE if the variable has a type i.e. String, Object etc. i.e. the variable already exists in the scope.</p>\n\n<p><code>empty</code> will return TRUE if the variable === 0 || === false || === null</p>\n\n<p>As (in this case) <code>empty</code> will return true if the variable is not set (as the var would === null). You only need to use <code>empty</code>.</p>\n\n<pre><code>$platform = $_GET['platform'];\n$platform = !empty($platform) ? prepVar($platform) : '';\n</code></pre>\n\n<p>The same principles can be applied to your third page with the added complication of adding the <code>$where</code> variable to each of the operations.</p>\n\n<pre><code>if (!empty($platform)) {\n $platform = prepVar($platform);\n $where .= \"platform = '{$platform}'\";\n}\n</code></pre>\n\n<p>I don't understand this bit of code:</p>\n\n<pre><code>if (isset($_GET['order']) &amp;&amp; !empty($_GET['order'])){\n $order = mysql_real_escape_string(htmlentities(trim($_GET['order'])));\n if($where == \" ORDER BY $order ASC\"){\n $where .= \" ORDER BY $order DESC\";\n }else{\n $where .= \" ORDER BY $order ASC\";\n }\n}\n</code></pre>\n\n<p>Are you sure you want to be checking <code>$where</code> for a value, if it contains that value append a second ORDER BY statement to it? That doesn't make much sense :(</p>\n\n<p>Removing a filter category</p>\n\n<p>I would save the search state to <code>$_SESSION</code> each time it is run through your function. You can then recall the previous search state, modify it and then run that through your query again allowing you to remove / change / add as much or as little as you want.</p>\n\n<p>Easier ways to pass to your query string</p>\n\n<p>Firstly you are asking for the same information within your function as you are within the procedural code on your second page. </p>\n\n<pre><code>if (isset($_GET['platform']) &amp;&amp; !empty($_GET['platform'])){ ...\n</code></pre>\n\n<p>As you already have variables that have been mildly sanitised with <code>mysql_real_escape_string()</code> why not pass them to the function as variables as well. Or declare them global variables within the function? In essence the easier way is to make sure you are not duplication your code, setting a variable once and using that variable throughout your script will yield greater stability of your application in the long run.</p>\n\n<p>Better way to structure a filter for mySQL</p>\n\n<p>I dont see a problem with the way you are structuring it, personally I prefer to use functions to decorate SQL queries. In honesty it is each to there own!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T17:23:44.967", "Id": "11533", "ParentId": "11503", "Score": "1" } } ]
{ "AcceptedAnswerId": "11533", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T05:14:16.127", "Id": "11503", "Score": "2", "Tags": [ "php", "mysql", "search" ], "Title": "need help improving mysql and php filter code" }
11503
<p>I've an <code>IEnumerable&lt;T&gt;</code> source which takes time to generate each item. Once an item is generated, I want to cache it to avoid recomputing the same thing. I want to separate out caching logic from original source.</p> <p>A few things that bother me are:</p> <ol> <li>Where should I have <code>_cache</code>? In <code>CachedEnumerable</code> or <code>CacheEnumerator</code>?</li> <li>Thread safety in adding into cache.</li> <li>Reinventing? Any existing .NET or other library which does this.</li> <li>Why <code>Dispose</code> in <code>IEnumerator</code>? Should I be doing something there? <code>_cache</code> nuke?</li> </ol> <p></p> <pre><code>class CachedEnumerable&lt;T&gt; : IEnumerable&lt;T&gt; { private IList&lt;T&gt; _cache = new List&lt;T&gt;(); IEnumerator&lt;T&gt; _cacheEnumerator = null; IEnumerable&lt;T&gt; _source = null; public CachedEnumerable(IEnumerable&lt;T&gt; source) { _source = source; _cacheEnumerator = _source.GetEnumerator(); } public IEnumerator&lt;T&gt; GetEnumerator() { return new CachedEnumerator&lt;T&gt;(_cache, _cacheEnumerator); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } class CachedEnumerator&lt;T&gt; : IEnumerator&lt;T&gt; { private IList&lt;T&gt; _cache; private IEnumerator&lt;T&gt; _source; private T _current; private int _index; private bool _moveNextStatus; public CachedEnumerator(IList&lt;T&gt; cache, IEnumerator&lt;T&gt; source) { _cache = cache; _source = source; Reset(); } public T Current { get { if (_moveNextStatus) { return _current; } else { throw new InvalidOperationException(); } } } public void Dispose() { _source.Dispose(); } object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { _moveNextStatus = _MoveNext(); return _moveNextStatus; } private bool _MoveNext() { _index++; if (_index &lt; _cache.Count) { _current = _cache[_index]; return true; } else { if (_source.MoveNext()) { _current = _source.Current; _cache.Add(_current); return true; } else { return false; } } } public void Reset() { _index = -1; _current = default(T); _moveNextStatus = false; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T09:46:47.427", "Id": "18576", "Score": "3", "body": "The idea of IEnumerable is that it is lazy and executed on command. If you want to cache data, then why not put it in a List? You can then write further queries onto your list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T14:52:57.990", "Id": "36233", "Score": "2", "body": "A bit late to the party, but here's an implementation that I found that was done quite well. It is thread safe, lazy, and licensed under MS-PL. https://gist.github.com/AArnott/118348 It's got some nice advantages over your code, such as not caching the IEnumerable if it's already a list, array, etc. Only calling GetEnumerator in the CachedEnumerator's GetEnumerator instead of the constructor, implements Dispose with more intuitive behavior, and, as mentioned before, is thread safe" } ]
[ { "body": "<p>You do not have to go to all this trouble to implement a caching wrapper. It can be done much more simply:</p>\n\n<pre><code>class CachedEnumerable&lt;T&gt; : IEnumerable&lt;T&gt; \n{\n private readonly IEnumerable&lt;T&gt; producer;\n private IEnumerable&lt;T&gt; cache;\n\n public CachedEnumerable(IEnumerable&lt;T&gt; producer)\n {\n this.producer = producer;\n }\n\n public IEnumerator&lt;T&gt; GetEnumerator()\n {\n if (!this.IsCacheValid()) {\n this.cache = this.producer.ToList();\n }\n\n return this.cache.GetEnumerator();\n }\n\n protected virtual bool IsCacheValid()\n {\n return this.cache != null;\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return this.GetEnumerator();\n }\n}\n</code></pre>\n\n<p>This implementation has a cache that never expires, but you can modify (or override in a derived class) <code>IsCacheValid</code> to tweak this behavior to taste. It also has no thread safety, but that's as easy to add as</p>\n\n<pre><code>// need to make this always have a non-null value so it can be \n// used as a parameter to Monitor.Enter\nprivate IEnumerable&lt;T&gt; cache = new T[0];\n\npublic IEnumerator&lt;T&gt; GetEnumerator()\n{\n lock (this.cache) {\n if (!this.IsCacheValid()) {\n this.cache = this.producer.ToList();\n }\n\n return this.cache.GetEnumerator();\n }\n}\n</code></pre>\n\n<p>If <code>IsCacheValid</code> were <code>private</code> then the <code>lock</code> could be reduced to protecting just the <code>this.producer.ToList()</code> statement, but as it stands it must protect everything inside <code>GetEnumerator</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T05:36:23.853", "Id": "18477", "Score": "2", "body": "I can't invoke this.producer.ToList() This will take a lot of time. That's why I'm going through the trouble to MoveNext(). Caller's of this API usually call this using producer.Take(n)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T00:50:21.863", "Id": "11514", "ParentId": "11505", "Score": "1" } }, { "body": "<ol>\n<li>You need to access <code>_cache</code> in both classes, so it makes sense to have it as field in both of them too.</li>\n<li>Your code is not thread safe. If you wanted to make it thread safe, I think the best solution would be to have a lock that you use whenever you access <code>_cache</code> or <code>_source</code>.</li>\n<li>I don't think anything like this is in .Net.</li>\n<li>What you're currently doing in <code>Dispose()</code> is wrong. You can't call <code>Dispose()</code> on <code>_source</code> and expect to use it later in another enumerator. In your case, I think you shouldn't do anything in <code>Dispose()</code>. You certainly shouldn't “nuke” <code>_cache</code>, because you're going to need it later!</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T12:33:33.677", "Id": "18483", "Score": "0", "body": "about 4. So my `CachedEnumerable<T>` needs to inherit from `IDisposable` and clear cache and dispose cacheEnumerator. Right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T13:01:27.103", "Id": "18484", "Score": "0", "body": "@R56, yeah implementing `IDisposable` in `CachedEnumerable` makes sense. Clearing the cache there not so much, because that's just managed memory and the GC will take of that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T08:56:07.333", "Id": "11523", "ParentId": "11505", "Score": "5" } }, { "body": "<p>1 and 2 I agree with svick:</p>\n\n<ol>\n<li>You need to access _cache in both classes, so it makes sense to have it as field in both of them too.</li>\n<li>Your code is not thread safe. If you wanted to make it thread safe, I think the best solution would be to have a lock that you use whenever you access _cache or _source.</li>\n</ol>\n\n<p>Regarding 3 I found the following 2 solutions besides this page:</p>\n\n<ul>\n<li><a href=\"http://community.bartdesmet.net/blogs/bart/archive/2010/01/07/more-linq-with-system-interactive-functional-fun-and-taming-side-effects.aspx\" rel=\"nofollow\">Option 2: MemoizeAll()</a></li>\n<li><a href=\"http://refactormycode.com/codes/945-cached-ienumerable-t\" rel=\"nofollow\">A threadsafe cached IEnumerable</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T10:53:25.470", "Id": "11991", "ParentId": "11505", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T20:12:03.767", "Id": "11505", "Score": "5", "Tags": [ "c#", ".net", "linq", "cache", "ienumerable" ], "Title": "Generic cached IEnumerable<T>" }
11505
<p>This is my solution to the <a href="http://learnpythonthehardway.org/book/ex48.html" rel="nofollow">exercise 48 of Learn Python the hard way by Zed Shaw</a>. Please visit the link for testing suite and requirements.</p> <p>I'm worried about my the word banks I have created (COMPASS, VERBS, etc...) as this seems a duplication from the testing code.</p> <p>I'm also afraid my handling might have gone overboard as all I needed it for was finding out which string items could be converted to integers.</p> <pre><code>1 COMPASS= ['north','south','east','west']$ 2 VERBS = ['go', 'kill', 'eat']$ 3 STOPS = ['the', 'in', 'of']$ 4 NOUNS = ['bear', 'princess']$ 5 $ 6 import string$ 7 def scan(sentence):$ 8 action = []$ 9 #TODO: it seems there might be a way to combine these if statments$ 10 for word in sentence.split(' '):$ 11 lword = string.lower(word)$ 12 try:$ 13 if lword in COMPASS:$ 14 action.append(('direction', word))$ 15 elif lword in VERBS:$ 16 action.append(('verb', word))-$ 17 elif lword in STOPS:$ 18 action.append(('stop', word))$ 19 elif lword in NOUNS:$ 20 action.append(('noun', word))$ 21 elif int(lword):$ 22 action.append(('number', int(word)))$ 23 except:$ 24 action.append(('error', word))$ 25 return action$ 26 $ </code></pre>
[]
[ { "body": "<pre><code>lword = string.lower(word) \n</code></pre>\n\n<p>There is no need to import the string module for this, you can use:</p>\n\n<pre><code>lword = word.lower()\n</code></pre>\n\n<p>As for this:</p>\n\n<pre><code>elif int(lword):\n</code></pre>\n\n<p>Probably better as</p>\n\n<pre><code>elif lword.isdigit():\n</code></pre>\n\n<p>As for your exception handling</p>\n\n<pre><code> except: \n action.append(('error', word))\n</code></pre>\n\n<p>You should almost never use a bare except. You should catch a specific exception, and put a minimal amount of code in the try block. In this case you could have done something like</p>\n\n<pre><code>try:\n actions.append( ('number', int(word) )\nexcept ValueError:\n actions.append( ('error', word) )\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T21:42:03.920", "Id": "11509", "ParentId": "11506", "Score": "1" } } ]
{ "AcceptedAnswerId": "11509", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T20:37:51.960", "Id": "11506", "Score": "1", "Tags": [ "python", "unit-testing", "exception-handling" ], "Title": "LPTHW - ex48 - Handling exceptions and unit testing" }
11506
<p>I'm trying to improve my code. I've some doubts about db_index, primary_key and unique parameters.</p> <pre><code> # -*- coding: UTF-8 -*- from django.db import models from django.contrib.auth.models import User #=================================================================================# class Country(models.Model): country_id = models.IntegerField(primary_key=True, unique=True, verbose_name="Id", editable=False) name = models.CharField(unique=True, db_index=True, max_length=50, verbose_name="Nome") short_name = models.CharField(unique=True, max_length=5, verbose_name="Abreviatura") class Meta: verbose_name = "País" verbose_name_plural = "Países" ordering = ['name'] def __unicode__(self): return self.name #=================================================================================# class State(models.Model): state_id = models.IntegerField(primary_key=True, unique=True, verbose_name="Id", editable=False) state = models.CharField(unique=True, db_index=True, max_length=2, verbose_name="Sigla") name = models.CharField(unique=True, db_index=True, max_length=20, verbose_name="Nome") region = models.CharField(max_length=20, verbose_name="Região") country = models.ForeignKey(Country, verbose_name="País") class Meta: verbose_name = "Estado" verbose_name_plural = "Estados" ordering = ['name'] def __unicode__(self): return self.name #=================================================================================# class City(models.Model): city_id = models.IntegerField(primary_key=True, unique=True, editable=False) # id baseado no IBGE name = models.CharField(db_index=True, max_length=150, verbose_name="Nome") # db_index para otimizar desempenho short_name = models.CharField(max_length=150, blank=True, null=True, verbose_name="Slug") state = models.ForeignKey(State, verbose_name="Estado") class Meta: verbose_name = "Cidade" verbose_name_plural = "Cidades" ordering = ['name'] def __unicode__(self): return ('%s - %s') % (self.name, self.state.state) #=================================================================================# class Phone(models.Model): PHONES_TYPE_CHOICES = ( ('R', u'Residencial'), ('M', u'Celular'), ('C', u'Comercial'), ) user = models.ForeignKey(User, verbose_name='Usuário') type = models.CharField(max_length=1, choices=PHONES_TYPE_CHOICES, verbose_name='Tipo') number = models.CharField('Número', max_length=15) class Meta: verbose_name = "Telefone" verbose_name_plural = "Telefones" def __unicode__(self): return self.number #=================================================================================# class Address(models.Model): STREETS_TYPE_CHOICES = ( ('R', 'Rua'), ('A', 'Avenida'), ('T', 'Travessa'), ('E', 'Estrada'), ('R', 'Rodovia'), ('Q', 'Quadra'), ('B', 'Bloco'), ) user = models.ForeignKey(User, verbose_name='Usuário') street_type = models.CharField(max_length=1, choices=STREETS_TYPE_CHOICES, verbose_name='Logradouro') street = models.CharField('Endereço', max_length=100) number = models.IntegerField(verbose_name='Número') complement = models.CharField(max_length=45, blank=True, verbose_name='Complemento') neighborhood = models.CharField('Bairro', max_length=100) state = models.ForeignKey(State, verbose_name="Estado") city = models.ForeignKey(City, verbose_name="Cidade") country = models.ForeignKey(Country, verbose_name="País") zip_code = models.CharField('CEP', max_length=10) class Meta: verbose_name = "Endereço" verbose_name_plural = "Endereços" def __unicode__(self): return ("%s, %s") % (self.city, self.state) #=================================================================================# </code></pre>
[]
[ { "body": "<p>Is it introspected DB or newly created models? If it is created, you do not need <code>SOMETHING_id</code> fields, Django creates primary keys automatically.</p>\n\n<p>Always use unicode strings (<code>u'something'</code>) for everything that is displayed to user and can contain non-ascii characters.</p>\n\n<p>You don't need parenthesis around string in <code>__unicode__</code></p>\n\n<p>And the best way to set indexes is to analyze real queries that are being ran on specific model. Every new index slows down <code>INSERT</code> and <code>UPDATE</code> queries so do not use indexes if you don't need them. Also, in most cases indexes for chars work good only in <code>exact</code> or <code>startswith</code> comparisons (in Django terms). If you are using <code>contains</code> - index is useless.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T00:55:15.237", "Id": "18556", "Score": "0", "body": "Thank you! It's a introspected DB (this is the reason to use the custom ID). Any other tips?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T05:21:12.203", "Id": "11517", "ParentId": "11507", "Score": "1" } }, { "body": "<p>If <code>primary_key=True</code> set to field then <code>unique=True</code> is redundant.\n<code>unique=True</code> also assumes that <code>db_index=True</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T08:32:07.207", "Id": "11522", "ParentId": "11507", "Score": "0" } } ]
{ "AcceptedAnswerId": "11517", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T20:45:15.057", "Id": "11507", "Score": "1", "Tags": [ "python", "django" ], "Title": "Doubts about db_index, primary_key and unique parameters" }
11507
<p>I am looking to make the below code a bit more efficient / OOP based. As can be seen by the X, Y &amp; Z variables, there is a bit of duplication here. Any suggestions on how to make this code more pythonic?</p> <p>The code functions as I wish and the end result is to import the dictionary values into a MySQL database with the keys being the column headers.</p> <pre><code>import fnmatch import os import pyexiv2 matches = [] dict1 = {} # The aim of this script is to recursively search across a directory for all # JPEG files. Each time a JPEG image is detected, the script used the PYEXIV2 # module to extract all EXIF, IPTC and XMP data from the image. Once extracted # the key (ie. "camera make" is generated and it's respective value # (ie. Canon) is then added as the value in a dictionary. for root, dirnames, filenames in os.walk('C:\Users\Amy\Desktop'): for filename in fnmatch.filter(filenames, '*.jpg'): matches.append(os.path.join(root, filename)) for entry in matches: metadata = pyexiv2.ImageMetadata(entry) metadata.read() x = metadata.exif_keys y = metadata.iptc_keys z = metadata.xmp_keys for key in x: value = metadata[key] dict1[key] = value.raw_value for key in y: value = metadata[key] dict1[key] = value.raw_value for key in z: value = metadata[key] dict1[key] = value.raw_value print dict1 </code></pre>
[]
[ { "body": "<pre><code>import fnmatch\nimport os\nimport pyexiv2\n\nmatches = []\ndict1 = {}\n</code></pre>\n\n<p><code>dict1</code> isn't a great name because its hard to guess what it might be for. </p>\n\n<pre><code># The aim of this script is to recursively search across a directory for all\n# JPEG files. Each time a JPEG image is detected, the script used the PYEXIV2\n# module to extract all EXIF, IPTC and XMP data from the image. Once extracted\n# the key (ie. \"camera make\" is generated and it's respective value\n# (ie. Canon) is then added as the value in a dictionary.\nfor root, dirnames, filenames in os.walk('C:\\Users\\Amy\\Desktop'):\n</code></pre>\n\n<p>Your code will be a bit faster if you put stuff into a function rather than at the module level. </p>\n\n<pre><code> for filename in fnmatch.filter(filenames, '*.jpg'):\n matches.append(os.path.join(root, filename))\n for entry in matches:\n</code></pre>\n\n<p>ok, you add each file you find to the matches. But then each time you go over all the matches. I doubt you meant to do that. As its stand, you are going to look at the same file over and over again</p>\n\n<pre><code> metadata = pyexiv2.ImageMetadata(entry)\n metadata.read()\n x = metadata.exif_keys\n y = metadata.iptc_keys\n z = metadata.xmp_keys\n</code></pre>\n\n<p><code>x</code> <code>y</code> and <code>z</code> aren't great variable names. But its seems you aren't really interested in them seperately, just in all the keys. In that case do</p>\n\n<pre><code>keys = metadata.exif_keys + metadata.iptc_keys + metadata.xmp_keys\n</code></pre>\n\n<p>to combine them all into one list. (I'm guessing as to what exactly these keys are but, I think I it'll work.)</p>\n\n<pre><code> for key in x:\n value = metadata[key]\n dict1[key] = value.raw_value\n</code></pre>\n\n<p>I'd combine the two lines</p>\n\n<pre><code>dict1[key] = metadata[key].raw_value\n\n\n for key in y:\n value = metadata[key]\n dict1[key] = value.raw_value\n for key in z:\n value = metadata[key]\n dict1[key] = value.raw_value\n print dict1\n</code></pre>\n\n<p>If you put combine x,y,z as above, you'll only need the one loop</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T22:12:52.743", "Id": "11510", "ParentId": "11508", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T21:38:10.247", "Id": "11508", "Score": "1", "Tags": [ "python", "object-oriented" ], "Title": "JPEG metadata processor" }
11508
<p>The goal is to display all posts with their categories underneath them. The code below accomplishes this, however I'm thinking it's bad and was hoping someone could review and offer some feedback.</p> <p>Because each post can have many categories and because each category can belong to many posts, I used a many-to-many table.</p> <p>I have three tables:</p> <ul> <li><p>table 1: <code>Posts</code><br> columns: | <code>id</code> | <code>post_name</code> | <code>post_text</code> |</p></li> <li><p>table 2: <code>categories</code><br> columns: | <code>id</code> | <code>category_name</code> |</p></li> <li><p>table 3: <code>cats_to_posts</code><br> columns: | <code>cats_id</code> | <code>post_id</code> |</p></li> </ul> <p>index.php:</p> <pre><code>$posts = Posts::read_all(); foreach ( $posts as $post ) { echo $post-&gt;post_name ."&lt;br&gt;"; echo $post-&gt;post_text ."&lt;br&gt;"; $categories_array = Posts::get_cats_by_post_id($post-&gt;id); foreach ($categories_array as $category) { echo "&amp;bull;". $category-&gt;category_name ."&lt;br&gt;"; } } </code></pre> <p>Posts class:</p> <pre><code>public static function get_cats_by_post_id($id) { $db = new Database(); $sql = "SELECT cats_to_posts.cats_id FROM cats_to_posts WHERE cats_to_posts.post_id = {$id}"; $result = $db-&gt;exe_query($sql); $cat_id_array = array(); // stores array of category ids that match post ids while ( $record = $result-&gt;fetch_object() ) { $cat_id_array[] = $record; } $cat_name_array = array(); // stores array of category names that match category ids foreach($cat_id_array as $cat_id) { $new_sql = "SELECT category_name FROM categories WHERE id = ". $cat_id-&gt;cats_id; $new_result = $db-&gt;exe_query($new_sql); while ( $new_record = $new_result-&gt;fetch_object() ) { $cat_name_array[] = $new_record; } } return $cat_name_array; } </code></pre> <p>My main curiosity is on the <code>get_cats_by_post_id()</code> method inside the <code>Posts</code> class. Is there is a better way to get all category names based on the <code>post_id</code> than using two SQL commands like I am doing?</p>
[]
[ { "body": "<p>By the looks of it, you</p>\n\n<ul>\n<li>get the category IDs using the post ID</li>\n<li>get the categories according to the category IDs you just had</li>\n</ul>\n\n<p>Well, you can use JOINS to bridge the tables:</p>\n\n<pre><code>SELECT c.category_name //select category name\nFROM cats_to_posts cp //from cats_to_posts\n INNER JOIN categories c //joined with categories\n ON cp.cats_id=c.id //where the cats_to_posts id = category id\nWHERE cp.post_id = {$id} //get for post with ID\n</code></pre>\n\n<p>This single query should return an array of all category names for that certain post ID. The INNER JOIN joins the <code>cats_to_posts</code> table with <code>categories</code> table and returns only those categories that have an equivalent ID in <code>cats_to_posts</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T06:38:37.950", "Id": "18478", "Score": "0", "body": "You rock!!! That's exactly what I was looking for. And damn, I actually had almost all of that sequel a couple of hours ago, but didn't have the last line \"WHERE cp.post_id = {$id}\" correct. thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T06:28:32.887", "Id": "11519", "ParentId": "11518", "Score": "3" } } ]
{ "AcceptedAnswerId": "11519", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T06:12:05.580", "Id": "11518", "Score": "0", "Tags": [ "php", "mysql" ], "Title": "Displaying data from from many-to-many table" }
11518
<p>I just finished my working code, but still want to improve it.</p> <p>I want to transform this input:</p> <pre><code>&lt;item&gt;asdf&lt;/item&gt; &lt;item&gt;asdf&lt;/item&gt; &lt;item&gt;asdf&lt;/item&gt; </code></pre> <p>to this output:</p> <pre><code>&lt;string name="x1"&gt;asdf&lt;/string&gt; &lt;string name="x2"&gt;asdf&lt;/string&gt; &lt;string name="x3"&gt;asdf&lt;/string&gt; </code></pre> <p>My current code:</p> <pre><code> static void Main(string[] args) { String content; using (StreamReader reader = new StreamReader("arrays2.xml")) { content = reader.ReadToEnd(); } int counter = 0; int startIndex = 0; while ((startIndex = content.IndexOf("&lt;item&gt;", startIndex)) != -1) { counter++; content = content.Substring(0, startIndex) + "&lt;string name=\"rule" + counter + "\"&gt;" + content.Substring(startIndex + 6); } content = content.Replace("&lt;/item&gt;", "&lt;/string&gt;"); using (StreamWriter writer = new StreamWriter("arrays2_formatted.xml")) { writer.Write(content); } Console.WriteLine(content); } </code></pre> <p>I think the bottleneck is in the <code>content</code> assignment within the loop, as a lot of <code>String</code> instance are created and thrown away.</p> <p>However, is there a <em>completely</em> different way to do this efficiently?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T09:00:52.740", "Id": "18480", "Score": "0", "body": "So, you're saying your code is too slow? Have you profiled it? How big is the file you're converting? Are you sure the code is the bottleneck and not the disk?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T12:14:37.157", "Id": "18482", "Score": "0", "body": "@svick No, I don't claim anything. I just want to improve it, as I am not a c# developer, normally. :)" } ]
[ { "body": "<p>Don't parse it through string manipulation, use the XML libraries in the framework. I'd recommend LINQ to XML. Parse it and make your changes.</p>\n\n<pre><code>var xmlStr = @\"&lt;root&gt;\n&lt;item&gt;asdf&lt;/item&gt;\n&lt;item&gt;asdf&lt;/item&gt;\n&lt;item&gt;asdf&lt;/item&gt;\n&lt;/root&gt;\";\n\nvar doc = XDocument.Parse(xmlStr); // parse from string\n//var doc = XDocument.Load(\"arrays2.xml\"); // or load from file\nvar items = doc.Descendants(\"item\"); // find all item elements\nvar index = 1;\nforeach (var item in items.ToList()) // ToList() required since we're modifying the document\n{\n var name = \"x\" + index++;\n var nameAttr = new XAttribute(\"name\", name); // create the name attribute\n var value = (string)item; // read the value as a string\n var newNode = new XElement(\"string\", nameAttr, value); // create the new element\n item.ReplaceWith(newNode); // replace the current one\n}\n//doc.Save(\"arrays2_formatted.xml\"); // save the changes to the file\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T08:27:21.783", "Id": "18479", "Score": "0", "body": "Note, your \"XML\" is not _valid_ XML, it needs a root." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T08:26:19.617", "Id": "11521", "ParentId": "11520", "Score": "3" } } ]
{ "AcceptedAnswerId": "11521", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T07:16:39.650", "Id": "11520", "Score": "0", "Tags": [ "c#", "strings", "xml" ], "Title": "Manipulate XML files in c#" }
11520
<p>I want to write an example for a language similar to Haskell called <a href="http://code.google.com/p/frege/">Frege</a>. While the interpreter is conceptually easy, it is lengthy and looks still quite messy. Note that I <strong>don't</strong> want to use Parsec etc, as it isn't available yet in Frege. Please help me to improve the Haskell version.</p> <pre><code>import Data.Char data Tape = Tape { left :: [Int], cell :: Int, right :: [Int] } instance Show Tape where show (Tape ls c rs) = show [reverse ls,[c],rs] data Op = Plus | Minus | GoLeft | GoRight | Output | Input | Loop [Op] deriving (Eq, Show) removeComments :: [Char] -&gt; [Char] removeComments xs = filter (`elem` "+-&lt;&gt;.,[]") xs parseOp :: [Char] -&gt; Maybe (Op, [Char]) parseOp ('+':cs) = Just (Plus, cs) parseOp ('-':cs) = Just (Minus, cs) parseOp ('&lt;':cs) = Just (GoLeft, cs) parseOp ('&gt;':cs) = Just (GoRight, cs) parseOp ('.':cs) = Just (Output, cs) parseOp (',':cs) = Just (Input, cs) parseOp ('[':cs) = case parseOps cs of (prog, (']':cs')) -&gt; Just (Loop prog, cs') _ -&gt; Nothing parseOp _ = Nothing parseOps :: [Char] -&gt; ([Op],[Char]) parseOps cs = go cs [] where go cs acc = case parseOp cs of Nothing -&gt; (reverse acc, cs) Just (op, cs') -&gt; go cs' (op:acc) parse :: String -&gt; [Op] parse prog = case parseOps $ removeComments $ prog of (ops, []) -&gt; ops (ops, rest) -&gt; error $ "Parsed: " ++ show ops ++ ", Rest: " ++ rest execute :: [Op] -&gt; IO Tape execute prog = exec prog (Tape [] 0 []) exec :: [Op] -&gt; Tape -&gt; IO Tape exec [] tape = return tape exec (Plus:prog) (Tape ls c rs) = exec prog (Tape ls (c+1) rs) exec (Minus:prog) (Tape ls c rs) = exec prog (Tape ls (c-1) rs) exec (GoLeft:prog) (Tape ls c rs) = let (hd,tl) = uncons ls in exec prog (Tape tl hd (c:rs)) exec (GoRight:prog) (Tape ls c rs) = let (hd,tl) = uncons rs in exec prog (Tape (c:ls) hd tl) exec (Output:prog) tape = do printAsChar (cell tape) exec prog tape exec (Input:prog) (Tape ls _ rs) = do n &lt;- getChar exec prog (Tape ls (digitToInt n) rs) exec (Loop loop:prog) tape @ (Tape ls 0 rs) = exec prog tape exec again@(Loop loop:prog) tape = do tape' &lt;- exec loop tape exec (if (cell tape') == 0 then prog else again) tape' uncons :: [Int] -&gt; (Int,[Int]) uncons [] = (0,[]) uncons (x:xs) = (x,xs) printAsChar :: Int -&gt; IO () printAsChar i = putStr $ [chr i] main = do tape &lt;- execute $ parse helloWorld putStrLn $ "\n" ++ show tape ++ "\n" helloWorld = "&gt;+++++++++[&lt;++++++++&gt;-]&lt;.&gt;+++++++[&lt;++++&gt;-]&lt;+.+++++++..+++.[-]&gt;++++++++" ++ "[&lt;++++&gt;-]&lt;.&gt;+++++++++++[&lt;+++++&gt;-]&lt;.&gt;++++++++[&lt;+++&gt;-]&lt;.+++.------.--------." ++ "[-]&gt;++++++++[&lt;++++&gt;-]&lt;+.[-]++++++++++." </code></pre> <p><strong>[Edit]</strong></p> <p>parseOp can be simplified to:</p> <pre><code>ops = [('+', Plus),('-', Minus),('&lt;',GoLeft),('&gt;',GoRight),('.',Output),(',',Input)] parseOp :: [Char] -&gt; Maybe (Op, [Char]) parseOp ('[':cs) = case parseOps cs of (prog, (']':cs')) -&gt; Just (Loop prog, cs') _ -&gt; Nothing parseOp (c:cs) = fmap (flip (,) cs) $ lookup c ops parseOp [] = Nothing </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T19:23:34.180", "Id": "18493", "Score": "0", "body": "This is about as straightforward as it gets. You could line some things up with whitespace, and perhaps use `where` instead of `let/in`, but other than that, there's really not much I can see that could be simplified." } ]
[ { "body": "<p>Disclaimer: I know nothing about Frege, all comments apply to Haskell only.</p>\n\n<p>1)</p>\n\n<p>Running <a href=\"http://community.haskell.org/~ndm/hlint/\">hlint</a> on your code shows places where you can remove <code>$</code> and brackets. Please do it!</p>\n\n<p>2)</p>\n\n<p>In <code>exec</code>, you always do <code>exec prog tape</code> after finishing current instruction. So you are iterating the list in some sense. This is a fold.</p>\n\n<pre><code>exec :: [Op] -&gt; Tape -&gt; IO Tape\nexec prog tape = foldM f tape prog\n\n where f (Tape ls c rs) Plus = return $ Tape ls (c+1) rs\n f (Tape ls c rs) Minus = return $ Tape ls (c-1) rs\n f (Tape ls c rs) GoLeft = let (hd, tl) = uncons ls in return $ Tape tl hd (c:rs)\n f (Tape ls c rs) GoRight = let (hd, tl) = uncons rs in return $ Tape (c:ls) hd tl\n f tape Output = printAsChar (cell tape) &gt;&gt; return tape\n f (Tape ls _ rs) Input = do n &lt;- getChar\n return $ Tape ls (digitToInt n) rs\n\n f tape again@(Loop loop) | cell tape == 0 -&gt; return tape\n | otherwise -&gt; do tape' &lt;- exec loop tape\n f tape' again\n</code></pre>\n\n<p>3)</p>\n\n<pre><code>printAsChar i = putStr $ [chr i]\n</code></pre>\n\n<p>hlint will tell you the $ is redundant:</p>\n\n<pre><code>printAsChar i = putStr [chr i]\n</code></pre>\n\n<p>You can use <code>putChar</code>:</p>\n\n<pre><code>printAsChar i = putChar (chr i)\n</code></pre>\n\n<p>and finally get:</p>\n\n<pre><code>printAsChar = putChar . chr\n</code></pre>\n\n<p>You have a strange asymmetry - output uses <code>chr</code>, and input <code>digitToInt</code>. These are not inverses! <code>digitToInt '0'</code> is <code>0</code>, but <code>chr 0</code> is <code>'\\NUL'</code>, not <code>'0'</code>.</p>\n\n<p>If you want to output numbers longer than 1 character, use</p>\n\n<pre><code>printAsString = putStr . show\n</code></pre>\n\n<p>4)</p>\n\n<p>I would merge <code>execute</code> and <code>exec</code>:</p>\n\n<pre><code> execute :: [Op] -&gt; IO Tape\n execute = foldM f (Tape [] 0 [])\n where f = ...\n</code></pre>\n\n<p>5)</p>\n\n<pre><code> putStrLn $ \"\\n\" ++ show tape ++ \"\\n\" \n</code></pre>\n\n<p><code>putStrLn</code> already adds <code>'\\n\"</code> to the end, you might remove it.</p>\n\n<p>6)</p>\n\n<p>If you remove the requirement to print the tape (is it needed for debugging only?), you can use an infinite list:</p>\n\n<pre><code> execute = foldM f (Tape (repeat 0) 0 (repeat 0))\n</code></pre>\n\n<p>and get rid of <code>uncons</code>:</p>\n\n<pre><code> f (Tape (hd:tl) c rs) GoLeft = return $ Tape tl hd (c:rs)\n f (Tape ls c (hd:tl)) GoRight = return $ Tape (c:ls) hd tl\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T06:45:00.080", "Id": "18691", "Score": "0", "body": "Excellent answer. Regarding 6), I considered it, but reverted it exactly because of the debugging problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T08:23:48.617", "Id": "18693", "Score": "0", "body": "You could put `show (Tape ls c rs) = show [reverse (take 10 ls),[c],take 10 rs]` but I understand it might hinder debugging." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T22:25:30.567", "Id": "11639", "ParentId": "11525", "Score": "7" } } ]
{ "AcceptedAnswerId": "11639", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T10:19:49.320", "Id": "11525", "Score": "9", "Tags": [ "haskell", "brainfuck", "interpreter" ], "Title": "Brainfuck Interpreter" }
11525
<p>I wrote a little function to compact long text. I am relatively new to JavaScript so I am not sure I wrote it as elegantly as possible. I wrote it to be runnable on the server side (Node.js) as well, so can't use jQuery or such. Can the code be improved?</p> <pre><code>// change a long text into "bla bla bla... (more)" where (more) is a link to open the rest of the text // compact text if over maxWords words (split by ' ', default 25) // or if over maxRows lines (split by '&lt;br&gt;', default 2) // but avoid compacting if no more than "almostFinished" (default 5) words to the end of the text compactText = function(text, prefix, maxWords, maxRows, almostFinished) { if (!maxWords) { maxWords = 25; } if (!maxRows) { maxRows = 2; } if (!almostFinished) { almostFinished = 5; } var result = []; var compacted = false; // escape the html code in the text text = (text || '').replace(/&lt;/g, '&amp;lt;').replace(/&gt;/g,'&amp;gt;').replace(/\r/g, ' ').replace(/\n/g, ' &lt;br&gt; ') var pn = text.split(' '); var row = 1; for (var word=0; word&lt; pn.length; word++) { if (pn[word] === "&lt;br&gt;") { row++; } if (!compacted &amp;&amp; (row &gt; maxRows || word == maxWords) &amp;&amp; word&lt; pn.length - almostFinished) { compacted = true; /* too long - add a (more) link and open hidden span for rest of text */ result.push('&lt;span class="'+prefix+'-more-text"&gt;...&lt;a href="#" onclick="javascript:$('+ "'."+prefix+"-more-text').toggle(); return false;"+ '"&gt;(show more)&lt;/a&gt;&lt;/span&gt;'); result.push('&lt;span class="'+prefix+'-more-text" style="display:none"&gt;'); } result.push(pn[word]); } if (compacted) { // compacted: add link to toggle back (less) and close the hidden span. result.push('&lt;a href="#" onclick="javascript:$('+ "'."+prefix+"-more-text').toggle(); return false;"+ '"&gt;(show less)&lt;/a&gt;&lt;/span&gt;'); } return result.join(' '); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T14:58:13.120", "Id": "18485", "Score": "0", "body": "Why do you need the br? Can't you use `white-space: pre-line;`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T22:38:45.480", "Id": "18498", "Score": "0", "body": "I didn't know about the white-space css, it certainly removes the need for replacing \\n with <br>, thanks!" } ]
[ { "body": "<ol>\n<li><p>Instead of <code>pn</code> use a longer variable name. A variable like this with such a big scope really deserves a longer name. It would make the code easier to read.</p>\n\n<pre><code>var pn = text.split(' ');\n</code></pre></li>\n<li><p>Instead of commenting use the comment name as a function name:</p>\n\n<pre><code>// escape the html code in the text\ntext = (text || '').replace(/&lt;/g, '&amp;lt;').replace(/&gt;/g,'&amp;gt;').replace(/\\r/g, ' ').replace(/\\n/g, ' &lt;br&gt; ')\n</code></pre>\n\n<p>I'd write this:</p>\n\n<pre><code>function escapeHtml(text) {\n if (!text) {\n return \"\";\n }\n return text.replace(/&lt;/g, '&amp;lt;').replace(/&gt;/g,'&amp;gt;').replace(/\\r/g, ' ').replace(/\\n/g, ' &lt;br&gt; ') \n}\n</code></pre></li>\n<li><p>I'd create a <code>createToggleLink</code> function. </p>\n\n<pre><code>function createToggleLink(prefix, linkText) {\n return '&lt;a href=\"#\" onclick=\"javascript:$(' +\n \"'.\" + prefix + \"-more-text').toggle(); return false;\" +\n '\"&gt;(\" + linkText + \")&lt;/a&gt;');\n}\n</code></pre>\n\n<p>It removes some code duplication and furthermore makes it more explicit that you close the <code>span</code> tag:</p>\n\n<pre><code>if (compacted) {\n var toggleLink = createToggleLink(prefix, '(show less)');\n result.push(toggleLink);\n result.push('&lt;/span&gt;');\n}\n</code></pre>\n\n<p>So, the comment is unnecessary, the code says the same.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T14:20:02.687", "Id": "11529", "ParentId": "11528", "Score": "1" } } ]
{ "AcceptedAnswerId": "11529", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T13:52:19.257", "Id": "11528", "Score": "1", "Tags": [ "javascript", "node.js" ], "Title": "Collapse long text (with more/less links)" }
11528
<p>Having spent years writing procedural PHP (albeit with a moderate understanding of OOP from Java) I took the plunge and have attempted to write an autoload class for my PHP applications.</p> <pre><code>abstract class AutoloadClass { protected $_observers = array(); protected $structure; protected $extension; /** * autoload() * Includes files from specified structure * @param String $class The class name and file name * @param String $structure The location of this file * @param String $extension The file extension */ protected function autoload($class, $structure, $extension) { $filename = $structure . strtolower($class) . $extension; if (!file_exists($filename)) { return false; } require_once $filename; return true; } /** * attach() * Attaches an Observer */ public function attach($observer) { array_push($this-&gt;_observers, $observer); } /** * detach() * Removes an Observer */ public function detach($observer) { foreach ($this-&gt;_observers as $key =&gt; $item) { if ($observer == $item) { unset($this-&gt;_observers[$key]); } } } /** * update() * Notify all observers of change in state */ public function update() { foreach ($this-&gt;_observers as $key =&gt; $item) { $item-&gt;update($this); } } /** * apply() * Applys observers code. Some observers do not require this */ public function apply() { foreach ($this-&gt;_observers as $key =&gt; $item) { $item-&gt;apply(); } } } /** * LoadFolder * Extends the AutoloadClass and adds observer functionality * as well as implementing methods to set autload folder paths * @see AutoloadClass * **/ class LoadFolder extends AutoloadClass { protected $structure; protected $extension; private $state = ""; // String containing a current state message /** * __construct() { * Attaches observers to be automatically included * **/ public function __construct() { $this-&gt;attach(AutoloadObserver::getInstance()); //$this-&gt;attach(ConsoleLogger::getLogger()); } /** * setAttributes($structre,$extension) * This method takes user input $structure and $extension * e.g. $this-&gt;setAttributes("app/libs/",".app.libs.php") * stores these attributes in class variables, and instantiates * spl_autoload_register() using $this and customAutoloader() as its method * **/ public function setAttributes($structure, $extension) { $this-&gt;structure = $structure; $this-&gt;extension = $extension; $this-&gt;state = "Attributes added"; $this-&gt;update($this); spl_autoload_register(array($this, 'customAutoLoader'),true); } /** * getAttributes() * Returns an array of the current attributes * @return Array ('structure','extension') * **/ public function getAttributes() { return array('structure' =&gt; $this-&gt;structure, 'extension' =&gt; $this-&gt;extension); } /** * getState() * Returns the current state of the class. This is represented by $this-&gt;state * @return String state * **/ public function getState() { return $this-&gt;state; } /** * customAutoloader($class) * This method is only instantiated by spl_autoload_register() * It checks the return value of the autoload() method (@see AutoloadClass) * updates the current state and informs observers. * **/ private function customAutoloader($class) { if (!$this-&gt;autoload($class, $this-&gt;structure, $this-&gt;extension)) { $this-&gt;state = $class . " load failed"; $this-&gt;update($this); } else { $this-&gt;state = $class . " loaded"; $this-&gt;update($this); } } } /** * AutoloadFactory * Factory class to return new autload objects as required * This class is a singleton. **/ class AutoloadFactory { private static $instance; private function __construct() {} public static function getInstance() { if (!is_object(self::$instance)) self::$instance = new AutoloadFactory(); return self::$instance; } public function getObject() { return new LoadFolder(); } } </code></pre> <p>A couple of questions:</p> <ol> <li><p>I'm still slightly sketchy in some areas of OOP implementation, I've tried to stick to tried and tested patterns with some modifications (i.e. Observers not just being notified of a change in state, but also being asked to perform certain tasks using <code>AutoloadClass apply()</code>). Is this kind of tinkering with the pattern doing me any favours or should I be looking at other patterns to 'plugin' such objects?</p></li> <li><p>Is this massive overkill? It works great locally for me but I am guessing will add considerable overhead on my remote servers. Any pointers how to make it more efficient would be great!</p></li> </ol> <p>Please let me know of any tweaks / changes you would make to this regardless of the questions I've asked.</p>
[]
[ { "body": "<p>Yes, this is <strong>massive overkill</strong>. I'll cover this first, then give some minor comments.</p>\n\n<h2>Autoload Overkill</h2>\n\n<p>The point of autoloading is that it happens automatically. You just assume that it works (because it has to). What happens when you can't autoload a class? Can your code recover from it? (Maybe, but probably no). Should it try to recover from it? (No, perhaps an error page would be nice).</p>\n\n<p>Not being able to load a class that you are trying to use is a very serious error. If you want to use that class then not loading it is not an option. It is too late when you try to use it and invoke the autoloader. You should not have written the code that was going to require a class that you don't have.</p>\n\n<p>There are a few options on how you can fail out of autoloading. The standard way is a <strong>fatal error</strong>. This provides limited options to handle the error. You can only do very basic things within a shutdown function (set via <a href=\"http://php.net/manual/en/function.register-shutdown-function.php\" rel=\"nofollow\">register_shutdown_function</a>).</p>\n\n<p>The other option is making the autoloader aware of what it should have control over (what classes it should be able to load). Because we can have a stack of functions that provide autoloading we can only throw an exception if we know that the autoloader should have been able to load the class that was passed to it. <strong>Throwing an exception</strong> gives us more control over how it is handled than a fatal error.</p>\n\n<p>It is very easy to display an error page when you catch an exception (This is the appropriate thing to do rather than try to recover from an autoloading failure). This exception gives the signal to the correct place (which is the higher up code that is making the call) rather than an observer which can only guess at what the current execution stack is.</p>\n\n<h2>Minor Comments</h2>\n\n<ol>\n<li><p><strong>Inconsistent Naming</strong></p>\n\n<pre><code>protected $_observers = array();\nprotected $structure;\nprotected $extension;\n</code></pre>\n\n<p>Personally I prefer protected variables without the leading underscore. You should be consistent though. Even if you see a difference in how you use those properties, they should be named the same way.</p></li>\n<li><p><strong>Singleton is wrong</strong></p>\n\n<p>First, I hate singletons in PHP. It causes tight coupling. All of the code that calls it gets bound to the singleton class. (See also Static causes Tight Coupling below).</p>\n\n<p>If you really must make a singleton, do it right. Stop people constructing, cloning or getting another from unserialize:</p>\n\n<pre><code>private function __construct();\nprivate function __clone();\nprivate function __wakeup();\n</code></pre></li>\n<li><p><strong>getObject</strong></p>\n\n<p>When getObject fronts up to the media and answers the reporters' questions about his nondescript name he says \"no comment\".</p>\n\n<p>Seriously though, a comment shouldn't be required here, but the method name should be something like <code>buildFolderAutoloader</code> (I'd rename that class to FolderAutoloader).</p></li>\n<li><p><strong>Static causes Tight Coupling</strong></p>\n\n<p>Whenever you see <code>xxx::yy()</code> there are two things you need to satisfy. You need a class called <code>xxx</code> with a method <code>yy</code>. Using objects you have <code>$xxx-&gt;yy()</code>. However <code>$xxx</code> can be any object that has a <code>yy</code> method. </p>\n\n<p>Passing in these <code>xxx</code> objects in your constructor is what is called 'Dependency Injection'. It makes your classes stand by themselves, rather than requiring people who want to reuse your class to drag in all of the staticly bound classes (and the classes which they are bound to etc.).</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T09:13:15.430", "Id": "18512", "Score": "0", "body": "Thanks for the comments Paul, I've re-edited my code above as your point #1 was due to me editing the code in the textbox after I'd pasted it from my IDE. You've given me a lot to think about / read about. Thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T09:29:09.743", "Id": "18513", "Score": "0", "body": "No problems, I have removed my point #1 and the rest have been renumbered." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T03:20:24.803", "Id": "11543", "ParentId": "11530", "Score": "4" } }, { "body": "<p>First off, I completely agree with Paul, this is just a suplement that would have been to big to add as a comment. So +1 Paul :)</p>\n\n<p><strong>Q:</strong> \"Is this kind of tinkering with the pattern doing me any favours or should I be looking at other patterns to 'plugin' such objects?\"</p>\n\n<p><strong>A:</strong> It is perfectly fine to tinker with a pattern and tweak it to your needs. In fact, that is expected! Tweak away, patterns are meant as guidelines, not strict laws to be adhered to. If patterns were meant to be followed that faithfully, they would have been added to the language and any deviations would cause errors.</p>\n\n<p><strong>Q:</strong> \"Is this massive overkill?\"</p>\n\n<p><strong>A:</strong> Paul had a nice answer for this. If I could give him another +1 I would.</p>\n\n<p><strong>Properties</strong></p>\n\n<p>Completely agree with Paul, your properties/methods should be consistent. The accepted standard is that private properties/methods should be prefixed by an underscore \"_\". I personally extend this to protected properties/methods as well, but that is my preference. However, even the accepted standard is a preference. As long as your code is consistent, it does not matter if you use the standard or not. Also, I see a lot of people initiating their properties individually. I don't know if it is their preference, or if they don't know about combining like properties, so in case you didn't know, you could combine them like so...</p>\n\n<pre><code>protected\n $_observers = array(),\n $structure,\n $extension\n;\n</code></pre>\n\n<p>Or any other way. PHP is very flexible with its whitespace. This is just the way I do mine.</p>\n\n<p><strong>array_search()</strong></p>\n\n<p>There is no reason to iterate over the array in your <code>detach()</code> method. Use PHP's built in <code>array_search()</code> functionality to find your key.</p>\n\n<pre><code>public function detach($observer) {\n $key = array_search($observer, $this-&gt;_observers);\n if($key !== null &amp;&amp; $key !== FALSE) { unset($this-&gt;_observers[$key]); }\n}\n</code></pre>\n\n<p><strong>Foreach Loops</strong></p>\n\n<p>Your <code>update()</code> and <code>apply()</code> methods set a key value pair in their foreach loop, but you never use the keys. You don't have to set a key each time you use a foreach loop, just like you don't always need to set a value.</p>\n\n<pre><code>foreach($array as $value) { } //iterate over just values\nforeach(array_keys($array) as $key) { } //iterate over just keys\n</code></pre>\n\n<p><strong>Typecasting Arguments</strong></p>\n\n<p>You should typecast your arguments if you only expect to pass a specific argument type to its method. This will cause your class to throw an error if an argument is passed that is not of the expected type. There are a number of advantages to this. Built in input filtering and making debugging easier to name only two. This could be extended so that you could give the method a new object of this type as a default value. This way you would only have to add an argument to its method if you wanted to add an existing instance of it. Take the <code>attach()</code> method for instance.</p>\n\n<pre><code>public function attach(AutoloadObserver $observer = AutoloadObserver::getInstance()) {\n array_push($this-&gt;_observers, $observer);\n}\n</code></pre>\n\n<p>I looked and could not find you using <code>attach()</code> anywhere else, except for a commented out section. If you plan on the input changing object type, but remaining an object, you can just typecast it as a generic object, but you would be unable to add a default for it.</p>\n\n<p><strong>Code Efficiency</strong></p>\n\n<p>Don't rewrite code! Reuse as much as possible. You don't have to write yours exactly like mine. I just condenced it as far as I could. I know some people don't like ternary.</p>\n\n<pre><code>private function customAutoloader($class) {\n $this-&gt;state = $class;\n $this-&gt;state .= ($this-&gt;autoload($class, $this-&gt;structure, $this-&gt;extension) ? ' loaded' : ' load failed');\n $this-&gt;update($this);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T08:23:40.357", "Id": "18566", "Score": "0", "body": "Some really helpful and useful comments, I'm fully self taught in PHP so learning the accepted meta is invaluable, thanks for your guidance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T08:25:47.327", "Id": "18567", "Score": "0", "body": "Quick question on typecasting. Arrays I will usually typecast, I didnt realise that PHP could typecast specific classes/objects as method arguments. How would you typecast a string in PHP? `String string` doesn't seem to exist?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T08:32:47.237", "Id": "18569", "Score": "0", "body": "+1 Its always good to see another answer with a clear focus and useful suggestions. With multiple properties, a reason to not group them together is when you are using [DocBlock comments](http://en.wikipedia.org/wiki/PHPDoc#DocBlock) on each one. These can be very useful for automatic code documenting tools. @DavidBarker Yes, scalar type casting doesn't exist. The best you can do is use is_string and throw an exception yourself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T13:02:03.300", "Id": "18582", "Score": "0", "body": "@Paul: Ah, yes. I forgot about the comments. I don't normally comment my variables so that method of grouping works for me. My variables are usually self documented and the methods usually explain what isn't clear :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T16:58:25.057", "Id": "11568", "ParentId": "11530", "Score": "3" } }, { "body": "<p>I'm a big fan of not having to write my own code, but instead, using other peoples. This is another instance where there is code already out there, what is already been widely adopted.</p>\n\n<p><a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md\" rel=\"nofollow\">https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md</a> is a SPL_Autoloader class from the 'PHP Framework Interoperability Group'. It forms at least the base for new Zend framework and Synfony2 autoloader.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T18:08:22.647", "Id": "11601", "ParentId": "11530", "Score": "1" } } ]
{ "AcceptedAnswerId": "11543", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T15:03:45.487", "Id": "11530", "Score": "2", "Tags": [ "php", "object-oriented", "php5" ], "Title": "PHP autoload class" }
11530
<p>I need to generate a sequence of <code>int</code> values: <code>{ 0, 1, 2, ... }</code>, but there's a twist: I need to access them from different threads.</p> <p>So I wrote this code:</p> <pre><code>class Counter { private static Counter instance = new Counter(); private static int i = 0; public static Counter Instance { get { return instance; } } public int Next() { lock (this) { return i++; } } public void Reset() { lock (this) { i = 0; } } } </code></pre> <p>May this be implemented in a simpler way?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T17:12:36.823", "Id": "18487", "Score": "0", "body": "Your code looks quite simple, readable and obvious to me (ignoring the unnecessary singleton “noise”). Why do you want to do it even simpler?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T05:05:37.113", "Id": "18507", "Score": "0", "body": "@svick also I expect that probably `lock` can be avoided somehow, probably c# has built-in `synchronized int` or something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T09:01:29.300", "Id": "18511", "Score": "0", "body": "@javapowered, yes, C# has something like that, but it's quite hard to get right. So, unless this code is a performance bottleneck for you, you should probably stick with `lock`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T11:59:50.027", "Id": "121971", "Score": "0", "body": "I think [Interlocked.Increment](http://msdn.microsoft.com/en-us/library/dd78zt0c.aspx) is what you're looking for." } ]
[ { "body": "<pre><code>private static int i = 0;\n</code></pre>\n\n<p>Are you sure that <code>i</code> should be static? If it's static there isn't too much sense of the <code>Counter instance = new Counter()</code> instance and the <code>Next</code> and the <code>Reset</code> methods also could be static.</p>\n\n<p>Anyway, I'd use a longer variable name, like <code>nextValue</code> for better readability.</p>\n\n<p>Furthermore, consider the drawbacks of the Singleton pattern:</p>\n\n<blockquote>\n <p>This pattern makes unit testing far more difficult, \n as it introduces global state into an application.</p>\n</blockquote>\n\n<p>More on <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern#Drawbacks\" rel=\"nofollow\">Wikipedia</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T17:07:30.947", "Id": "11532", "ParentId": "11531", "Score": "2" } }, { "body": "<p>Never lock on <code>this</code> as your callers can also do the same and cause deadlocks where you don't expect them. See below where I create and use a <code>private</code> locking variable. And made <code>i</code> an instance variable since you use a singleton instance anyhow.</p>\n\n<pre><code>class Counter\n{\n private static readonly Counter instance = new Counter();\n\n private static readonly object locker = new object();\n\n private int i;\n\n public static Counter Instance\n {\n get\n {\n return instance;\n }\n }\n\n public int Next()\n {\n lock (locker)\n {\n return i++;\n }\n }\n\n public void Reset()\n {\n lock (locker)\n {\n i = 0;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T13:52:43.213", "Id": "18528", "Score": "0", "body": "this code doesn't look simpler, I know that it is not recomended to lock on `this` but it's fine for such small simple and rarely used class imho." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T13:53:30.703", "Id": "18529", "Score": "1", "body": "Never claimed it was simpler -- just making it work properly. That's the first step before trying to simplify." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T13:57:35.063", "Id": "18530", "Score": "1", "body": "Nitpicking: `lock (locker)` makes me think of a box that contains a secret that one locks. I would call it something else ... maybe lockHandle, like Bill Wagner does http://www.informit.com/articles/article.aspx?p=1231461" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T14:01:23.737", "Id": "18532", "Score": "0", "body": "Hm.. I can buy that `locker` isn't a good name, but I really detest things with `handle` in them when they're not actually handles, either. `lockingObject`, `monitor` (since `lock` expands to `Monitor.Enter` and `Monitor.Exit`), `sync` ??" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T13:51:15.527", "Id": "11553", "ParentId": "11531", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T16:52:44.243", "Id": "11531", "Score": "1", "Tags": [ "c#", "multithreading" ], "Title": "Generate consecutive sentence of int values accessed from different threads" }
11531
<p>Commenting omitted to give you the idea. I've been toying with this recently as a variant of the Builder pattern. I've recently fallen in love with immutable objects for the benefits they give in larger concurrent systems.</p> <p>Questions: </p> <p>Is there a way to do this without having to instantiate two Objects? (ie. <code>Something.Mutable extends Something</code> but adds setters, while preserving <code>final</code> on the underlying fields once the object gets finalized?</p> <p>If I have to instantiate two Objects, can I keep <code>final</code> on their somehow and not repeat myself in the contained Builder Object?</p> <pre><code>public class Something { private final int someInteger; private final String someString; public Something(int someInteger, String someString) { this.someInteger = someInteger; this.someString = someString; } public int getSomeInteger() { return someInteger; } public String getSomeString() { return someString; } public static class Mutable { private int someInteger; private String someString; public Something.Mutable() {} public int getSomeInteger() { return someInteger; } public String getSomeString() { return someString; } public Something.Mutable setSomeInteger(int someInteger) { this.someInteger = someInteger; return this; } public Something.Mutable setSomeString(String someString) { this.someString = someString; return this; } public Something build() { return new Something(someInteger, someString); } } } </code></pre> <p>Here is an example of me using it:</p> <pre><code>Something something = new Something.Mutable() .setString("hi") .setInteger(42) .build(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T20:56:35.450", "Id": "18496", "Score": "1", "body": "Your code doesn't compile: The inner class must be just `Mutable`, and you need to rename the `finalize` method (which is already defined in `Object`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T23:31:13.683", "Id": "18500", "Score": "0", "body": "Thanks for the comment, I clearly typed this up in the editor; I'll update!" } ]
[ { "body": "<p>If you <em>really</em> want to avoid object creation, you have no other choice as dropping <code>final</code>, e.g.:</p>\n\n<pre><code>public interface Something {\n\n public int getSomeInteger();\n public String getSomeString();\n\n public static class Mutable implements Something {\n private int someInteger;\n private String someString;\n private boolean open = true;\n\n public int getSomeInteger() {\n return someInteger;\n }\n\n public String getSomeString() {\n return someString;\n }\n\n public Something.Mutable setSomeInteger(int someInteger) {\n assert open;\n this.someInteger = someInteger;\n return this;\n }\n\n public Something.Mutable setSomeString(String someString) {\n assert open;\n this.someString = someString;\n return this;\n }\n\n public Something make() {\n open = false;\n return this;\n }\n }\n}\n</code></pre>\n\n<p>But this pattern is brittle, and the Java runtime is pretty good in dealing with object creation these days, so if you don't write a graphic or math lib or so, you shouldn't care about.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T18:09:08.633", "Id": "18547", "Score": "0", "body": "Thanks for the answer, it's unfortunate java doesn't seem to support \"freeze\"." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T21:09:22.830", "Id": "11539", "ParentId": "11538", "Score": "1" } }, { "body": "<p>Effective Java 2nd Edition has a complete chapter on this topic: <em>Item 2: Consider a builder when faced with many constructor parameters</em>.</p>\n\n<p>You can put a <code>freezed</code> flag into the class then set it in the <code>build</code> method and check it in every setter.</p>\n\n<pre><code>public class Something {\n private int someInteger;\n private String someString;\n\n private boolean freezed;\n\n public Something() {\n }\n\n public int getSomeInteger() {\n return someInteger;\n }\n\n public Something setSomeInteger(final int someInteger) {\n checkFreezed();\n this.someInteger = someInteger;\n return this;\n }\n\n public String getSomeString() {\n return someString;\n }\n\n public Something setSomeString(final String someString) {\n checkFreezed();\n this.someString = someString;\n return this;\n }\n\n private void checkFreezed() {\n if (freezed) {\n throw new IllegalStateException();\n }\n }\n\n public Something build() {\n freezed = true;\n return this;\n }\n}\n</code></pre>\n\n<p>Of course it has its own drawbacks:</p>\n\n<blockquote>\n <p>[...] it can cause errors\n at runtime, as the compiler cannot ensure that the programmer calls the freeze\n method on an object before using it.</p>\n</blockquote>\n\n<p>(From Effective Java 2nd Edition, Item 2: Consider a builder when faced with many constructor parameters)</p>\n\n<p>You can avoid some repetition with an IDE plugin which generates the builder for you (for example, with \n<a href=\"http://code.google.com/p/fluent-builders-generator-eclipse-plugin/\" rel=\"nofollow\">fluent-builders-generator-eclipse-plugin</a>).</p>\n\n<p>Note that the term <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#finalize%28%29\" rel=\"nofollow\">finalize</a> is used for a completely different mechanism in Java. I'd use the regular <code>build</code> word.</p>\n\n<hr>\n\n<p><strong>Edit</strong>: Anyway, it's possible with only one object creation via reflection but it's really ugly. I don't think that it's worth it, object creation is cheap nowadays.</p>\n\n<p><code>Something</code>:</p>\n\n<pre><code>public interface Something {\n\n int getSomeInteger();\n\n}\n</code></pre>\n\n<p><code>SomethingReflected</code>:</p>\n\n<pre><code>import java.lang.reflect.Field;\n\npublic class SomethingReflected implements Something {\n\n private final int someInteger;\n\n public SomethingReflected() {\n this.someInteger = 0;\n }\n\n public SomethingReflected(final int someInteger) {\n super();\n this.someInteger = someInteger;\n }\n\n public SomethingReflected setSomeInteger(final int someInteger) {\n updateField(\"someInteger\", someInteger);\n return this;\n }\n\n private void updateField(final String fieldName, final int value) {\n try {\n final Field field = this.getClass().getDeclaredField(fieldName);\n field.setAccessible(true);\n field.set(this, value);\n } catch (final NoSuchFieldException e) {\n throw new AssertionError(e);\n } catch (final IllegalAccessException e) {\n throw new AssertionError(e);\n }\n }\n\n @Override\n public int getSomeInteger() {\n return someInteger;\n }\n\n public Something build() {\n return this;\n }\n}\n</code></pre>\n\n<p>Another drawback is that clients could misuse it easily:</p>\n\n<pre><code>final SomethingReflected somethingReflected = new SomethingReflected();\nsomethingReflected.setSomeInteger(5);\n\nfinal Something something = somethingReflected.build();\n\nassertEquals(5, something.getSomeInteger());\n\nsomethingReflected.setSomeInteger(6);\nfinal Something something2 = somethingReflected.build();\n\nassertEquals(5, something.getSomeInteger()); // fails, returns 6\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T18:10:58.677", "Id": "18548", "Score": "0", "body": "Thanks for this useful pattern; unfortunately it means I lose the final keyword and the speedups that offers. I'll wait around a few days to see if any other answers come in, and otherwise probably accept this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T15:22:47.440", "Id": "18603", "Score": "1", "body": "@corykendall: The \"final speedup\" is nowadays often neglectable, if there is any. Generally you seem to be too concerned with speed - but then you stay with mutable objects anyway. There *is* a little price to pay for more secure immutable objects, but I'd say in 95% of the cases that doesn't matter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T17:02:12.507", "Id": "67110", "Score": "0", "body": "If immutable objects are guaranteed to really are immutable, then code can safely replace references to distinct but equal objects with references to a common object. For such replacement to be safe, however, there should be no way by which even erroneously-threaded code could create an \"immutable\" object that mutates. It's difficult to provide such assurance when using popsicle immunity. It's much safer to say that no immutable object should encapsulate any object which has ever been exposed to mutation without cloning it first." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T21:18:31.337", "Id": "11540", "ParentId": "11538", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-06T20:39:21.277", "Id": "11538", "Score": "1", "Tags": [ "java", "design-patterns", "immutability" ], "Title": "Comments on my Java pattern for Mutable turned Immutable objects" }
11538
<p>I was looking for a way of doing simple message passing in Guile and found some references to the module (ice-9 occam-channel) which is a pretty nifty, but undocumented, module for occam-like channels. Since I decided I wanted to use buffered channels I decided to try and write my own implementation of it based on the occam-channel module.</p> <p>My first attempt looks like this:</p> <pre><code>(define-module (gbot buffered-channel) #:use-module (oop goops) #:use-module (ice-9 threads) #:export (make-buffered-channel ? ?? !)) (define-class &lt;channel&gt; ()) (define-class &lt;buffered-channel&gt; (&lt;channel&gt;) (buffer #:accessor buffer #:init-value '()) (cv #:accessor cv #:init-form (make-condition-variable)) (mutex #:accessor mutex #:init-form (make-mutex))) (define-method (make-buffered-channel) (make &lt;buffered-channel&gt;)) ; Hold until there is something in the channel and then ; pop the first item in the buffer. (define-method (? (ch &lt;buffered-channel&gt;)) (lock-mutex (mutex ch)) (if (eq? (buffer ch) '()) (wait-condition-variable (cv ch) (mutex ch))) (let ((res (car (buffer ch)))) (set! (buffer ch) (cdr (buffer ch))) (unlock-mutex (mutex ch)) res)) ; Return #f if there is nothing in the buffer, otherwise ; pop the first element of the buffer. (define-method (?? (ch &lt;buffered-channel&gt;)) (lock-mutex (mutex ch)) (let ((res (if (eq? (buffer ch) '()) #f (let ((res (car (buffer ch)))) (set! (buffer ch) (cdr (buffer ch))) res)))) (unlock-mutex (mutex ch)) res)) (define-method (! (ch &lt;buffered-channel&gt;)) (! ch *unspecified*)) ; Push x onto the buffer FILO-style. (define-method (! (ch &lt;buffered-channel&gt;) x) (lock-mutex (mutex ch)) (set! (buffer ch) (cons x (buffer ch))) (signal-condition-variable (cv ch)) (unlock-mutex (mutex ch))) </code></pre> <p>Being rather new at scheme programming and the pitfalls of concurrent programming I'm quite suspicious of the correctness of this code since it's significantly shorter than the code in occam-channel while still being more capable. I've done some simple testing but still haven't found any problems with it, any suggestions for improvement?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T13:49:31.003", "Id": "18527", "Score": "0", "body": "No suggestions (which is why this isn't an answer). In terms of your surprise, I'd be more suspicious of overlong code than of short code that does the same thing. If you're coming to Scheme by way of imperative/OO-exclusive languages, there's nothing to worry about; the functional way of decomposing programs often naturally leads to shorter code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T16:09:03.373", "Id": "18537", "Score": "0", "body": "Well, I wouldn't claim that my code does the same since by channel is FILO while the data-channel in occam-channel only can keep one value at any time. If this counts as more or less functionality is discussable." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T01:43:36.707", "Id": "11542", "Score": "1", "Tags": [ "lisp", "scheme", "multithreading" ], "Title": "Implementing buffered channels in Guile" }
11542
<p>The output result is perfect to what I wanted, but takes a tad bit too long to pull data then render into a graph. Is there a better way to rewrite this code to speed up the process?</p> <pre><code>CASE "TestGrid": $SnapArrayResult = array(); $PlayArrayResult = array('A','B','C','D'); echo "&lt;table id='tb' style='width:200px;height:200px;font-family:tahoma;font-size:2pt;visibility:hidden;' cellspacing='0'&gt;\n"; echo "&lt;caption&gt;Data on Alliance&lt;/caption&gt;\n"; $SnapResult = $db-&gt; query("SELECT snap FROM scSVR WHERE hex(alliance) IN (hex('A'),hex('B'),hex('C'),hex('D')) GROUP BY snap ORDER BY snap ASC"); while ($SnapRow = $db-&gt; fetch_assoc($SnapResult)){ $SnapArrayResult[] = $SnapRow['snap']; } echo "&lt;thead&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;\n"; foreach($SnapArrayResult as $SAR){ echo "&lt;th&gt;".DTConvS($SAR)."&lt;/th&gt;\n"; } echo "&lt;/tr&gt;&lt;/thead&gt;\n"; echo "&lt;tbody&gt;"; foreach($PlayArrayResult as $PAR){ echo "&lt;tr&gt;&lt;th scope='row'&gt;".$PAR."&lt;/th&gt;"; foreach($SnapArrayResult as $SAR){ $PlayerResult = $db-&gt; query("SELECT COALESCE(count(*),0) as pCnt FROM scSVR WHERE hex(alliance) = hex('".$PAR."') AND snap = ".$SAR); $PlayerRow = $db-&gt; fetch_assoc($PlayerResult); echo "&lt;td&gt;".$PlayerRow['pCnt']."&lt;/td&gt;\n"; } echo "&lt;/tr&gt;"; } echo "&lt;/tbody&gt;&lt;/table&gt;"; break; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T10:52:41.267", "Id": "18519", "Score": "0", "body": "How large is your data? Do you have index on `alliance`? try not using sql functions. enable caching." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T15:35:29.303", "Id": "18535", "Score": "0", "body": "id is the index and will continue to grow daily (1.3 mil rows of data at the moment)" } ]
[ { "body": "<p>Look at the code below. I haven't tried it yet, but the idea is avoid iterating query that will take a long time. So, I just use one query.</p>\n\n<pre><code>CASE \"TestGrid\":\n $SnapArrayResult = array();\n $PlayArrayResult = array('A','B','C','D');\n echo \"&lt;table id='tb' style='width:200px;height:200px;font-family:tahoma;font-size:2pt;visibility:hidden;' cellspacing='0'&gt;\\n\";\n echo \"&lt;caption&gt;Data on Alliance&lt;/caption&gt;\\n\";\n echo \"&lt;thead&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;\\n\";\n $SnapResult = $db-&gt; query(\"SELECT snap,COALESCE(count(*),0) as pCnt,hex(alliance) as alliance FROM scSVR WHERE hex(alliance) IN (hex('A'),hex('B'),hex('C'),hex('D')) GROUP BY snap,alliance ORDER BY snap ASC\");\n $changeSnap = null;\n $PlayerRow = array();\n while ($SnapRow = $db-&gt; fetch_assoc($SnapResult))\n {\n if($changeSnap!=$SnapRow['snap'])\n {\n $SnapArrayResult[] = $SnapRow['snap'];\n $changeSnap=$SnapRow['snap'];\n $PlayerRow[$changeSnap] = array();\n echo \"&lt;th&gt;\".DTConvS($SAR).\"&lt;/th&gt;\\n\";\n }\n $PlayerRow[$changeSnap][$SnapRow['alliance']] = $SnapRow['pCnt'];\n }\n\n echo \"&lt;/tr&gt;&lt;/thead&gt;\\n\";\n echo \"&lt;tbody&gt;\";\n foreach($PlayArrayResult as $PAR){\n echo \"&lt;tr&gt;&lt;th scope='row'&gt;\".$PAR.\"&lt;/th&gt;\";\n foreach($SnapArrayResult as $SAR){ \n echo \"&lt;td&gt;\".$PlayerRow[$SAR][$PAR].\"&lt;/td&gt;\\n\";\n }\n echo \"&lt;/tr&gt;\";\n }\n echo \"&lt;/tbody&gt;&lt;/table&gt;\";\n break;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T16:52:14.140", "Id": "18543", "Score": "0", "body": "wow, i used this code, it REALLY cut down the load time, I really do mean BIG time lol.. ok now the issue arised that the chart is not rendering because it NEEDS to have some value (numeric) in it. For some reason, even with \"COALESCE(count(*),0) as pCnt\" in it, it gives no value in that particular <td></td>, how would I go about \"forcing\" to put in 0?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T17:08:23.603", "Id": "18544", "Score": "0", "body": "i THINK i found a way, unless said otherwise... See Edit Above:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T17:11:55.813", "Id": "18546", "Score": "0", "body": "ok 2 lines changed from original code provided by you bitoshi, it now renders everything AND supplies all proper data. Unless I'm doing something wrong, please DO lemme know :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T11:13:51.157", "Id": "11549", "ParentId": "11548", "Score": "1" } } ]
{ "AcceptedAnswerId": "11549", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T10:48:31.673", "Id": "11548", "Score": "2", "Tags": [ "php", "mysql", "ajax" ], "Title": "Rendering data into a graph" }
11548
<p>Here is my template code</p> <pre><code>&lt;?php namespace classes; /** * Description of Template * * @author Aamir */ class Template { private $templateVars, $templateFile ; protected static $templateFolder, $masterTemplate, $masterInstance, $placeholder, $path_dir, $path_web ; /** * Constructor for the template * @param string $file file path * @param array $args associative array */ public function __construct($file, $args = array()) { $this-&gt;templateFile = self::$path_dir . self::$templateFolder . '/' . $file . '.phtml'; $this-&gt;templateVars = $args; } /** * Magic method to get the array element * @param string $name template variable name to fetch * @return mixed */ public function __get($name) { if (array_key_exists($name, $this-&gt;templateVars)) { return $this-&gt;templateVars[$name]; } else { return ''; } } /** * Magic method to set template var * @param string $name * @param mixed $value */ public function __set($name, $value) { $this-&gt;templateVars[$name] = $value; } /** * output the template to a string * @return string */ public function __toString() { ob_start(); include $this-&gt;templateFile; return ob_get_clean(); } /** * Function to initialize the template * @param string $templatePath Template Path */ public static function setTemplate($templatePath) { self::$templateFolder = $templatePath; } /** * Get current template path * @return string */ public static function getTemplate() { return self::$templateFolder; } /** * Get current template path from root * It will print the path. To be used in image and file paths */ public static function getPath() { echo self::$path_web . self::$templateFolder . '/'; } /** * Set Master Template for project * * @param string $masterTemplate master template file name from template folder */ public static function setMaster($masterTemplate) { self::$masterTemplate = $masterTemplate; self::$placeholder = new Placeholder(); } /** * Set the Paths for root directory, and URL based path * @param string $PATH_WEB URL Path e.g. http://localhost/project1/abc/ * @param string $PATH_DIR Physical path e.g. /home/userA/www/project1/abc/ */ public static function setPaths($PATH_WEB, $PATH_DIR) { self::$path_web = $PATH_WEB; self::$path_dir = $PATH_DIR; } /** * Get the instance of Placeholder object * @return object */ public static function getMasterPlaceHolder() { return self::$placeholder; } /** * Output the template to browser */ public function render() { $master = new Template(self::$masterTemplate, array( 'placeholder' =&gt; self::$placeholder, 'content' =&gt; $this )); echo $master; } } </code></pre> <p><strong>Placeholder.php</strong> used in master template</p> <pre><code>&lt;?php namespace classes; /** * Description of Placeholder * * @author aamir */ class Placeholder { private $templateVars; public function __get($name) { if (array_key_exists($name, $this-&gt;templateVars)) { return $this-&gt;templateVars[$name]; } else { return ''; } } public function __set($name, $value) { $this-&gt;templateVars[$name] = $value; } } </code></pre> <p><strong>USAGE</strong></p> <p>code from <strong>config.php</strong></p> <pre><code>/** * Default Template folder and languages * setTemplate (Template folder); */ classes\template::setTemplate('template/template1'); classes\template::setMaster('master'); define('TEMPLATE_PATH', classes\template::getTemplate() . '/'); </code></pre> <p><strong>Pages.php</strong></p> <pre><code>&lt;?php require 'config.php'; $template = new \classes\template('page'); $template-&gt;page_content = $pageData; $template-&gt;render(); // will output including master template // echo $template; // will output only the page template excluding master layout for AJAX out put </code></pre> <p><strong>Pages.php</strong></p> <p>To change the contents of Master layout e.g. Change of Page title etc</p> <pre><code>$placeholder = \classes\template::getMasterPlaceHolder(); $placeholder-&gt;pageTitle = $cur_page['page_title']; $placeholder-&gt;cur_page = getParam('p'); $template = new \classes\template('page'); $template-&gt;page_content = $pageData; $template-&gt;render(); // will output including master template // echo $template; // will output only the page template excluding master layout for AJAX out put </code></pre> <p><strong>page.phtml</strong> file inside the template/template1 folder</p> <pre><code>&lt;div class="left" style="width: 845px;"&gt;&lt;?php echo $this-&gt;page_content; // this will render page contents ?&gt; &lt;/div&gt; </code></pre> <p><strong>master.phtml</strong> (we need to define placeholders in the template)</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;?php echo $this-&gt;placeholder-&gt;pageTitle ?&gt;&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;link rel="stylesheet" href="&lt;?php echo TEMPLATE_PATH ?&gt;css/style.css" /&gt; &lt;link rel="stylesheet" href="&lt;?php echo TEMPLATE_PATH ?&gt;css/fluid_grid.css" /&gt; &lt;link type="text/css" href="&lt;?php echo TEMPLATE_PATH ?&gt;css/jquery.jscrollpane.css" rel="stylesheet" media="all" /&gt; &lt;script type="text/javascript" src="&lt;?php echo TEMPLATE_PATH ?&gt;js/jquery-1.7.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="&lt;?php echo TEMPLATE_PATH ?&gt;js/jquery.tooltip.pack.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="&lt;?php echo TEMPLATE_PATH ?&gt;js/jquery.jscrollpane.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="&lt;?php echo TEMPLATE_PATH ?&gt;js/jquery.mousewheel.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="&lt;?php echo TEMPLATE_PATH ?&gt;js/jquery-ui-1.8.18.custom.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;?php echo $this-&gt;placeholder-&gt;beforeContent?&gt; &lt;div class="wrapper"&gt; &lt;?php echo $this-&gt;content ?&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>So basically, we set the template folder, and set template master file, and then where we have to display content we used <code>$template = new template('templatefile')</code> (it will add <code>.phtml</code> auto) and if we want full template including master we use <code>$template-&gt;render()</code> or if we just want to output without master for example for an AJAX request we simply echo it <code>echo $template</code>.</p> <p>Please let me know how can I improve it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T13:11:59.097", "Id": "18524", "Score": "0", "body": "I'm still looking over it, but the first major improvement I would suggest is to indent everything appropriately. You don't seem to indent the first level for some reason." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T05:32:07.723", "Id": "18560", "Score": "0", "body": "Formating of the code is disturbed in stackexchange, else it is formated properly in my netbeans IDE" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T13:08:10.673", "Id": "18583", "Score": "0", "body": "Ah, well that's fine then. Just wanted to make sure you were indenting properly :) Taking a look at the changes now. BTW: I've updated the Class Properties section. Paul brought up a good point about that in another question." } ]
[ { "body": "<p>A lot of these suggestions are just that, suggestions. I have little to add for improvement except for aesthetics or readability. So here it goes.</p>\n\n<p><strong>Class Properties</strong></p>\n\n<p>Cool thing about class properties is that they can be combined when initially declaring them. A lot of people don't like doing it because when they see examples of it its always shown as one long string. However, it doesn't all have to be on the same line. Unless you are planning on commenting your variables, PHP is flexible and will allow you to pretty it up with as much, or as little, white space as you like. This is how I like initially declaring my properties, but as I said, this is just a suggestion/preference, it is up to you.</p>\n\n<pre><code>private\n $templateVars,\n $templateFile\n;\nprotected static\n $templateFolder,\n $masterTemplate,\n $masterInstance,\n $placeholder\n;\n</code></pre>\n\n<ul>\n<li>DocBlock commented variables have to be declared separately. You don't have to comment your variables, I don't, but figured I'd mention this for completion.</li>\n</ul>\n\n<p><strong>Constants</strong></p>\n\n<p>This is the only real problem I see. Constants <code>PATH_WEB</code> and <code>PATH_DIR</code> came from no where and I can't find them defined anywhere else. Your models should not be dependent upon another source to work, else you risk fatal errors should that source ever become unavailable or changes. Models should always work error free by themselves. This rule isn't as important for views or controllers since they are already so dependent on other files, but it still sort of applies for them to. I wouldn't set a constant in a config file, <code>TEMPLATE_PATH</code>, to be used in a controller or view, instead I would set it in the controller so that there was one less dependency. In fact, I would probably do away with the config file all together and just throw that all into the controller. The rule of thumb here: set it where you need it.</p>\n\n<p><strong>Method Organization and Improvements</strong></p>\n\n<p>This is just a preference, but one I think most would agree with. I like to move all my magic methods <code>__get()</code>, <code>__set()</code>, <code>__construct()</code>, etc... to the top of my classes. This makes them easier to find because they will always be in the same place. The way you have them now, they are just kind of in the middle. Not that it applies here because you don't seem to be using private/protected methods, but I also separate my methods by type (private/protected or public) for similar reasons. The final thing I do is visually separate these sections using comment blocks, which makes it easier to scroll long classes to find a specific section.</p>\n\n<p>Why did you make your construct method chainable? Never tried it myself because I never thought I'd be able to do it cleanly so I don't even know if it is possible to chain it. Never used namespaces before either, but it looks like it can be done cleanly enough with them, I'll have to take a look at that. You don't appear to be chaining it anyways though, so I would just remove the return from your construct method.</p>\n\n<p>Why did you create your own tostring method when you are not doing anything with the overloaded magic tostring method? Just combine the two and stop manually calling the method. Just echo the class instance, thats the whole reason for it. Also, to keep with the accepted standard, methods should only be prefixed by a single underscore \"_\" if they are private.</p>\n\n<p><strong>Final Thoughts</strong></p>\n\n<p>Now, my brain started shutting down when I looked at your usage sample, so this review is not 100%, but it should be a good 90% at the very least. That has nothing to do with your coding at all, I'm just tired and my brain doesn't want to do the mental gymnastics required to link everything in my head right now. I'll try and come back to this later if I see anything with your usage sample.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T06:01:10.763", "Id": "18562", "Score": "0", "body": "Thank you for a very detailed reply. It really helped me. I have removed the `_toString()` method, i have removed the method chaining from constructor, added new static function of `setPaths()` where PATH_WEB and PATH_DIR can be set, if not set then it will be empty strings. Moved all the magic methods to top of the class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T10:08:16.433", "Id": "18577", "Score": "0", "body": "I have updated the template class as per your suggestions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T13:38:09.013", "Id": "18585", "Score": "0", "body": "@AamirMahmood: I don't really see anything else. It all looks good to me :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T15:02:31.300", "Id": "11560", "ParentId": "11551", "Score": "3" } } ]
{ "AcceptedAnswerId": "11560", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T12:10:05.067", "Id": "11551", "Score": "3", "Tags": [ "php", "template" ], "Title": "Template system with master layout" }
11551
<p>I'm writing a method to save an input stream to an output stream. What's the optimal size for the buffer? Here's my method: </p> <pre><code>/** * Saves the given InputStream to a file at the destination. Does not check whether the destination exists. * * @param inputStream * @param destination * @throws FileNotFoundException * @throws IOException */ public static void saveInputStream(InputStream inputStream, File outputFile) throws FileNotFoundException, IOException { try (OutputStream out = new FileOutputStream(outputFile)) { byte[] buffer = new byte[2097152]; //This is set to two MB. But I have no idea whether this is optimal int length; while ((length = inputStream.read(buffer)) &gt; 0) { out.write(buffer, 0, length); } inputStream.close(); } } </code></pre>
[]
[ { "body": "<p>It depends on a lot of factors, there's no universally \"optimal\" size. 512kB is probably good enough.</p>\n\n<p>If you want, you can always benchmark it for various buffer sizes: this will let you know what the best option is for your computer and OS.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T16:04:26.107", "Id": "18536", "Score": "0", "body": "Just asked [a question](http://stackoverflow.com/questions/10484115/get-system-block-size-in-java) about getting the block size. Could be useful. But I think you're right :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T16:13:37.090", "Id": "18538", "Score": "0", "body": "You still should benchmark it. You'll be surprised by the results!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T14:26:36.910", "Id": "11557", "ParentId": "11555", "Score": "2" } } ]
{ "AcceptedAnswerId": "11557", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T14:09:50.820", "Id": "11555", "Score": "1", "Tags": [ "java", "optimization" ], "Title": "Optimal buffer size for output stream" }
11555
<p>I'm making a method to save a <code>byte[]</code> to a file. It's for a <a href="https://github.com/kentcdodds/Java-Helper" rel="nofollow noreferrer">Java Helper</a> I'm writing, so it needs to be able to handle any kind of system. I saw on <a href="http://www.java-examples.com/write-byte-array-file-using-fileoutputstream" rel="nofollow noreferrer">this example</a> the method of <code>FileOutputStream</code> called <code>write</code> which accepts a <code>byte[]</code>. But I already have a method which will save an input stream to a file.</p> <p>Which is best?</p> <p><strong>Alternative 1</strong></p> <pre><code>/** * Saves the given bytes to the output file. * * @param bytes * @param outputFile * @throws FileNotFoundException * @throws IOException */ public static void saveBytesToFile(byte[] bytes, File outputFile) throws FileNotFoundException, IOException { ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); saveInputStream(inputStream, outputFile); } /** * Saves the given InputStream to a file at the destination. Does not check whether the destination exists. * * @param inputStream * @param destination * @throws FileNotFoundException * @throws IOException */ public static void saveInputStream(InputStream inputStream, File outputFile) throws FileNotFoundException, IOException { try (OutputStream out = new FileOutputStream(outputFile)) { byte[] buffer = new byte[2097152]; int length; while ((length = inputStream.read(buffer)) &gt; 0) { out.write(buffer, 0, length); } inputStream.close(); } } </code></pre> <p><strong>Alternative 2</strong></p> <pre><code>/** * Saves the given bytes to the output file. * * @param bytes * @param outputFile * @throws FileNotFoundException * @throws IOException */ public static void saveBytesToFile2(byte[] bytes, File outputFile) throws FileNotFoundException, IOException { FileOutputStream out = new FileOutputStream(outputFile); out.write(bytes); } </code></pre> <p>Obviously the second is shorter and easier, but I'm just wondering whether one's more optimal than the other. Also, as a side note, I'm wondering about the <a href="https://codereview.stackexchange.com/questions/11555/optimal-buffer-size-for-output-stream">optimal size for the byte buffer</a>.</p>
[]
[ { "body": "<p>Given the care and effort that has been put into performance within the JVM and Java standard libraries, it is a virtual certainty that the second implementation will be faster.</p>\n\n<p>However, does it really matter? Worrying about optimization is generally only useful if the system performance is inadequate. It's far more important to worry about functionality and readability first. Performance issues can be tackled (if they exist) when the system is nearing completion and it is possible to get actual performance data on where the bottlenecks are.</p>\n\n<p>See the Wikipedia article on Program Optimization - especially the <a href=\"http://en.wikipedia.org/wiki/Premature_optimization#When_to_optimize\">\"When to optimize\" section</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T15:01:39.337", "Id": "18534", "Score": "0", "body": "I updated the beginning of my question to indicate why I care about optimization. Thanks for the answer. It's satisfactory." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T14:58:11.823", "Id": "11559", "ParentId": "11556", "Score": "6" } } ]
{ "AcceptedAnswerId": "11559", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T14:15:35.790", "Id": "11556", "Score": "2", "Tags": [ "java", "optimization", "file", "comparative-review" ], "Title": "Optimal method for writing bytes to file" }
11556
<p>I am writing a program which automatically crawls codes from this site!</p> <p>Would you please review my code?</p> <p>The required .jars: <a href="http://jsoup.org/packages/jsoup-1.6.2.jar" rel="nofollow">jsoup</a>, <a href="http://www.nic.funet.fi/pub/mirrors/apache.org//commons/io/binaries/commons-io-2.3-bin.zip" rel="nofollow">org.apache.commons.io</a>.</p> <p>Main.java:</p> <pre><code>public class Main { public static void main(String[] args) throws Exception { final String site1 = "http://codereview.stackexchange.com/questions/"; String site2[] = {"69", "109", "131"}; String site3[] = {"is-this-implementation-of-shamos-hoey-algorithm-ok", "are-there-any-ways-to-improve-my-http-request-path-parser", "law-of-demeter-and-data-models"}; HtmlGetter htmlGetter = new HtmlGetter(); for(int i = 0 ; i &lt; site2.length ; ++i) { htmlGetter.setUrl(site1, site2[i], site3[i]); htmlGetter.download(); htmlGetter.parse(i+1); } } } </code></pre> <p>HtmlGetter.java:</p> <pre><code>import java.io.*; import java.net.URL; import java.util.Scanner; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.io.IOUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class HtmlGetter { private URL url; private String fileName; public void setUrl(String site1, String site2, String site3) throws Exception { this.url = new URL(site1 + site2 + "/" + site3); this.fileName = "[" + site2 + "]" + site3 + ".html"; } public void download() throws Exception { final InputStream in = url.openStream(); final OutputStream out = new FileOutputStream(fileName); IOUtils.copy(in, out); in.close(); out.close(); divideFile(); } private void divideFile() throws Exception { Scanner scanner = new Scanner(new File(fileName)); String oneLine; final BufferedWriter out1 = new BufferedWriter(new FileWriter("question.html")); final BufferedWriter out2 = new BufferedWriter(new FileWriter("answer.html")); while(scanner.hasNextLine()) { oneLine = scanner.nextLine(); if(oneLine.matches(".*&lt;div class=\"post-text\" itemprop=\"description\"&gt;.*")) { while(scanner.hasNextLine()&amp;&amp;(!oneLine.matches(".*&lt;div class=\"post-menu\"&gt;.*"))) { out1.write(oneLine); out1.newLine(); oneLine = scanner.nextLine(); } } if(oneLine.matches("&lt;td class=\"answercell\"&gt;")) { while(scanner.hasNextLine()&amp;&amp;(!oneLine.matches(".*&lt;div class=\"post-menu\"&gt;.*"))) { out2.write(oneLine); out2.newLine(); oneLine = scanner.nextLine(); } break; } } out1.close(); out2.close(); } public void parse(int articleNumber) throws Exception { parse2("question.html", articleNumber); parse2("answer.html", articleNumber); } public void parse2(String strFileName, int articleNumber) throws Exception { File input = new File(strFileName); Document doc = Jsoup.parse(input, "UTF-8"); Elements codes = doc.select("code"); BufferedWriter out; int subNumber = 0; String qa = "x"; for(Element code: codes) { if(strFileName.equals("question.html")) { qa = "q"; } else if(strFileName.equals("answer.html")) { qa = "a"; } else { System.out.println("Error!"); } out = new BufferedWriter(new FileWriter(qa + articleNumber + "-" + (++subNumber) + ".txt")); out.write(code.text().replaceAll("[\r\n]", "\r\n")); out.close(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T04:14:59.537", "Id": "18559", "Score": "0", "body": "any reason you haven't taken my advice to use something like jSoup?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T08:27:43.543", "Id": "18568", "Score": "0", "body": "@WinstonEwert What are you saying? He *is* using jSoup. Looks like a nice framework by the way, wasn't familiar to me before. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T15:14:05.313", "Id": "18597", "Score": "0", "body": "@ZeroOne, my bad. I saw the regexes in divideFile and assumed he hadn't taken my advice." } ]
[ { "body": "<p>At least at first sight I couldn't tell you were new to Java, so that's pretty good. :) Not many issues there, but a some:</p>\n\n<p>First, your <code>divideFile</code> method has some duplicate code. You should refactor that into a new method. The method also never closes the <code>BufferedWriter</code>s if some exception occurs, which is why we have <code>finally</code> block in the <code>try-catch</code>-structure. This I'll leave for you as an exercise, though.</p>\n\n<p>Next, in your <code>parse2</code> method, move that if-block that's deciding the value of the variable <code>qa</code> outside of that for each -loop. There's no need to do costly string comparisons on each iteration. Then also notice that the <code>strFileName</code> could be <code>null</code> so your if-block could crash due to a <code>NullPointerException</code> when you do <code>strFileName.equals(\"question.html\")</code>, so you should do a null-check prior to that. Then change the visibility of the method to <code>private</code>, if you only intend it to be called from <code>parse</code>.</p>\n\n<p>Then, you've got those same <code>question.html</code> and <code>answer.html</code> strings in the code many times. That's always bad, because when you one day decide to change the file name to something else, you need to replace many occurrences. Rather, you should turn them into constants: <code>private static final String QUESTION_FILE = \"question.html\";</code>. Then just use the <code>QUESTION_FILE</code> constant in place of the string.</p>\n\n<p>Furthermore, you could turn those constants into an <a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html\" rel=\"nofollow\">enum</a>. An enum is like a collection of allowed values for something. You can define an enum that only holds the values <code>question.html</code> and <code>answer.html</code>. It's more handy when you have a little more options, but you get the point. </p>\n\n<p>Finally, I find that <code>int variable = 0; ++variable;</code> syntax rather confusing and would rather use <code>int variable = 1; variable++;</code>, but I guess that's mostly just a matter of personal preference. Although you should be careful when changing the value of a variable in the middle of a sentence in any way, because eventually you might want to add some code into that block and to use that variable again. Then it's confusing if the variable number does not stay the same for the entire iteration. </p>\n\n<p>So all in all I might write something like this in the <code>HtmlGetter</code> class:</p>\n\n<pre><code>public class HtmlGetter {\n\nprivate enum FILE_TYPE {\n question, answer;\n public String getFileName() {\n switch (this) {\n case question: return \"question.html\";\n case answer: return \"answer.html\";\n default:\n System.out.println(\"Error!\");\n return \"error.html\";\n }\n }\n};\nprivate URL url;\nprivate String fileName;\nprivate static final String POST_MENU = \".*&lt;div class=\\\"post-menu\\\"&gt;.*\";\n\npublic void setUrl(String site1, String site2, String site3) throws Exception {\n this.url = new URL(site1 + site2 + \"/\" + site3);\n this.fileName = \"[\" + site2 + \"]\" + site3 + \".html\";\n}\n\npublic void download() throws Exception {\n final InputStream in = url.openStream();\n final OutputStream out = new FileOutputStream(fileName);\n IOUtils.copy(in, out);\n in.close();\n out.close();\n divideFile();\n}\n\nprivate void divideFile() throws Exception {\n Scanner scanner = new Scanner(new File(fileName));\n String oneLine;\n final BufferedWriter out1 = new BufferedWriter(new FileWriter(FILE_TYPE.question.getFileName()));\n final BufferedWriter out2 = new BufferedWriter(new FileWriter(FILE_TYPE.answer.getFileName()));\n\n while (scanner.hasNextLine()) {\n oneLine = scanner.nextLine();\n if (oneLine.matches(\".*&lt;div class=\\\"post-text\\\" itemprop=\\\"description\\\"&gt;.*\")) {\n while (scanner.hasNextLine() &amp;&amp; (!oneLine.matches(POST_MENU))) {\n oneLine = writeAndReadLine(scanner, out1, oneLine);\n }\n }\n if (oneLine.matches(\"&lt;td class=\\\"answercell\\\"&gt;\")) {\n while (scanner.hasNextLine() &amp;&amp; (!oneLine.matches(POST_MENU))) {\n oneLine = writeAndReadLine(scanner, out2, oneLine);\n }\n break;\n }\n }\n out1.close();\n out2.close();\n}\n\nprivate String writeAndReadLine(Scanner scanner, BufferedWriter out, String line) throws Exception {\n out.write(line);\n out.newLine();\n return scanner.nextLine();\n}\n\npublic void parse(int articleNumber) throws Exception {\n parse2(FILE_TYPE.question, articleNumber);\n parse2(FILE_TYPE.answer, articleNumber);\n}\n\nprivate void parse2(FILE_TYPE file, int articleNumber) throws Exception {\n File input = new File(file.getFileName()); // This throws a NullPointerException\n Document doc = Jsoup.parse(input, \"UTF-8\");\n Elements codes = doc.select(\"code\");\n BufferedWriter out;\n int subNumber = 1;\n for (Element code : codes) {\n out = new BufferedWriter(new FileWriter(\"codereview-questions/\"\n + file.getFileName().charAt(0) + articleNumber + \"-\" + subNumber + \".txt\"));\n out.write(code.text().replaceAll(\"[\\r\\n]\", \"\\r\\n\"));\n out.close();\n subNumber++;\n }\n}\n}\n</code></pre>\n\n<p>You <code>Main</code> class seems to be for testing purposes only since it doesn't parse the questions from the main page of the site, so I won't comment on it except by saying that it seems to do its job. And even though this message may look longish, I found your original code quite good. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T11:02:58.373", "Id": "18580", "Score": "0", "body": "Many thanks for your valuable comments, ZeroOne!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T13:42:51.257", "Id": "18587", "Score": "0", "body": "I've never thought about using Enum. You taught me a great lesson!! Thanks a lot again!!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T18:52:34.037", "Id": "18611", "Score": "0", "body": "No problem, happy to help. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T02:23:06.617", "Id": "18901", "Score": "1", "body": "This is a good answer, but the enum is implemented somewhat incorrectly. See my answer for more information." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T23:05:53.723", "Id": "11577", "ParentId": "11558", "Score": "2" } }, { "body": "<p>While ZeroOne's answer has the good idea to use an enum, the enum itself is not implemented very well. Java enums are a powerful system, and using a switch statement inside the <code>getFileName()</code> method is very unnecessary. Furthermore, the naming conventions are a bit off. Here's a better implementation of the same enum:</p>\n\n<pre><code>private enum FileType {\n QUESTION(\"question.html\"),\n ANSWER(\"answer.html\");\n\n private final String fileName;\n\n FileType(String fileName) {\n this.fileName = fileName;\n }\n\n public String getFileName() {\n return fileName;\n }\n}\n</code></pre>\n\n<p>This uses the unique capabilities of Java enums to store individual parameters. This also changes the names of the enum and its values. Java enum names should be upper camel-case (same as class names), while enum values should be all caps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T02:22:38.193", "Id": "11787", "ParentId": "11558", "Score": "3" } } ]
{ "AcceptedAnswerId": "11577", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T14:34:57.400", "Id": "11558", "Score": "2", "Tags": [ "java", "beginner", "web-scraping", "stackexchange" ], "Title": "CR Stack Exchange crawler" }
11558
Model–View–Controller (MVC) is a design pattern for computer user interfaces that divides an application into three areas of responsibility. It is often applied to websites.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T16:00:49.867", "Id": "11564", "Score": "0", "Tags": null, "Title": null }
11564
<p>I'm working on adding checkbox functionality that controls adding new checkboxes to a <code>div</code> element as well a tracking checkbox behavior. My goal is to make this dirt simple. I've noticed that there is some JavaScript function prototypes for creating objects such as checkboxes and also controlling basic behavior such as visibility, whether its checked or disabled and maybe even adding a label or image next to the checkbox. My plan is to add this to an array or list and how can this be done?</p> <p>I just need basic class object in JavaScript to be created to track just whether its checked, visible, or disabled. In my case when its disabled it will not be checked, but may change in a later release. I've looked at GWT and ZWT JavaScripting libraries and they seem too complicated. Is there a simple solution I can do myself?</p> <p>Looking for some constructive criticism, a good link or two for reference, and perhaps an estimate on whether this is feasible and how would I add a checkbox to the class below, and do I also have to worry about adding events to this? And what would be the best way to track multiple famous people in this example: a list, an array, or another class? I'm thinking a dynamic array of some kind.</p> <pre><code> // Constructor for dynamic checkbox classes var FamousPerson = function (id, checkStatus, visibleStatus, enabledStatus) { this.id = id; // primary key for a person for a specific row this.checkStatus = checkStatus; this.visibleStatus = visibleStatus; this.enabledStatus = enabledStatus; } FamousPerson.prototype.getId() = function () { return this.id; // id is reference stored in xml or database row }; FamousPerson.prototype.update = function (checkStatus, visibleStatus, enabledStatus) { // note: don't update id this.checkStatus = checkStatus; // boolean 0 is not checked, 1 is checked this.visibleStatus = visibleStatus; // boolean 0 is not visible, 1 is visible this.enabledStatus = enabledStatus; // boolean 0 is not enalbed, 1 is enabled }; FamousPerson.prototype.getCheckStatus = function () { return this.checkStatus; }; FamousPerson.prototype.getVisibleStatus = function () { return this.visibleStatus; }; </code></pre>
[]
[ { "body": "<p>In my opinion, it seems like this should be it's own class. You should have another object to control the <code>FamousPerson</code> objects and add them when they are instantiated. I would also decouple the checkbox from the <code>FamousPerson</code> class itself and tie the behavior in elsewhere. </p>\n\n<p>As for the solution part, if you still want to add it in here, check out <a href=\"https://stackoverflow.com/questions/5121042/javascript-can-an-input-type-checkbox-use-appendchild-in-ie8-or-not\">this</a>. There's an example of creating a checkbox with a label and adding it to the DOM. Shouldn't be too hard to patch some of it in to your existing class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T11:41:54.533", "Id": "11587", "ParentId": "11569", "Score": "3" } }, { "body": "<pre><code>this.checkStatus = checkStatus; // boolean 0 is not checked, 1 is checked\nthis.visibleStatus = visibleStatus; // boolean 0 is not visible, 1 is visible\nthis.enabledStatus = enabledStatus; // boolean 0 is not enalbed, 1 is enabled\n</code></pre>\n\n<p>I'd call these fields as <code>checked</code>, <code>visible</code> and <code>enabled</code>. It would make the comments unnecessary and it would be obvious what <code>true</code> and <code>false</code> values mean.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T17:46:30.233", "Id": "11599", "ParentId": "11569", "Score": "1" } }, { "body": "<p>I think you are mixing up different concepts here. Presentation logic is quite different from domain logic and both shouldn't be mixed together. I'm having trouble understanding what you are trying to achieve (what does the checked status means in your domain?), however in my opinion a <code>FamousPerson</code> should be expressed in domain terms and should not have any knowledge of specific ui data such as visible, checked...etc.</p>\n\n<p>I strongly suggest you to read about <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">MVC</a>. There are lots of MVC, MVP, MVVM... flavors in JS and that's why we mostly categorize these as MV* rather than MVC now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-12T23:54:49.233", "Id": "41522", "ParentId": "11569", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T18:11:41.393", "Id": "11569", "Score": "4", "Tags": [ "javascript", "form" ], "Title": "Adding a checkbox to a JavaScript class object" }
11569
<p>From my original question on Stack Overflow: <a href="https://stackoverflow.com/questions/10486743/is-my-implementation-of-reversing-a-linked-list-correct">Is my implementation of reversing a linked list correct?</a></p> <p>I'm a beginner at C and I'd like to know about style, and correctness of the reverse algorithms. What about memory management?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct Node { int val; struct Node *next; } Node; Node * build_list(int num); Node * reverse_list(Node * head); static Node * r_reverseItem(Node * last, Node * head); Node * r_reverse(Node * head); /* * Function which iterates to 100 creating nodes * and linking them to head * */ Node * build_list(int num) { Node * head = NULL; Node * curr; int i; for(i=0;i&lt;num;i++) { curr = (Node *)malloc(sizeof(Node)); curr-&gt;val = i; curr-&gt;next = head; head = curr; } return head; } /* * Function which reverses linked list * by traversing list and flipping ptr of curr to last * @param head * */ Node * reverse_list(Node * head) { if (head == NULL) //only one elem return NULL; Node * last = NULL; do { Node * next = head-&gt;next; head-&gt;next = last; last = head; head = next; } while (head != NULL); return last; } /* * Function which recursively reverses linked list * @param last * @param head * */ static Node * r_reverseItem(Node * last, Node * head) { if (head == NULL) return last; Node * next = head-&gt;next; head-&gt;next = last; return r_reverseItem(head,next); } Node * r_reverse(Node * head) { return r_reverseItem(NULL, head); } int main (void) { Node * head = build_list(5); Node * curr; head = r_reverse(head); // head = reverse_list(head); while(head) { printf("%d\n",head-&gt;val); curr = head; head = head-&gt;next; free(curr); } return 0; } </code></pre>
[]
[ { "body": "<p>Good fix for the edge case of only one element, but what happens if there's only <em>two</em> elements? I'm seeing another edge case concern.</p>\n\n<pre><code>//inside reverse_list\n...\nlast = head;\ncurr = head-&gt;next;\nhead = curr-&gt;next; //or head-&gt;next-&gt;next - null if two elements\n\nlast-&gt;next = NULL\nwhile (head-&gt;next) { //head is null here if list length = 2\n</code></pre>\n\n<p>I see no other major concerns in your algorithm(s).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T20:39:13.770", "Id": "11575", "ParentId": "11573", "Score": "1" } }, { "body": "<h2>Code Comments:</h2>\n<pre><code>curr = malloc(sizeof(Node));\n</code></pre>\n<p><code>malloc()</code> returns <code>void*</code> thus you need to cast it before assignment.</p>\n<pre><code>curr = (Node*) malloc(sizeof(Node));\n</code></pre>\n<p>Most (all I have seen) coding standards mention not to use this:</p>\n<pre><code>Node * head, * curr;\nhead = NULL;\n</code></pre>\n<p>I agree with them as it just makes things hard to read (thus maintain). So one variable per line. And initialize on declaration (where appropriate).</p>\n<pre><code>Node *head = NULL;\nNode *curr;\n</code></pre>\n<p>OK. The next one is arguable (so feel free to use best judgement).</p>\n<p>Personally I find that hard to read:</p>\n<pre><code> if (!head-&gt;next)\n</code></pre>\n<p>I think it would be easier to read as:</p>\n<pre><code>if (head-&gt;next == NULL)\n</code></pre>\n<p>But surprisingly I normally I prefer using the <code>!</code> when the object is a pointer (or bool). I think in this case it is because it is combined with testing a nested member of a structure it just does not look correct (but as I said it is an arguable case).</p>\n<h2>Edge Case</h2>\n<p>What happens if the list is empty?</p>\n<pre><code>Node * reverse_list(Node * head) {\n\n if (!head-&gt;next) //only one elem\n return head;\n</code></pre>\n<p>You have chosen the wrong edge case.<br />\nThe one you should be checking is checking for NULL. A list of one node is no different than a list of many. The edge case with pointers is nearly always the NULL case.</p>\n<h2>Algorithm</h2>\n<h3>Iterative</h3>\n<p>The code before your while loop looks like the code inside the while loop. This sort of suggests you can replace it with a do-while loop. Thus your iterative code should look more like this:</p>\n<pre><code>Node* reverse(Node* list)\n{\n if (list == NULL)\n { \n return NULL;\n } \n\n Node* last = NULL;\n do \n { \n Node* next = list-&gt;next;\n list-&gt;next = last;\n last = list;\n list = next;\n } \n while(list != NULL);\n\n return last;\n}\n</code></pre>\n<h3>Recursive</h3>\n<p>Converting a loop into recursion requires an extra function to cope with the extra variable used for last. So the main recursion looks like this (it just calls the actually recursive function setting up the last parameter). You should have this wrapper function to help users of the code from calling the recursive part of the function incorrectly.</p>\n<pre><code>Node* r_reverse(Node* list)\n{\n return r_reverseItem(NULL, list);\n}\n</code></pre>\n<p>Now we can do the recursion. Again the edge case is still NULL.</p>\n<pre><code>Node* r_reverseItem(Node* last, Node* list)\n{\n if (list == NULL)\n { \n return last;\n } \n\n Node* next = list-&gt;next;\n list-&gt;next = last;\n return r_reverseItem(list,next);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T04:53:23.950", "Id": "11581", "ParentId": "11573", "Score": "4" } } ]
{ "AcceptedAnswerId": "11581", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T20:15:29.690", "Id": "11573", "Score": "6", "Tags": [ "c", "beginner", "recursion", "memory-management" ], "Title": "Reversing a linked list by iteration and recursion" }
11573
<p>I'm uploading videos to Vimeo using the <a href="http://vimeo.com/api/docs/upload" rel="nofollow">VimeoAPI</a>. I want to show a progress bar to the user. The only way to do this with the VimeoAPI is to call a method to the server which verifies the chunk you've just sent. I can send a video up in chunks of 8 bytes or 2 gigabytes. For the progress bar, the smaller the better, but there's a huge performance hit it keeps verifying the bytes every couple bytes.</p> <p><strong>So I am wondering</strong>, is there an optimal buffer size in which you think would be the best of both worlds? Currently I'm using a size of 10 MB. The files I upload will normally be around 750 MB or so... But some are 30 MB or so... I'm including my code just in case anyone finds it helpful.</p> <pre><code>/** * Send the video data * * @return whether the video successfully sent */ private boolean sendVideo(String endpoint, File file) throws FileNotFoundException, IOException { // Setup File long contentLength = file.length(); String contentLengthString = Long.toString(contentLength); FileInputStream is = new FileInputStream(file); int bufferSize = 10485760; // 10 MB = 10485760 bytes byte[] bytesPortion = new byte[bufferSize]; int maxAttempts = 5; //This is the maximum attempts that will be given to resend data if the vimeo server doesn't have the right number of bytes for the given portion of the video long lastByteOnServer = 0; boolean addContentRange = false; while (is.read(bytesPortion, 0, bufferSize) != -1 &amp;&amp; getStatus() != TransferObject.STOPPED) { //Check that this isn't the last chunk. If it is, we want to send just the last bytesPortion, not a whole other full bufferSized one int remainingBytes = (int) (contentLength - lastByteOnServer); PrinterHelper.print(StringHelper.newline + getVideoTitle() + " has " + remainingBytes + " bytes remaining."); if (remainingBytes &lt; bufferSize) { bytesPortion = Arrays.copyOf(bytesPortion, remainingBytes); bufferSize = remainingBytes; // Just so it doesn't complain on the next iteration (which should break the while loop) } lastByteOnServer = prepareAndSendByteChunk(endpoint, contentLengthString, lastByteOnServer, bytesPortion, addContentRange, 0, maxAttempts); if (lastByteOnServer == -1) { return false; } addContentRange = true; getProgressBar().setValue(NumberHelper.getPercentFromTotal((int) lastByteOnServer, (int) getTransfer().getFileSize())); } return true; } /** * Prepares the given bytes to be sent to Vimeo * * @param endpoint * @param contentLengthString * @param lastByteOnServer * @param byteChunk * @param addContentRange * @param attempt * @param maxAttempts * @return number of bytes currently on the server * @throws FileNotFoundException * @throws IOException */ private long prepareAndSendByteChunk(String endpoint, String contentLengthString, long lastByteOnServer, byte[] byteChunk, boolean addContentRange, int attempt, int maxAttempts) throws FileNotFoundException, IOException { if (attempt &gt; maxAttempts) { return -1; } else if (attempt &gt; 0) { PrinterHelper.printErr("Attempt number " + attempt + " for video " + getVideoTitle()); } long totalBytesShouldBeOnServer = lastByteOnServer + byteChunk.length; String contentRange = lastByteOnServer + "-" + totalBytesShouldBeOnServer; long bytesOnServer = sendVideoBytes(endpoint, contentLengthString, "video/mp4", contentRange, byteChunk, addContentRange); addContentRange = true; if (bytesOnServer != totalBytesShouldBeOnServer) { PrinterHelper.printErr(bytesOnServer + " (bytesOnServer)" + " != " + totalBytesShouldBeOnServer + " (totalBytesShouldBeOnServer) for " + getVideoTitle()); long remainingBytes = totalBytesShouldBeOnServer - bytesOnServer; int beginning = (int) (byteChunk.length - remainingBytes); int ending = (int) byteChunk.length; byte[] newByteChunk = Arrays.copyOfRange(byteChunk, beginning, ending); return prepareAndSendByteChunk(endpoint, contentLengthString, bytesOnServer, newByteChunk, addContentRange, attempt + 1, maxAttempts); } else { return bytesOnServer; } } /** * Sends the given bytes to the given endpoint * * @return the last byte on the server (from verifyUpload(endpoint)) */ private long sendVideoBytes(String endpoint, String contentLength, String fileType, String contentRange, byte[] fileBytes, boolean addContentRange) throws FileNotFoundException, IOException { OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint); request.addHeader("Content-Length", contentLength); request.addHeader("Content-Type", fileType); if (addContentRange) { request.addHeader("Content-Range", "bytes " + contentRange + "/" + contentLength); } request.addPayload(fileBytes); try { Response response = VimeoController.signAndSend(vimeoService, vimeoAccount.getVimeoToken(), request, "sendVideo on " + getVideoTitle(), false); if (response.getCode() != 200 &amp;&amp; !response.isSuccessful()) { return -1; } } catch (Exception ex) { PrinterHelper.printErr("There was an exception for video " + getVideoTitle() + " in sendVideoBytes: " + StringHelper.newline + ex); Logger.getLogger(VimeoUpload.class.getName()).log(Level.SEVERE, null, ex); return -1; } return verifyUpload(endpoint); } </code></pre>
[]
[ { "body": "<p>An idea: measure how fast is the user's internet connection, how many bytes they can send per ten second, for example, then use this as chunk size. It should have a minimum value which is bigger than 8 bytes because of the TCP/IP overhead. Check the overhead with a packet sniffer (<a href=\"http://www.ethereal.com/\" rel=\"nofollow\">Ethereal</a>, for example).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T06:45:50.457", "Id": "11583", "ParentId": "11578", "Score": "1" } } ]
{ "AcceptedAnswerId": "11583", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T02:01:49.603", "Id": "11578", "Score": "1", "Tags": [ "java", "optimization" ], "Title": "Optimal buffer size for HTTP PUT" }
11578
<p>I use the following code to store user passwords.</p> <pre><code>string password = "..."; string user_salt = System.Web.Security.Membership.GeneratePassword(20, 5); string common_salt = "..."; byte[] hash_target = Encoding.UTF8.GetBytes(password + user_salt + common_salt); string password_hash = BitConverter. ToString(new SHA512CryptoServiceProvider().ComputeHash(hash_target)). Replace("-", string.Empty). ToUpper(); </code></pre> <p>The user salt is stored together with the hashed password in the database. Additionally, every time a user's password is changed, the user salt is regenerated.</p> <p>The reasoning behind a common salt and a user salt is: access to the database alone isn't enough to figure out how the hashing works. And then in case someone manages to disassemble the code, the malicious user cannot make use of a single rainbow table.</p> <p>Is this a good method?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T13:41:18.933", "Id": "18586", "Score": "3", "body": "Semi-related: `SHA512CryptoServiceProvider` implements `IDisposable`, so it should be assigned to a variable and wrapped in a `using` block." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T14:49:28.587", "Id": "18591", "Score": "0", "body": "Why use `string.Empty` instead of `\"\"`? It’s six times as long." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T14:51:45.370", "Id": "18592", "Score": "6", "body": "@KonradRudolph Personal preference for readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T15:03:47.430", "Id": "18594", "Score": "1", "body": "@Stijn I’ve never understood these preferences. How is that more readable? Sorry for the flame bait, I’m just seriously baffled and find it a horrid practice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T15:08:17.287", "Id": "18595", "Score": "0", "body": "@KonradRudolph that's ok, it is personal preference after all. Just like my preference for avoiding `thisKindOfVariable` and using `this_kind_of_variable` instead. I prefer whatever I find easier to read through." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T08:37:50.733", "Id": "18630", "Score": "1", "body": "@KonradRudolph `\"\"` is a value and `string.Empty` is a constant declared for this value. This is of course a very well known value but still can be considered magic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T10:41:27.320", "Id": "18634", "Score": "0", "body": "@Den Sorry, I don’t think this is a valid reason, it’s a mis-application of a general principle which isn’t valid here. `\"\"` is no more a special value than `string.Empty`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T11:16:48.190", "Id": "18635", "Score": "2", "body": "@KonradRudolph I find string.Empty not only more readable but safer because as soon as you start coding string literals, you introduce potential for a fat-finger typo. I take it you haven't hunted down a bug that turned out to be \" \" instead of \"\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T12:19:35.437", "Id": "18639", "Score": "0", "body": "@Adam Never. I seriously doubt that this is a real issue. Writing `string.Empty` instead of `\"\"` is like writing `int.Zero` instead of `0`, or `object.None` instead of `null`. Wait, those don’t exist. I wonder why … ah, because it would be ridiculous, meaningless code bloat." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T12:23:17.453", "Id": "18640", "Score": "0", "body": "Feel free to continue this discussion in a chat room, I'm getting notifications for a discussion unrelated to my question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-24T15:54:29.140", "Id": "166298", "Score": "0", "body": "20 and 5 should be named (probably const) variables because without looking up the GeneratePassword method I have no idea what they do." } ]
[ { "body": "<p>In SQL Server, we store password salts as an int and password hashes as binary. There really is no reason to have the salt as a string value. Also, there is no need to have the hash as a string. You can use the bytes from the computed hash (which is a fixed, known number of bytes) and store the binary value directly in the database. These two things make it very fast to check check against when attempting to verify the password.</p>\n\n<p>See my answer on <a href=\"https://stackoverflow.com/a/4331313/498969\">Stack Overflow here</a> about hashing passwords using SHA-1. You are using SHA-512, which the code can easily be adopted to support.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T11:25:44.607", "Id": "11615", "ParentId": "11588", "Score": "2" } }, { "body": "<p>Including a secret shared salt, in addition to a per-hash salt, is a decent idea, at the very least it doesn't hurt. I typically put the common salt(which is essentially a key) into a config file instead embedding it in the application code.</p>\n\n<p>On the other hand SHA-512 is completely wrong, since it's fast, and thus cheap to brute-force. You should use a slow key derivation function, such as PBKDF2, bcrypt, or scrypt. The only one of these built into .net is PBKDF2-HMAC-SHA-1, exposed through the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx\" rel=\"nofollow\"><code>Rfc2898DeriveBytes</code> class</a>. Choose the number of iterations as high as possible without hurting the performance of your application.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T20:01:17.400", "Id": "18816", "Score": "0", "body": "Didn't know about PBKDF2. I had looked into bcrypt and scrypt a few months ago and found one or two implementations, but couldn't be sure about their stability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T23:04:33.807", "Id": "18822", "Score": "0", "body": "PBKDF2 is the way to go." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T21:15:01.130", "Id": "11704", "ParentId": "11588", "Score": "2" } } ]
{ "AcceptedAnswerId": "11615", "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T12:05:58.637", "Id": "11588", "Score": "1", "Tags": [ "c#", "security" ], "Title": "Password hashing" }
11588
<p>This linq query works, and it does what I want it to do, but is there any other way I could improve the query so I'm not repeating <code>a.AnswerRevisions.OrderByDescending(r =&gt; r.DateCreated).FirstOrDefault()</code>?</p> <pre><code>IQueryable&lt;Article&gt; query = from a in _db.Articles orderby a.DateCreated descending where a.AnswerRevisions.Count &gt; 0 &amp;&amp; (a.AnswerRevisions.OrderByDescending(r =&gt; r.DateCreated).FirstOrDefault().UpVotes - a.AnswerRevisions.OrderByDescending(r =&gt; r.DateCreated).FirstOrDefault().DownVotes &lt; 0) select a; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T13:14:43.393", "Id": "18584", "Score": "3", "body": "I'd rather do `.UpVotes < .Downvotes`." } ]
[ { "body": "<p>Use the <code>let</code> statement and also do the final <code>orderby</code> after the <code>where</code> clause, this will increase efficiency, as less entries will have to be sorted</p>\n\n<pre><code>IQueryable&lt;Article&gt; query = from a in _db.Articles \n let rev = a.AnswerRevisions.OrderByDescending(r =&gt; r.DateCreated).FirstOrDefault()\n where a.AnswerRevisions.Count &gt; 0 &amp;&amp; \n (rev.UpVotes - rev.DownVotes &lt; 0) \n orderby a.DateCreated descending \n select a; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T15:03:02.870", "Id": "18593", "Score": "0", "body": "Ok thanks that's great - never used the let clause before, works really well in this situation. Kudos on the orderby too, I was under the impression that with linq-to-entities the orderby had to be before the where but I was wrong on that front!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-13T18:15:50.503", "Id": "252337", "Score": "0", "body": "I'm pretty sure the query generated by EF will account for the order of ordering/filtering, and if not, the underlying DB should when executing the query. I haven't actually tested it though, so don't quote me on that!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-13T18:54:33.330", "Id": "252353", "Score": "0", "body": "It might make no difference with EF, but if you have linq-to-objects it will. In SQL the `order by` comes always after `where`. It feels better to have order by at the end." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T12:50:31.340", "Id": "11590", "ParentId": "11589", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T12:41:41.823", "Id": "11589", "Score": "2", "Tags": [ "c#", "linq", "entity-framework" ], "Title": "How could I remove repetition from this linq-to-entities query?" }
11589
<p>I'm novice in C++, I've recently read some simple books and now I'm reading <code>Scott Meyers "Effective C++"</code> book, but I understand that I can't apply new knowledge.</p> <p>I have to realize a simple C++ class that (with help of openCV) generates bitmap kernels consist of n circles.</p> <p>Here is my code: <a href="https://gist.github.com/2638329/368bc56ffd3b00d04ff20064bf63d87f14e9cd72" rel="nofollow">Link to source on gist.github.com</a></p> <p><code>Kernel</code> class is a wrapper for cv::Mat kernels. Just for simpler access to center, radius and data. <code>KernelFactory</code> is class that generates kernels (double-circle kernel, one-circle kernel or n-circle kernel).</p> <p>I need a piece of advice about how correctly declare class members and methods? Do I need to keep some members as references, or no?</p> <p><strong>UPDATE 1:</strong></p> <p>According to the advice and comments of <code>@Loki Astari</code> I've made some changes in my first variant of code, and here is new version of code, with a few questions, written as Notes in comments in code.</p> <pre><code>/// Calculating the max value of array int maxArr(std::vector&lt;int&gt; const&amp; arr) { return *std::max_element(arr.begin(), arr.end()); // Note 0. // Maybe, it's preffered to write something like: // int max = ....; // return max; // ? } /** * Wrapper for cv::Mat kernel */ class Kernel { private: // Data (array) of kernel cv::Mat data; public: // Note 1. // Constructor gets const cv::Mat array by value // Should I use `by reference`? Using copying by value, it means // that creating Kernel instance i have array of cv::Mat in 2 copies: // 1) where it was created before constructing, // 2) after constructing in class member `data` Kernel(const cv::Mat kernel) { data = kernel; } /** * Getters */ cv::Mat const&amp; getData() const { return data; } cv::Mat&amp; getData() { return data; } int getSize() const { return data.rows; } int getRadius() const { return (data.rows-1)/2; } cv::Point getCenter() const { int R = getRadius(); cv::Point center(R-1, R-1); return center; } // Note 2. Now, am I going in right direction using the getters? ;) }; /** * Factory for Kernels */ class KernelFactory { private: static int const POINT_VALUE = 255; /// Draw a circle on Mat kernel in some center of radius r void draw_circle(cv::Mat&amp; kernel, const cv::Point2f center, int r) const { int c = ceil ( (r-2)/2 ); int d = c+1; for (int ci=-c; ci&lt;=c; ci++) { kernel.at&lt;char&gt;(center.y + (r-1), center.x + ci) = POINT_VALUE; kernel.at&lt;char&gt;(center.y - (r-1), center.x + ci) = POINT_VALUE; kernel.at&lt;char&gt;(center.x + ci, center.y + (r-1)) = POINT_VALUE; kernel.at&lt;char&gt;(center.x + ci, center.y - (r-1)) = POINT_VALUE; } for (int di=1; di&lt;=d; di++) { kernel.at&lt;char&gt;(center.y + (r-1-di), center.x + di + c) = POINT_VALUE; kernel.at&lt;char&gt;(center.y - (r-1-di), center.x + di + c) = POINT_VALUE; kernel.at&lt;char&gt;(center.x - di - c, center.y - (r-1-di)) = POINT_VALUE; kernel.at&lt;char&gt;(center.x + di + c, center.y - (r-1-di)) = POINT_VALUE; } } /// Generic function for building n-size circle mask /// This function is called by other public facades Kernel build_circle_mask_n(std::vector&lt;int&gt; const&amp; radiuses) { int n = radiuses.size(); int Rmax = maxArr(radiuses); int kernel_size = Rmax*2-1; cv::Mat kernel = cv::Mat::ones(kernel_size, kernel_size, CV_8U); cv::Point center(Rmax-1, Rmax-1); for (int i=0; i&lt;n; i++) { draw_circle(kernel, center, radiuses[i]); } return Kernel(kernel); // Note 3: // Is this resource-safe of returning instance of Kernel in this situation? } public: /// Build n-circle mask kernel Kernel circleMaskN(std::vector&lt;int&gt; const&amp; radiuses) { return build_circle_mask_n(radiuses); } /// Build Double-circle mask kernel Kernel circleMask2(int r, int R) { std::vector&lt;int&gt; radiuses(2); radiuses[0] = r; radiuses[1] = R; return build_circle_mask_n(radiuses); } /// Build uni-circle kernel Kernel circleMask(int r) { std::vector&lt;int&gt; radiuses(1); radiuses[0] = r; return build_circle_mask_n(radiuses); } // Note 4: // Should I overload circleMaskN method for a case // when radius-vector is of size = 1? // Maybe I should write a version of build_circle_mask_n // that gets integer parameter, but not vector(1)? }; </code></pre> <p>If you prefer gist syntax much, <a href="https://gist.github.com/2638329/fcfdc1e21ac8894e4e186c3ca7272608b0b0af2d" rel="nofollow">here</a> is a gist link to this source.</p>
[]
[ { "body": "<p>The first thing that I notice is:</p>\n<pre><code>int maxArr(int arr[], int length)\n</code></pre>\n<p>Notice that you have to pass an array and a length (as the size is not part of the array). In C++ we usually fix this by using std::vector (or std::array in C++11). Pass this object around as it contains the size information.</p>\n<p>Also notice that arrays actually decay to pointers. And in this function the content of the array is not modified (or it looks like the content should not be modified). Thus you really want to pass a const version to indicate your intention. This will also prevent accidental mistakes in the future.</p>\n<pre><code>int maxArr(std::vector&lt;int&gt; const&amp; arr)\n</code></pre>\n<p>Now this finds the maximum element in the array. If you look in the standard library you will notice that there is already an <a href=\"http://www.sgi.com/tech/stl/max_element.html\" rel=\"nofollow noreferrer\">algorithm</a> that does this (getting used to the <a href=\"http://www.sgi.com/tech/stl/table_of_contents.html\" rel=\"nofollow noreferrer\">standard library</a> will save you a lot of time):</p>\n<pre><code>int max = *std::max_element(arr.begin(), arr.end()); // assuming arr is a vector\n\n// note: std::max_element() returns an iterator so is only guranteed to work if\n// the container is not empty.\n</code></pre>\n<p>OK. I hate getter/setters they totally break encapsulation (<a href=\"https://softwareengineering.stackexchange.com/questions/21802/when-are-getters-and-setters-justified\">OK I exagerate but they are totally overused by beginners</a>). They basically tightly couple your code to a particular implementation of an internal representation. You may think they allow you to change the implementation this is nearly always false apart from the simplest of classes where you can transform the internal representation easily. But if the object is complex and/or expensive to create it basically traps you into a specific implementation. Your method should be actions (think of verbs) that manipulate the object. OK. Moving on.</p>\n<p>Are you sure you want to return by value:</p>\n<pre><code>cv::Mat getData() const\n{\n return data; \n}\n</code></pre>\n<p>Because you are returning by value you are copying the value out of the object. This is not usually what you want. You generally want to return a reference to the object inside your object (not because the getter is const you want to return a const reference).</p>\n<pre><code>cv::Mat const&amp; getData() const\n // ^^^^^^\n{\n return data; \n}\n</code></pre>\n<p>If you want the getter to return an object that can be manipulated then you should also create a non const version.</p>\n<pre><code>cv::Mat &amp; getData()\n // ^^^ Note: ^^^^^^ no const here.\n{\n return data; \n}\n</code></pre>\n<p>OK. You store some values about the data object:</p>\n<pre><code> size = kernel.rows;\n radius = (size-1)/2;\n center = calc_center(radius);\n</code></pre>\n<p>Do you really need to store these values? It seems the getter could just get the value from the <code>data</code> object.</p>\n<pre><code>int getSize() const { return data.rows; }\n</code></pre>\n<p>Thus if <code>data</code> is modified you return the correct number of rows. I know currently in your design you can not modify <code>data</code> as it is not exposed. But this will future proof your code to changes that can happen in the future.</p>\n<p>Comments are great. But they should not be explaining the code (the code does that). They should explain your intention. Then a maintainer can verify that the code implements the intention.</p>\n<p>Perfect example of a crap comment:</p>\n<pre><code>// value of 1 to set in mask\nint VALUE;\n</code></pre>\n<p>Yet later in the code:</p>\n<pre><code>/// Constructor (nothing happens)\nKernelFactory(): VALUE(255) {}\n</code></pre>\n<p>Really 255 or 1 what does it mean. Do you really need to tell me it is a constructor. Do you think I am so stupid you need to tell me? I can see it is a constructor why are you wasting space with a meaningless comment.</p>\n<p>If this is const and never modified then it should be declared as a const. Since the same thing is used in all instances of KernelFactory we may as well declare it as static:</p>\n<pre><code>static int const VALUE = 255;\n</code></pre>\n<p>Now you don't even need a constructor! (what do I do with the comment).</p>\n<p>Returning a const value has no meaning.</p>\n<pre><code>const Kernel circleMaskN(int n, int radiuses[])\nconst Kernel circleMask2(int r, int R)\nconst Kernel circleMask(int r)\n</code></pre>\n<p>Because you are returning a value you are copying the value out of the function.</p>\n<h2>EDIT</h2>\n<p>Based on code changes:</p>\n<pre><code>// Note 1. \n// Constructor gets const cv::Mat array by value\n// Should I use `by reference`? Using copying by value, it means\n// that creating Kernel instance i have array of cv::Mat in 2 copies:\n// 1) where it was created before constructing,\n// 2) after constructing in class member `data`\n\nKernel(const cv::Mat kernel) \n</code></pre>\n<p>Yes you should be passing by const reference here. What is happening is that you pass by value so a copy is done calling the copy constructor creating the parameter <code>kernel</code>. Then the during the assignment another copy is done copying <code>kernel</code> into <code>data</code>.</p>\n<p>Also you should prefer to use the initializer list. Otherwise you will be default constructing <code>data</code> before using the assignment operator to copy <code>kernal</code> into <code>data</code>.</p>\n<p>So your code is currently:</p>\n<pre><code>1) Copy Construct cv::Map into kernal\n2) Default construct data\n3) Use assignment operator from kernal into data\n This is probably another copy.\n</code></pre>\n<p>Your constructor should look like this:</p>\n<pre><code>Kernel(cv::Mat const&amp; kernel)\n : data(kernal) // Only one copy directly to data on copy construction.\n{} \n</code></pre>\n<blockquote>\n<p>Note 2. Now, am I going in right direction using the getters?</p>\n</blockquote>\n<p>Better.</p>\n<blockquote>\n<p>Note 3: Is this resource-safe of returning instance of Kernel in this situation?</p>\n</blockquote>\n<p>This is fine.<br />\nIf you are using C++11 you may want to look up move constructors to see if you can avoid copy the Kernel object during the return.</p>\n<blockquote>\n<p>Note 4:\nShould I overload circleMaskN method for a case\nwhen radius-vector is of size = 1?\nMaybe I should write a version of build_circle_mask_n\nthat gets integer parameter, but not vector(1)?</p>\n</blockquote>\n<p>That totally depends on use case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T18:43:09.497", "Id": "18610", "Score": "0", "body": "Thank you very much for your comments. I've made some changes in my code (in question post). Can you look at it now, after changes, and say a few words? (There are some questions in comments in code)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T21:50:41.800", "Id": "18623", "Score": "0", "body": "Please don't edit the question like that. Questions and answers become out of sync and thus less valuable to new readers. Any changes should be **additions** to the question not a modification." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T19:30:16.237", "Id": "18668", "Score": "0", "body": "Thank you for all your comments. I appreciate your help. About my post edit. I've *added* some new information, my only change of main post was that I've hidden the first variant of source code under the link - to make the post question a bit shorter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-09T03:51:19.950", "Id": "357058", "Score": "0", "body": "I think that returning by value invokes the move constructor, and compiler by even elide it, are you sure is not better to return the return element by value?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-09T16:36:15.990", "Id": "357182", "Score": "0", "body": "@WooWapDaBug: A return by value will invoke move if the object being returned is an r-value (or is it x-value in the new terminology). But an object member is not an r-value and thus will be copied; otherwise you would be destroying (making it undefined as the result of a move) the value in the object which is not acceptable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-09T16:40:16.800", "Id": "357183", "Score": "0", "body": "@WooWapDaBug Copy elision happens when you are returning a new value. Rather than build it in the current stack frame you build it at the location that it will be returned to in the higher stack frame. But here we are returning a member of an object. As the object already exists you can not elide the copy." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-09T16:42:24.057", "Id": "357184", "Score": "0", "body": "@WooWapDaBug: `are you sure is not better to return the return element by value`. Sure is a very strong word. I can only give advice based on the code shown (there may be more context that I am unaware of that could change my mind). But given the code above I think returning by `const reference` is the best option. This will prevent unneeded copies but does not prevent the user of the code from creating a copy by assigning the result to an object rather than a reference variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-09T16:56:56.293", "Id": "357186", "Score": "0", "body": "Great, thank you very much for the explanation, now it's way clearer to me! I didn't notice it was a member of the class. Thank you again!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T16:06:55.263", "Id": "11595", "ParentId": "11592", "Score": "2" } } ]
{ "AcceptedAnswerId": "11595", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T13:57:10.737", "Id": "11592", "Score": "3", "Tags": [ "c++" ], "Title": "C++ Kernel Factory class" }
11592
<p>In an effort to learn as much as possible about best development practices and software architecture, I created my own MVC framework using PHP (github: <a href="https://github.com/alemmedia/miniMVC" rel="nofollow">https://github.com/alemmedia/miniMVC</a>). I've found that this has resulted in phenomenal improvements in my programming skills, but I'm still limited by my own limited experience when it comes to reviewing my code.</p> <p>I'd like to get your critique on one of my least favorite classes (I always feel like there is something off about them):</p> <p>Here is my Session singleton I use to access/manage session data.</p> <pre><code>class Session{ /** * @var object Holds the single instance of Session */ private static $instance; /** * @var string The session id of the current session */ protected $id; /** * @var mixed The data to be held in session. */ public $data; /** * __construct - Starts session * * Establishes Session::data reference to $_SESSION superglobal array, and sets session id. * Privately held an called only by Session::open for singleton functionality */ private function __construct(){ session_start(); $this -&gt; id = session_id(); $this -&gt; data =&amp; $_SESSION; } /** * open - Creates singleton instance of Session object * * @return object */ public static function open() { if ( !isset(self::$instance) ) self::$instance = new self(); return self::$instance; } /** * set - Recieves variables to set to $_SESSION array * * @param string $property The property to set to the session * @param mixed $value The balue to set to the property * @param bool $make_array If set to true the property will be an numeric array */ public static function set($property, $value = null, $make_array = false){ if ( is_array( $property) ){ foreach($property as $key =&gt; $single_property) Session::open() -&gt; set($key, $single_property); }else{ if ($make_array == false) Session::open() -&gt; data[$property] = $value; else Session::open() -&gt; data[$property][] = $value; } } /** * del - Recieves variables to delete in $_SESSION array * * @param string $property The property to delete from the session */ public static function del($property){ if ( is_array( $property) ){ foreach($property as $key =&gt; $single_property) Session::open() -&gt; del($key); }else unset(Session::open() -&gt; data[$property]); } /** * get - Returns variables from $_SESSION array. * * @param string $property The property to retrieve from the session * @return mixed|bool The retrieved property or false. */ public static function get($property){ if ( isset( Session::open() -&gt; data[$property] ) ) return Session::open() -&gt; data[$property]; else return false; } /** * get - Returns variables from $_SESSION array and subsequently deletes them. * * @param string $property The property to retrieve and delete from the session * @return mixed The retrieved property. */ public static function getThenDel($property){ $result = Session::open() -&gt; get ($property); Session::open() -&gt; del ($property); return $result; } } </code></pre> <p>Let me know if you've spotted any mistakes or have any suggestions. Also, if you've found any code in the GitHub repository to be sub-optimal, I'd be happy to hear your comments.</p>
[]
[ { "body": "<p>Use braces <code>{}</code>! Can't say this enough. PHP has made many mistakes, but allowing this syntax is by far the worst. Adding those braces only increases file size by 2 bits! And it increases readability so much!</p>\n\n<pre><code>if ( !isset(self::$instance) ) { self::$instance = new self(); }\n</code></pre>\n\n<p>I'd check out the magic setter and getter methods (<code>__set()</code> and <code>__get()</code> respectively). Instead of calling a set or get method manually you just pass the variable you want. So...</p>\n\n<pre><code>$sessObj-&gt;set('var', 'value');\n$sessObj-&gt;set('array', 'value', TRUE);\nvar_dump($sessObj-&gt;get('var'));\nvar_dump($sessObj-&gt;get('array'));\n//compared to\n$sessObj-&gt;var = 'value';\n$sessObj-&gt;array[] = 'value';\nvar_dump($sessObj-&gt;var);\nvar_dump($sessObj-&gt;array);\n</code></pre>\n\n<p>Why are you not using <code>$this</code>? I mean, I don't use static methods at all really so correct me if I'm wrong, but from what I understand you can still access the internal instance by just using <code>$this</code>. So replace all <code>Session::open()</code> with <code>$this</code>. Even if you can't I would just dump all those static methods just for that alone. Why <em>is</em> everything static? If its not necessary, and I can't imagine why it would be, it shouldn't be static.</p>\n\n<pre><code>$this-&gt;set($key, $single_property);\n</code></pre>\n\n<p>Because my suggestions would change this code so drastically I will finish the review here. Hope this helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T16:47:46.083", "Id": "11597", "ParentId": "11594", "Score": "4" } }, { "body": "<p>I have a similar session manager class in my MVC framework, and while I have absolutely nothing against Singletons (I apply the pattern where it makes sense, e.g. factories); I never felt that it made sense to use the pattern with my <code>SessionManager</code> class. If your goal was to prevent the object instance from being copied/cloned (by design or accidentally) you could opt for a regular ole' class and use <code>private final __clone(){}</code> to prevent the object instance from being cloned.</p>\n\n<p>Using <code>$this-&gt;method()</code> was more legible (for me) than using <code>self::method()</code> or <code>SessionManager::method()</code> especially where referencing/calling class members/methods was concerned.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T01:17:55.907", "Id": "17627", "ParentId": "11594", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T15:59:56.707", "Id": "11594", "Score": "1", "Tags": [ "php", "mvc" ], "Title": "PHP MVC Framework Class" }
11594
<p>I have written a program to find all the possible permutations of a given list of items. This precisely means that my program prints all possible P(n,r) values for r=0 to n.</p> <pre><code>package com.algorithm; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; public class Permutations&lt;T&gt; { public static void main(String args[]) { Permutations&lt;Integer&gt; obj = new Permutations&lt;Integer&gt;(); Collection&lt;Integer&gt; input = new ArrayList&lt;Integer&gt;(); input.add(1); input.add(2); input.add(3); Collection&lt;List&lt;Integer&gt;&gt; output = obj.permute(input); int k = 0; Set&lt;List&lt;Integer&gt;&gt; pnr = null; for (int i = 0; i &lt;= input.size(); i++) { pnr = new HashSet&lt;List&lt;Integer&gt;&gt;(); for(List&lt;Integer&gt; integers : output){ pnr.add(integers.subList(i, integers.size())); } k = input.size()- i; System.out.println("P("+input.size()+","+k+") :"+ "Count ("+pnr.size()+") :- "+pnr); } } public Collection&lt;List&lt;T&gt;&gt; permute(Collection&lt;T&gt; input) { Collection&lt;List&lt;T&gt;&gt; output = new ArrayList&lt;List&lt;T&gt;&gt;(); if (input.isEmpty()) { output.add(new ArrayList&lt;T&gt;()); return output; } List&lt;T&gt; list = new ArrayList&lt;T&gt;(input); T head = list.get(0); List&lt;T&gt; rest = list.subList(1, list.size()); for (List&lt;T&gt; permutations : permute(rest)) { List&lt;List&lt;T&gt;&gt; subLists = new ArrayList&lt;List&lt;T&gt;&gt;(); for (int i = 0; i &lt;= permutations.size(); i++) { List&lt;T&gt; subList = new ArrayList&lt;T&gt;(); subList.addAll(permutations); subList.add(i, head); subLists.add(subList); } output.addAll(subLists); } return output; } } output: P(3,3) : Count (6) :- [[1, 2, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2], [2, 1, 3], [1, 3, 2]] P(3,2) : Count (6) :- [[3, 1], [2, 1], [3, 2], [1, 3], [2, 3], [1, 2]] P(3,1) : Count (3) :- [[3], [1], [2]] P(3,0) : Count (1) :- [[]] </code></pre> <p>My problem is increasing the numbers in the input list. Running time increases, and after 11 numbers in the input list, the program almost dies. Takes around 2 GB memory to run.</p> <p>I am running this on a machine having 8GB RAM and i5 processor, so the speed and space is not a problem. </p> <p>I would appreciate it if anyone can help me write more efficient code.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T18:23:34.073", "Id": "18608", "Score": "0", "body": "http://codereview.stackexchange.com/a/6991/9390" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T20:26:54.823", "Id": "18617", "Score": "2", "body": "You might want to write an `Iterator` class instead - your method fills up memory with every possible permutation - an iterator would only ever store one permutation at once, and find the next permutation from the previous every time you need it. Have a look at [Wikipedia](http://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order) for some algorithms to do this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T20:01:55.263", "Id": "53938", "Score": "1", "body": "Signed up just to comment. This is the only code on the internt that I can find to do nPr on anything besides strings. This saved me days of work. Thanks! I am using this code as the main piece in my brute-force exhaustive tree search. Like you were complaining about, the time it takes to perform my search blows up with anything larger than 10 entities. This is to be expected, as the number of possible permutations increase factorally. Good news though...if you solve this issue, you win a nobel prize." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T20:21:18.230", "Id": "53939", "Score": "0", "body": "@dberm22 thanks for the Nobel prize though :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-17T03:51:54.053", "Id": "157450", "Score": "1", "body": "2 years later, and I just published a github repo with a whole bunch of different search algorithms for solving bipartite graphs. https://github.com/dberm22/Bipartite-Solver . This entire project started with just your code, so I wanted to thank you again. If you take a close look, you can still see most of the original code (a bit tweaked) here: https://github.com/dberm22/Bipartite-Solver/blob/master/src/com/dberm22/bruteforce/Permutations.java" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-03T06:26:14.510", "Id": "168036", "Score": "0", "body": "@dberm22 saw your github repo... Really interesting... and I feel really happy that this code was worth something." } ]
[ { "body": "<p>The number of permutations typically increases factorially. Since 3! = 6, 4! = 24, 5! = 120, 6! = 720, 7! = 5040, 8! = 40,320, 9! = 362,880, 10! = 3,628,800, 11! = 39,916,800, 12! = 479,001,600.</p>\n\n<p>You can see that it get very large, very quickly. The output would be similarly huge.</p>\n\n<p>The bottom line is, that past a certain point, there's just no way to keep the entire set in memory. A couple of numbers later, you wouldn't be able to afford a disk drive large enough to store it. A couple of number after that, there isn't enough paper on the planet to be able to print it. Somewhere in the 30's or 40's, there wouldn't be enough atoms in the entire universe to represent the results in an atomic scale computer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T17:57:44.743", "Id": "18607", "Score": "0", "body": "Thank you sir. Does that mean the algorithm to find permutation does suffer a performance hit at larger magnitude and there is no much scope of improvement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T19:07:00.667", "Id": "18612", "Score": "0", "body": "Yes, that's exactly what it means. Sorry." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T09:48:51.473", "Id": "511891", "Score": "0", "body": "... and factorial growth is less then exponential growth ... like a certain Corona-Virus ..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T17:55:19.743", "Id": "11600", "ParentId": "11598", "Score": "11" } }, { "body": "<pre><code>private static void permute(char[] a, int n) {\n if (n == 1) {\n count++;\n System.out.println(a);\n return;\n }\n for (int i = 0; i &lt; n; i++) {\n swap(a, i, n-1);\n permute(a, n-1);\n swap(a, i, n-1);\n }\n}\n</code></pre>\n\n<p>This is an improved version which works using primitive data types so that memory used is in check.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-26T20:14:11.783", "Id": "33556", "Score": "1", "body": "This is much less useful than the original code. You want to return the results, not just write them to the console." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-26T19:03:04.587", "Id": "20941", "ParentId": "11598", "Score": "2" } } ]
{ "AcceptedAnswerId": "11600", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T17:35:53.820", "Id": "11598", "Score": "8", "Tags": [ "java", "algorithm", "combinatorics" ], "Title": "Permutations of a list of numbers" }
11598
<p>Suppose I have this code:</p> <pre><code>public interface BaseType { public void doSomething(); } public class ExtendedTypeA implements BaseType { //No Instance Variables @Override public void doSomething() { //really do something } } public class ExtendedTypeB implements BaseType { //No instance variables @Override public void doSomething() { //really do something, but different } } public enum BaseTypesValues { EXTENDED_TYPEA, EXTENDED_TYPEB } public BaseTypeFactoryStandard { public BaseType getBaseType(BaseTypesValues baseTypeValue) { switch(baseTypes) { case BaseTypesValues.EXTENDED_TYPEA: return new ExtendedTypeA(); case BaseTypesValues.EXTENDED_TYPEB: return new ExtendedTypeB(); default: throw new NoSuchTypeException(); } } } public BaseTypeFactoryMyWay { public static final Map&lt;BaseTypesValues, BaseType&gt; factoryMap = new HashMap&lt;//... static { factoryMap.put(BaseTypesValues.EXTENDED_TYPEA, new ExtendedTypeA()); factoryMap.put(BaseTypesValues.EXTENDED_TYPEB, new ExtendedTypeB()); } public BaseType getBaseType(BaseTypesValues baseTypeValue) { return factoryMap.get(baseTypeValue); } } </code></pre> <p>Is the last class a good/valid implementation of the factory pattern? Take into consideration the fact that classes that implement the BaseType DO NOT have a state (no non-final instance variables); this means that the objects are lightweight. </p> <p>Also, can it be implemented in this way (using a map) for the general case (in which classes have state). </p> <p>Or is this a dumb way in either cases?</p>
[]
[ { "body": "<p>Two things strike me:</p>\n\n<ul>\n<li>There's no need to have a separate factory class when you could put the functionality into the enum, unless you expect to have other factory implementations</li>\n<li>As you say, if the classes are stateless, there's no need to create a new instance on each call. (I've only just spotted your factory map class, which effectively does something like this, but there's no need to use a map.)</li>\n</ul>\n\n<p>Combining these:</p>\n\n<pre><code>public enum BaseTypesValues {\n EXTENDED_TYPEA(new ExtendedTypeA()),\n EXTENDED_TYPEB(new ExtendedTypeB());\n\n private final BaseType instance;\n\n private BaseTypesValues(BaseType instance) {\n this.instance = instance;\n }\n\n public BaseType getBaseType() {\n return instance;\n }\n}\n</code></pre>\n\n<p>Then to use:</p>\n\n<pre><code>BaseType type = EXTENDED_TYPEA.getBaseType();\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>public void doSomething(BaseTypesValue baseTypeValue) {\n baseTypeValue.getBaseType().someCallOnTheBaseType();\n}\n</code></pre>\n\n<p>EDIT: Note that here, if you want to introduce a new type which <em>isn't</em> stateless, it could override the <code>getBaseType</code> method:</p>\n\n<pre><code>EXTENDED_TYPEC(null) {\n @Override public BaseType getBaseType() {\n return new ExtendedTypeC();\n }\n};\n</code></pre>\n\n<p>Admittedly this would break code which <em>assumed</em> all implementations were stateless...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T14:51:43.423", "Id": "18613", "Score": "0", "body": "His implementation (`BaseFactoryMyWay`) actually has the property of not creating a new instance on each call." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T14:52:18.557", "Id": "18614", "Score": "0", "body": "@Romain: Yes, I'd missed that before. Have edited." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T14:52:24.660", "Id": "18615", "Score": "0", "body": "and if classes aren't stateless, it's very likely you can't just put one instance of them into a `Map` and return the same instance on each call." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T14:54:05.633", "Id": "18616", "Score": "0", "body": "I have provided the general/ideal case. The case in which I am actually working on actually depends on a String rather than an enum. Anyway, this implementation is really nice; thanks for it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T14:50:04.127", "Id": "11604", "ParentId": "11603", "Score": "11" } }, { "body": "<p>What you're doing is not a Factory anymore, some people call it a \"multiton\", it's a multi-instance variation around the singleton pattern.</p>\n\n<p>And yes, you're doing it right.</p>\n\n<p>That said, if you only have a single implementation, you don't need the factory at all. Like Jon Skeet mentions, you should move the behavior into the Enum.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T11:14:11.790", "Id": "69924", "Score": "0", "body": "In `BaseTypeFactoryMyWay`, yes, that's a multiton. But in the `BaseTypeFactoryStandard`, that's a factory. You don't make this distinction very clear in your answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T14:50:25.330", "Id": "11605", "ParentId": "11603", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T14:47:48.240", "Id": "11603", "Score": "9", "Tags": [ "java", "factory-method" ], "Title": "Is this a good implementation of the Factory Pattern?" }
11603
<p>I was wondering if there was any way I would be able to improve my HTML/CSS. Would you mind reviewing the following and telling me what I should do?</p> <p>CSS:</p> <pre><code>&lt;style type="text/css"&gt; body { font-family:Georgia, Palatino, Times, 'Times New Roman', serif; color:#333333; font-size:10px;} h1 { display:inline; color:#A8DBA8} h2 { display:inline; color:#333333; font-style:italic;} h3 { font-weight:bold; margin-bottom:5px;} li { list-style-type:none; margin:0; padding:0;} #portrait { margin-left:auto; margin-right:0px; margin-bottom:10px; -moz-border-radius: 64px; -webkit-border-radius: 64px; width: 64px; height: 64px; background-image:url({PortraitURL-64})} #container { margin-left:300px; margin-top:10px; width:500px;} #tags, #notes { margin-top:10px;} .sidebar { position:fixed; width:200px; margin-left:75px; margin-top:275px; text-align:right;} .sidebar #description { margin-bottom:10px;} .sidebar #navigation { margin-bottom:10px;} .entry { overflow:scroll; margin-bottom:10px;} .entry #tags { color:#CCCCCC;} .entry #quote_source { float:right;} .entry #audio { width:100%; height:100%; background-color:#000000;} #audio { width:500px; height:29px; background-color:#000000;} a:link, a:visited { color:#333333; text-decoration:none;} a:hover { color:#A8DBA8;} a.tag:link, a.tag:visited { color:#CCCCCC; text-decoration:none;} a.tag:hover { color:#CCCCCC text-decoration:underline;} &lt;/style&gt; </code></pre> <p>HTML:</p> <pre><code>&lt;div class="sidebar"&gt; &lt;div id="portrait"&gt;&lt;/div&gt; &lt;div id="description"&gt; &lt;h2&gt;"{Description}"&lt;/h2&gt; &lt;/div&gt; &lt;div id="navigation"&gt; &lt;a href="/"&gt;Home&lt;/a&gt; | &lt;a href="/about"&gt;About&lt;/a&gt; | &lt;a href="/ask"&gt;Message&lt;/a&gt; | &lt;a href="/archive"&gt;Archive&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="container"&gt; {block:Posts} {block:Text} &lt;div class="entry" id="text"&gt; {block:IndexPage} {/block:IndexPage} {block:Title} &lt;h3&gt;{Title}&lt;/h3&gt; {/block:Title} {Body} &lt;/div&gt; {/block:Text} {block:Photo} &lt;div class="entry" id="photo"&gt; {block:IndexPage} &lt;a href="{Permalink}"&gt;&lt;img src="{PhotoURL-500}"&gt;&lt;/a&gt; {/block:IndexPage} {block:PermalinkPage} &lt;a href="{LinkURL}"&gt;&lt;img src="{PhotoURL-500}"&gt;&lt;/a&gt; {block:HasTags} &lt;li id="tags"&gt; Tagged: {block:Tags} &lt;a href="{TagURL}" class="tag"&gt;{Tag}&lt;/a&gt; {/block:Tags} &lt;/li&gt; {/block:HasTags} {/block:PermalinkPage} &lt;/div&gt; {/block:Photo} {block:Photoset} &lt;div class="entry" id="photoset"&gt; {Photoset-500} &lt;/div&gt; {/block:Photoset} {block:Quote} &lt;div class="entry" id="quote"&gt; &lt;li id="quote_content"&gt; {Quote} &lt;/li&gt; &lt;li class="entry" id="quote_source"&gt; - {Source} &lt;/li&gt; &lt;/div&gt; {/block:Quote} {block:Link} &lt;div class="entry" id="link"&gt; &lt;li&gt;&lt;a href="{URL}" target="_blank"&gt;{Name} &amp;raquo;&lt;/a&gt; &lt;/ul&gt; {/block:Link} {block:Chat} &lt;div class="entry" id="chat"&gt; {block:Lines} {block:Label} {Label} {Line} &lt;br /&gt; {/block:Label} {/block:Lines} &lt;/div&gt; {/block:Chat} {block:Audio} &lt;div class="entry" id="audio"&gt; {AudioPlayerBlack} {block:PermalinkPage} &lt;div id="audio_description"&gt; {block:TrackName} {TrackName} {/block:TrackName} by {block:Artist} {Artist} {/block:Artist} &lt;/div&gt; {/block:PermalinkPage} &lt;/div&gt; {/block:Audio} {block:Video} &lt;div class="entry" id="video"&gt; {Video-500} &lt;/div&gt; {/block:Video} {block:Answer} &lt;div class="entry" id="answer"&gt; &lt;li id="answer_question"&gt; {Asker}: &amp;ldquo;{Question}&amp;rdquo; &lt;/li&gt; &lt;li id="answer_response"&gt; {Answer} &lt;/li&gt; &lt;/div&gt; {/block:Answer} {/block:Posts} &lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T03:46:38.897", "Id": "18628", "Score": "0", "body": "What are \"{block:IndexPage}\" type like things? I never seen them in html." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T11:48:59.530", "Id": "18636", "Score": "0", "body": "They're for a theme engine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-30T11:20:44.980", "Id": "22869", "Score": "0", "body": "@Matthew I posted my full detailed review for your tumblr theme" } ]
[ { "body": "<p>The first thing that really caught my eye is your usage of <code>margin-...</code>. If I am setting more than two sides of margin I like to use the syntax <code>margin: &lt;top&gt; &lt;right&gt; &lt;bottom&gt; &lt;left&gt;;</code> So this... </p>\n\n<pre><code>#portrait {\n margin-left:auto;\n margin-right:0px;\n margin-bottom:10px;\n -moz-border-radius: 64px; \n -webkit-border-radius: 64px; \n width: 64px;\n height: 64px; \n background-image:url({PortraitURL-64})}\n</code></pre>\n\n<p>becomes this...</p>\n\n<pre><code>#portrait {\n margin: auto 0px 10px auto;\n -moz-border-radius: 64px; \n -webkit-border-radius: 64px; \n width: 64px;\n height: 64px; \n background-image:url({PortraitURL-64})}\n</code></pre>\n\n<hr />\n\n<p>I noticed you are missing a semi-colon</p>\n\n<pre><code>a.tag:hover {\n color:#CCCCCC /* here */\n text-decoration:underline;}\n</code></pre>\n\n<hr />\n\n<p>According to the W3C Validation service, your HTML does not conform to the HTML 4.01 Strict Standard because of 13 errors... I'm not going to list them all here, but you can to <a href=\"http://validator.w3.org/check\" rel=\"nofollow\">http://validator.w3.org/check</a> and paste your HTML, select HTML 4.01 Strict, and view the results.</p>\n\n<hr />\n\n<p>Also... This isn't important, but I personally find the way you position your curly braces to be unusual. I usually only see one of the following syntax styles...</p>\n\n<pre><code>#portrait {\n margin: auto 0px 10px auto;\n width: 64px;\n height: 64px;\n}\n\n#portrait \n{\n margin: auto 0px 10px auto;\n width: 64px;\n height: 64px;\n}\n\n#port { margin:auto 0px 10px auto; width:64px; height:64px; }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T05:51:08.967", "Id": "18629", "Score": "0", "body": "Agree about the curly braces, but I think it is important. You'll find that out soon enough when you have a stray curly brace!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T02:27:37.310", "Id": "11609", "ParentId": "11607", "Score": "3" } }, { "body": "<p>+1 to @druciferre, but I'd keep the </p>\n\n<pre><code>#portrait {\n margin-left:auto;\n margin-right:0px;\n margin-bottom:10px;\n}\n</code></pre>\n\n<p>margin settings. It's easier to read (and modify) since readers don't have to memorize the top, right, bottom, left order.</p>\n\n<hr>\n\n<p>A common style about whitespace would improve the readability a little bit. Sometimes there is a space before the value, sometimes not.</p>\n\n<pre><code>width:200px;\n...\nwidth: 64px;\n</code></pre>\n\n<hr>\n\n<pre><code>&lt;a href=\"/\"&gt;Home&lt;/a&gt; |\n&lt;a href=\"/about\"&gt;About&lt;/a&gt; |\n&lt;a href=\"/ask\"&gt;Message&lt;/a&gt; |\n&lt;a href=\"/archive\"&gt;Archive&lt;/a&gt;\n</code></pre>\n\n<p>This could be an unordered list formatted by a proper CSS (as Drupal does, for example). \n<a href=\"https://stackoverflow.com/a/5622381/843804\">Why use list to do navigation menu instead of buttons?</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T20:44:10.337", "Id": "11633", "ParentId": "11607", "Score": "2" } }, { "body": "<p><em><strong>All links from the answer was included to the bottom.</em></strong></p>\n\n<hr>\n\n<h2>Small recommendations for <strong>CSS</strong>:</h2>\n\n<pre><code>/* space after colon required */\nbody {\n /* Georgia is more spread in OS than Palatino that's why browser will always select \n Georgia and never Palatino, that's why you must swapped these two fonts \n http://meiert.com/en/blog/20080220/helvetica-arial/ */\n font-family: Palatino, Georgia, Times, 'Times New Roman', serif;\n /* If you can use short syntax for color codes (#333333 = #333, #000000 = #000) */\n color: #333;\n font-size: 10px;\n}\n\n/* ‘Your selector’s intent must match that of your reason for styling something;\n ask yourself ‘am I selecting this\n because it’s a ul inside of .header or because it is my site’s main nav?’.’\n http://csswizardry.com/2012/07/shoot-to-kill-css-selector-intent/ */\nh1 {\n display: inline;\n color: #A8DBA8\n}\n\n/* color is unnessesary because is cascaded from body */\nh2 {\n display: inline;\n font-style: italic;\n}\n\n/* `font-weight: bold;` is unnessesary because it is default behaviour */\nh3 {\n margin-bottom: 5px;\n}\n\n/* drop default list-style from all lists on page is not very good idea,\n use `.nav` abstraction instead \n http://csswizardry.com/2011/09/the-nav-abstraction/ */\nli {\n /* in this situation `list-style-type` equal to `list-style` */\n list-style: none;\n margin: 0;\n padding: 0;\n}\n\n/* `moz` prefix can be dropped if only you are not support Firefox 3.6 \n http://hacks.mozilla.org/2010/09/firefox-4-recent-changes-in-firefox/ */\n#portrait {\n margin-left: auto;\n margin-right: 0;\n margin-bottom: 10px;\n /* use this smart syntax for vendor prefixes for better readability */\n -webkit-border-radius: 64px;\n border-radius: 64px;\n width: 64px;\n height: 64px;\n /* wrap url value in quotes for better syntax highlghting */\n background-image: url('{PortraitURL-64}');\n}\n\n/* use Top-Right-Bottom-Left rule to describe detailed properties\n also try not to use id for selectors\n http://csswizardry.com/2011/09/when-using-ids-can-be-a-pain-in-the-class/ */\n#container {\n margin-top: 10px;\n margin-left: 300px;\n width: 500px;\n}\n\n/* divide muilti-selectors to one selector on one line for better diffs in SVN or GIT */\n#tags,\n#notes {\n margin-top: 10px;\n}\n\n.sidebar {\n position: fixed;\n width: 200px;\n margin-left: 75px;\n margin-top: 275px;\n text-align: right;\n}\n\n/* selectors is overqualified \n and may be merged into one rule \n http://csswizardry.com/2011/09/writing-efficient-css-selectors/\n http://csswizardry.com/2012/07/quasi-qualified-css-selectors/ */\n#description,\n#navigation {\n margin-bottom: 10px;\n}\n\n.entry {\n overflow: scroll;\n margin-bottom: 10px;\n}\n\n/* selector is overqualified\n old code: .entry #tags */\n#tags {\n color: #CCC;\n}\n\n/* selector is overqualified\n old code: .entry #quote_source */\n#quote_source {\n float: right;\n}\n\n\n/* `#audio` and `.entry audio` may be swapped to delete repeated `background-color`\n `background-color` in this situation is equal to simple `background` */\n#audio {\n width: 500px;\n height: 29px;\n background-color: #000;\n}\n\n.entry #audio {\n width: 100%;\n height: 100%;\n}\n\n/* divide muilti-selectors to one selector on one line for better diffs in SVN or GIT */\na:link,\na:visited {\n color: #333;\n text-decoration: none;\n}\n\na:hover {\n color: #A8DBA8;\n}\n\n/* divide muilti-selectors to one selector on one line for better diffs in SVN or GIT */\na.tag:link,\na.tag:visited {\n color: #CCC;\n text-decoration: none;\n}\n\na.tag:hover {\n color: #CCC;\n text-decoration: underline;\n}\n</code></pre>\n\n<hr>\n\n<h2>Small recommendations for <strong>HTML</strong>:</h2>\n\n<h3><em>Title</em> code of block:</h3>\n\n<pre><code>{block:Title}\n &lt;h3&gt;{Title}&lt;/h3&gt;\n{/block:Title}\n</code></pre>\n\n<p><strong>Problems:</strong></p>\n\n<ul>\n<li>Post page has no <code>h1</code> with post's title.</li>\n</ul>\n\n<p><strong>Solution:</strong></p>\n\n<p><strong>HTML:</strong></p>\n\n<pre><code>&lt;!-- Tumblr post title non-minified description\n https://gist.github.com/2795206 --&gt;\n&lt;!-- snippet outputs `h2` on posts list pages and `h1` on single post pages --&gt;\n{block:Title}\n &lt;{block:IndexPage}h2{/block:IndexPage}{block:PermalinkPage}h1{/block:PermalinkPage} title=\"{Title}\" class=\"heading\"&gt;\n {block:IndexPage}&lt;a href=\"{Permalink}\" title=\"{Title}\" class=\"heading\"&gt;{/block:IndexPage}\n {Title}\n {block:IndexPage}&lt;/a&gt;{/block:IndexPage}\n &lt;/{block:PermalinkPage}h1{/block:PermalinkPage}{block:IndexPage}h2{/block:IndexPage}&gt;\n{/block:Title}\n</code></pre>\n\n<hr>\n\n<h3><em><code>#navigation</code></em> code of block:</h3>\n\n<pre><code>&lt;div id=\"navigation\"&gt;\n &lt;a href=\"/\"&gt;Home&lt;/a&gt; |\n &lt;a href=\"/about\"&gt;About&lt;/a&gt; |\n &lt;a href=\"/ask\"&gt;Message&lt;/a&gt; |\n &lt;a href=\"/archive\"&gt;Archive&lt;/a&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><strong>Problems:</strong></p>\n\n<ul>\n<li>Not use <code>|</code> symbols just for design, you can reproduce this visual elements with this CSS and HTML;</li>\n<li>Unordered list is more semantical, accessible and seo-optimized alternative for your variant of menu;</li>\n<li>Use <code>.nav</code> abstraction for reset <code>margin</code>,<code>padding</code> and <code>list-style</code>.</li>\n</ul>\n\n<p><strong>Solution <a href=\"http://dabblet.com/gist/3156899\" rel=\"nofollow\"><em>(demo on dabblet)</em></a>:</strong></p>\n\n<p><strong>HTML:</strong></p>\n\n<pre><code>&lt;ul id=\"navigation\" class=\"nav\"&gt;\n &lt;li&gt;\n &lt;a href=\"/\"&gt;Home&lt;/a&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a href=\"/about\"&gt;About&lt;/a&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a href=\"/ask\"&gt;Message&lt;/a&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a href=\"/archive\"&gt;Archive&lt;/a&gt;\n &lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p><strong>CSS:</strong></p>\n\n<pre><code>.nav {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n\n#navigation {\n overflow: hidden; /* clear float */\n}\n\n#navigation li {\n float: left;\n padding: 0 10px;\n}\n\n#navigation li + li {\n border-left: 1px solid gray;\n}\n</code></pre>\n\n<hr>\n\n<h3><em>Tags</em> code of block:</h3>\n\n<pre><code>{block:HasTags}\n&lt;li id=\"tags\"&gt;\nTagged: \n {block:Tags}\n &lt;a href=\"{TagURL}\" class=\"tag\"&gt;{Tag}&lt;/a&gt;\n {/block:Tags}\n&lt;/li&gt;\n{/block:HasTags}\n</code></pre>\n\n<p><strong>Problems:</strong></p>\n\n<ul>\n<li>There are not <code>ul</code> wrapper;</li>\n<li><code>#tags</code> blocks existed for each post, so you will have duplicating <code>id</code>'s.</li>\n</ul>\n\n<p><strong>Solution:</strong></p>\n\n<p><strong>HTML:</strong></p>\n\n<pre><code>{block:HasTags}\n&lt;div class=\"tags\"&gt;\nTagged: \n &lt;ul&gt;\n {block:Tags}\n &lt;li&gt;\n &lt;a href=\"{TagURL}\" class=\"tag\"&gt;{Tag}&lt;/a&gt;\n &lt;/li&gt;\n {/block:Tags}\n &lt;/ul&gt;\n&lt;/div&gt;\n{/block:HasTags}\n</code></pre>\n\n<hr>\n\n<h3><em><code>{PostType}</code></em> code of block:</h3>\n\n<pre><code>&lt;div class=\"entry\" id=\"text\"&gt; …\n&lt;div class=\"entry\" id=\"photo\"&gt; …\n&lt;div class=\"entry\" id=\"photoset\"&gt; …\n/* and others */\n</code></pre>\n\n<p><strong>Problems:</strong></p>\n\n<ul>\n<li><code>#text</code> blocks existed for each text post-type, so you will have duplicating <code>id</code>'s;</li>\n<li>If you are using tumblr engine you can use simple <code>{PostType}</code>.</li>\n</ul>\n\n<p><strong>Solution:</strong></p>\n\n<p><strong>HTML:</strong></p>\n\n<pre><code>&lt;div class=\"entry text\"&gt; …\n&lt;div class=\"entry photo\"&gt; …\n&lt;div class=\"entry photoset\"&gt; …\n\n/* or if Tumblr */ \n&lt;div class=\"entry {PostType}\"&gt; …\n</code></pre>\n\n<hr>\n\n<h3><em>Quote</em> code of block:</h3>\n\n<pre><code>{block:Quote}\n &lt;div class=\"entry\" id=\"quote\"&gt;\n &lt;li id=\"quote_content\"&gt;\n {Quote}\n &lt;/li&gt;\n &lt;li class=\"entry\" id=\"quote_source\"&gt;\n - {Source}\n &lt;/li&gt;\n &lt;/div&gt;\n{/block:Quote}\n</code></pre>\n\n<p><strong>Problems:</strong></p>\n\n<ul>\n<li>There are not ul wrapper;</li>\n<li>Use special, semantical <code>blockquote</code> element for quotes instead <code>ul</code> element;</li>\n<li>Duplicating <code>id</code>’s.</li>\n</ul>\n\n<p><strong>Solution:</strong></p>\n\n<p><strong>HTML:</strong></p>\n\n<pre><code>{block:Quote}\n &lt;div class=\"entry {PostType}\"&gt;\n &lt;blockquote class=\"quote_content\"&gt;\n {Quote}\n &lt;/blockquote&gt;\n &lt;p class=\"quote_source\"&gt;\n - {Source}\n &lt;/p&gt;\n &lt;/div&gt;\n{/block:Quote}\n</code></pre>\n\n<hr>\n\n<h3><em>Link</em> code of block:</h3>\n\n<pre><code>{block:Link}\n&lt;div class=\"entry\" id=\"link\"&gt;\n &lt;li&gt;&lt;a href=\"{URL}\" target=\"_blank\"&gt;{Name} &amp;raquo;&lt;/a&gt;\n &lt;/ul&gt;\n{/block:Link}\n</code></pre>\n\n<p><strong>Problems:</strong></p>\n\n<ul>\n<li>There is no end of <code>div</code> wrapper;</li>\n<li>There is no <code>ul</code> wrapper for <code>li</code> elements;</li>\n<li>Duplicating <code>id</code>’s problem;</li>\n<li>Leaked SEO PR states — use <code>rel=\"nofollow\"</code> solution;</li>\n<li>Non­-semantical additional symbols, use css generated content instead;</li>\n<li><code>target=\"_blank\"</code> is depricated construction — give your user choice in which tab to open your pages.</li>\n</ul>\n\n<p><strong>Solution:</strong></p>\n\n<p><strong>HTML:</strong></p>\n\n<pre><code>{block:Link}\n&lt;div class=\"entry {PostType}\"&gt;\n &lt;a href=\"{URL}\" rel=\"nofollow\"&gt;{Name} &lt;/a&gt;\n&lt;/div&gt;\n{/block:Link}\n</code></pre>\n\n<p><strong>CSS:</strong></p>\n\n<pre><code>.entry.link a:after {\n content: '&amp;raquo;';\n}\n</code></pre>\n\n<hr>\n\n<h3><em>Chat</em> code of block:</h3>\n\n<pre><code>{block:Chat}\n &lt;div class=\"entry\" id=\"chat\"&gt;\n {block:Lines}\n {block:Label}\n {Label} {Line} &lt;br /&gt;\n {/block:Label}\n {/block:Lines}\n &lt;/div&gt;\n{/block:Chat}\n</code></pre>\n\n<p><strong>Problems:</strong></p>\n\n<ul>\n<li>Never use <code>&lt;br /&gt;</code> element for markup, it exist only for text;</li>\n<li>Duplicating <code>id</code>’s problem;</li>\n<li>Situation for using <code>ul</code> element.</li>\n</ul>\n\n<p><strong>Solution:</strong></p>\n\n<p><strong>HTML:</strong></p>\n\n<pre><code>{block:Chat}\n &lt;div class=\"entry {PostType}\"&gt;\n {block:Lines}\n &lt;ul&gt;\n {block:Label}\n &lt;li&gt;\n {Label} {Line}\n &lt;/li&gt;\n {/block:Label}\n &lt;/ul&gt;\n {/block:Lines}\n &lt;/div&gt;\n{/block:Chat}\n</code></pre>\n\n<hr>\n\n<h3>Links from answer and some additionals</h3>\n\n<h3>CSS Links:</h3>\n\n<ul>\n<li><a href=\"http://meiert.com/en/blog/20080220/helvetica-arial/\" rel=\"nofollow\">“helvetica, arial”, Not “arial, helvetica”</a> </li>\n<li><a href=\"http://csswizardry.com/2012/07/shoot-to-kill-css-selector-intent/\" rel=\"nofollow\">Shoot to kill; CSS selector intent</a></li>\n<li><a href=\"http://hacks.mozilla.org/2010/09/firefox-4-recent-changes-in-firefox/\" rel=\"nofollow\">Firefox 4: recent changes in Firefox</a></li>\n<li><a href=\"http://csswizardry.com/2011/09/the-nav-abstraction/\" rel=\"nofollow\">The ‘nav’ abstraction</a></li>\n<li><a href=\"http://csswizardry.com/2011/09/when-using-ids-can-be-a-pain-in-the-class/\" rel=\"nofollow\">When using IDs can be a pain in the class…</a></li>\n<li><a href=\"http://csswizardry.com/2011/09/writing-efficient-css-selectors/\" rel=\"nofollow\">Writing efficient CSS selectors</a> </li>\n<li><a href=\"http://csswizardry.com/2012/07/quasi-qualified-css-selectors/\" rel=\"nofollow\">Quasi-qualified CSS selectors</a> </li>\n<li><a href=\"http://coding.smashingmagazine.com/2007/05/10/70-expert-ideas-for-better-css-coding/\" rel=\"nofollow\">70 Expert Ideas For Better CSS Coding</a> <em>(not all ideas are ideal but some of them is quite usefull)</em></li>\n</ul>\n\n<h3>HTML links:</h3>\n\n<ul>\n<li><a href=\"http://coding.smashingmagazine.com/2011/11/18/html5-semantics/\" rel=\"nofollow\">HTML5 Semantics</a></li>\n</ul>\n\n<h3>Tumblr links:</h3>\n\n<ul>\n<li><a href=\"http://www.tumblr.com/docs/en/custom_themes\" rel=\"nofollow\">How to create a custom HTML theme</a></li>\n<li><a href=\"http://disattention.com/labs/tumblr/theme-guide/\" rel=\"nofollow\">Unofficial Theme Guide</a> </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T15:58:03.280", "Id": "48727", "Score": "0", "body": "unofficial guide is unavailable by direct link now, so check it in wayback machine http://web.archive.org/web/20121021062653/http://disattention.com/labs/tumblr/theme-guide/" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-21T20:53:14.573", "Id": "13893", "ParentId": "11607", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T00:56:00.357", "Id": "11607", "Score": "2", "Tags": [ "html", "css" ], "Title": "HTML and CSS for a theme engine" }
11607
<p>I am a 3rd-year computer science undergraduate. One of my university lecturers has developed his own page for students to submit work. It came up that one student was accused of hacking (sic) by the system. The problem was the characters used in the comment field.</p> <p>The lecturer claimed that he needed to filter out certain characters in order to stop attacks, and that it was a known problem with PHP. (His system had been broken by students before). I am suspecting poor programming, as he claims that the strings are being executed by PHP.</p> <p>He told me to try writing a PHP program with a form text field, then input PHP code into the text form. He expects that there to be a vulnerability without filtering the input for bad chars.</p> <pre><code>&lt;?php if(isset($_POST['data']) ){ if( file_exists("../post.sqlite") ){ $db = new SQLite3("../post.sqlite"); if( isset($_POST['password']) &amp;&amp; $_POST['password'] === "correct horse battery staple" ){ $statement = $db-&gt;prepare("INSERT INTO posts( id, post ) VALUES ( NULL, ? )"); $statement-&gt;bindValue(1, $_POST['data'], SQLITE3_TEXT); $statement-&gt;execute(); } } else { $db = new SQLite3("../post.sqlite"); $db-&gt;exec("CREATE TABLE posts( id INTEGER PRIMARY KEY, post TEXT )"); } } function posts(){ if( file_exists("../post.sqlite") ){ $db = new SQLite3("../post.sqlite"); $query = $db-&gt;query("SELECT post from posts ORDER BY id DESC"); while( $row = $query-&gt;fetchArray(SQLITE3_ASSOC)){ print( "&lt;pre&gt;" ); print( htmlentities( $row['post'] ) ); print( "&lt;/pre&gt;&lt;hr /&gt;" ); } } } ?&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt;&lt;title&gt;Try This&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;form action="post.php" method="post"&gt; &lt;textarea rows="10" cols="80" name="data"&gt;&lt;/textarea&gt;&lt;br /&gt; &lt;input type="submit" value="Post" /&gt;&lt;br /&gt; Secret key: &lt;input type="text" name="password" /&gt; &lt;/form&gt; &lt;hr /&gt; &lt;div id="posts"&gt; &lt;?php posts(); ?&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Without the <code>htmlentities</code> function, I know it would have client side vulnerabilities (running malicious scripts). SQL injection is covered (prepared statements). I don't see how the program can be exploited server side. What (if anything) am I missing?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T13:20:15.340", "Id": "18646", "Score": "0", "body": "Not going to leave an actual answer because I've not done enough research in security to make any answer of mine educated enough. However, I am concerned about your passing any sort of POST data directly to your program, not to be confused with `$_POST['data']` though that is the main concern here. If you have PHP version >= 5.2 check out [`filter_input()`](http://php.net/manual/en/function.filter-input.php)" } ]
[ { "body": "<p>It seems fine for me.</p>\n\n<p>Some small changes:</p>\n\n<ol>\n<li><p>I'd change the action to </p>\n\n<pre><code>&lt;form action=\"&lt;?php echo htmlentities($_SERVER['PHP_SELF']); ?&gt;\" method=\"post\"&gt;\n</code></pre>\n\n<p><a href=\"http://www.html-form-guide.com/php-form/php-form-action-self.html\" rel=\"nofollow noreferrer\">Using PHP_SELF in the action field of a form</a></p></li>\n<li><p>I'd consider storing escaped data in the database instead of escaping them on every page requests for performance reasons if the page has lots of visitors.</p></li>\n<li><p><code>\"../post.sqlite\"</code> should be a constant.</p></li>\n<li><p>I'd reorganize the code a little bit to use only one <code>SQLite3</code> instance:</p>\n\n<pre><code>define(\"DB_FILE\", \"../post.sqlite\");\n\n$dbExists = file_exists(DB_FILE);\n$db = new SQLite3(DB_FILE);\nif (!$dbExists) {\n $db-&gt;exec(\"CREATE TABLE posts( id INTEGER PRIMARY KEY, post TEXT )\");\n}\n\nif (isset($_POST['data'])) {\n if( isset($_POST['password']) &amp;&amp; $_POST['password'] === \"correct horse battery staple\" ){\n $statement = $db-&gt;prepare(\"INSERT INTO posts( id, post ) VALUES ( NULL, ? )\");\n $statement-&gt;bindValue(1, $_POST['data'], SQLITE3_TEXT);\n $statement-&gt;execute();\n }\n}\n\nfunction posts($db) {\n $query = $db-&gt;query(\"SELECT post FROM posts ORDER BY id DESC\");\n\n while ($row = $query-&gt;fetchArray(SQLITE3_ASSOC)) {\n print( \"&lt;pre&gt;\" );\n print( htmlentities( $row['post'] ) );\n print( \"&lt;/pre&gt;&lt;hr /&gt;\" );\n }\n}\n\n?&gt;\n[...]\n\n &lt;?php posts($db); ?&gt;\n[...]\n\n&lt;?php\n $db-&gt;close();\n?&gt;\n</code></pre>\n\n<p>It may be worth creating the table with <code>IF NOT EXISTS</code> in every execution instead of the <code>file_exists</code> check for simplicity: <a href=\"https://stackoverflow.com/questions/3716443/creating-an-sqlite-table-only-if-it-doesnt-already-exist\">Creating an SQLite table only if it doesn't already exist</a></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-05T21:26:40.140", "Id": "75354", "Score": "0", "body": "Using `$_SERVER['SCRIPT_NAME']` instead of `PHP_SELF` is safer as it won't pass the extended path info." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T22:43:55.667", "Id": "11640", "ParentId": "11610", "Score": "6" } }, { "body": "<p>My two cents: </p>\n\n<p>As you said, from a security point of view your script looks OK, as it's defended from SQLi and XSS.</p>\n\n<p>You should, however, check all other scripts in your application, or other scripts that access the same database (if any). </p>\n\n<p>That's because the application could still be vulnerable to <a href=\"http://www.technicalinfo.net/papers/SecondOrderCodeInjection.html\" rel=\"nofollow\">Second Order Injection</a>, if someone else wrote another script that:</p>\n\n<ul>\n<li>uses the data in your table using non-parameterized queries (unlikely in your case, but worth mentioning)</li>\n<li>displays the data from your table without using <code>htmlentities</code> or another proper encoding mechanism</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T12:28:50.477", "Id": "11658", "ParentId": "11610", "Score": "2" } } ]
{ "AcceptedAnswerId": "11640", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T04:21:34.680", "Id": "11610", "Score": "5", "Tags": [ "php", "sql", "security" ], "Title": "Testing filtering of certain characters" }
11610
<p>I'm using Selenium to test a PHP site that goes through the following process:</p> <ol> <li>Register user</li> <li>Log in</li> <li>Fill out Form 1 and submit</li> <li>Fill out Form 2 and submit</li> <li>Fill out Form 3 and submit</li> <li>(tear down) Delete user</li> </ol> <p>A real user would go through these steps in this order.</p> <p>I've read in places that tests should be bite-sized, and to avoid asserting a lot of things in each test. So I've written my tests like this:</p> <pre><code>function testRegister() { //... } /** * @depends testRegister */ function testLogin() { //... } /** * @depends testLogin */ function testFillForm1() { //... } /** * @depends testFillForm1 */ function testFillForm2() { //... } /** * @depends testFillForm2 */ function testFillForm3() { //... } </code></pre> <p>This way my tests execute in the correct order.</p> <p>However, splitting up my tests is merely cosmetic. Since each test is dependent on the success of the previous one, it may as well be one long test.</p> <p>It also causes another problem. If <code>testFillForm2</code> fails, I have no way of re-running the test on its own, I have to wait for all the other tests to complete each time because of the dependencies.</p> <p>Is there a better approach I can take?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T07:54:58.150", "Id": "18726", "Score": "2", "body": "The \"bite sized tests\" remark is certainly true for unit tests (which test a single chunk of code in isolation), but I don't think it's necessarially so for a functional test (which tests several components at once to make sure they interact as intended)." } ]
[ { "body": "<h2>@depends does not define order</h2>\n\n<blockquote>\n <p>[@depends] do not define the order in which the test methods are to be executed</p>\n</blockquote>\n\n<p>Using <a href=\"http://www.phpunit.de/manual/3.6/en/writing-tests-for-phpunit.html\" rel=\"nofollow\">@depends</a> and not returning/passing arguments is an indicator that @depends isn't appropriate for what you're currently doing. You need to have a consistent application state before running each individual test method so that they do <em>not</em> depend on execution order. Otherwise tests easily become quite unwieldy and ultimately of little value.</p>\n\n<p>If you want to do that via @depends, you need to return from a test method and the following method should expect it as the first argument (and literally depend on whatever it receives).</p>\n\n<h2>Reduce dependencies</h2>\n\n<p>In tests you should aim to reduce, not add dependencies, otherwise you can be in quite a fragile position. If for example your register function breaks, it wouldn't affect existing users, or therefore all other tests, at all - but using cascading tests as shown you would be unable to test/demonstrate that. </p>\n\n<p>A broken register function would certainly be a problem - but is it a \"100% of the site is broken\" problem? It makes test results un-representative, and potentially harder to identify the root cause. If you have one failing test - it's very obvious where to focus your attention just from the test results. If all tests fail, it is not.</p>\n\n<p>Of course anything more than of 0% fails warrants developer attention.</p>\n\n<h2>Achieve consistent application state</h2>\n\n<p>So, for example, each test should:</p>\n\n<ul>\n<li>Establish a consistent application state (setUp functionality)</li>\n<li>Use the concept of <a href=\"http://www.phpunit.de/manual/3.6/en/fixtures.html\" rel=\"nofollow\">fixtures</a> to e.g. populate the session, cookies, db - whatever is required</li>\n<li>test what it needs to test</li>\n<li>cleanup after itself (tearDown functionality)</li>\n</ul>\n\n<p>In Context, I would say that means:</p>\n\n<p>Create a test user to be able to test logging in without first being forced in the test case to \"test\" your register function:</p>\n\n<pre><code>public funtion testLogin() {\n // Insert a user directly into the users table - simulate anything else from testRegister\n ...\n $this-&gt;assertSame(\"UserName\", $_SESSION['user']['name']);\n}\n</code></pre>\n\n<p>You setup the session/cookie/whatever state for each subsequent test so that you don't need to \"test\" your login function to be able to test other authorized functions:</p>\n\n<pre><code>public funtion testFillForm1() {\n $this-&gt;_login();\n ...\n}\n\npublic funtion testFillForm2() {\n $this-&gt;_login();\n ...\n}\n\npublic funtion testFillForm3() {\n $this-&gt;_login();\n ...\n}\n\nprotected function _login($user = array()) {\n if (!$user) {\n $user = array('name' =&gt; 'Default');\n }\n $_SESSION['user'] = $user;\n}\n</code></pre>\n\n<p>If any of your setup steps are generic enough to apply to all tests, put them in the <code>setUp</code> function. E.g. loading 10 test users, with various permissions - put that in setUp and therefore testing login, registration-\"that username already exists\" would need no in-test setup at all.</p>\n\n<p>I'm not exactly sure how that applies to using selenium, but hopefully this gives you enough of a hint to remove some of your inter-test dependencies.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T17:22:10.553", "Id": "18772", "Score": "0", "body": "Isn't inserting a user manually into the database before the test a bit dodgy? I can't guarantee that the app would be in the same state as if I went through the actual login/registration process in Selenium (particularly as it's built on a CMS and versions might change)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T07:46:55.050", "Id": "18882", "Score": "1", "body": "If, as is now apparent, it's code that you need to treat as a black box - depends. You really, really don't want false test dependencies. E.g. what if the register functionality changed but was not broken _and_ it took a week to figure out how to test it. You'd be completely blind to other test failures for a week. Inserting a user into the db was merely a hint - do whatever you need to have a consistent application state. Insert into the db, delete stuff, restore a db dump - just put yourself in the position to reduce your test dependencies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T07:51:54.250", "Id": "18883", "Score": "1", "body": "As an example: On a long-past project I would restore the whole disk image to have a consistent state before running the test suite (on another machine) because the application made changes all over the machine - db, windows registry, tmp files etc. But here you're talking about a typical php app - that's certainly not necessary. The principle is the same though: achieve a consistent application state." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T08:27:33.580", "Id": "11613", "ParentId": "11611", "Score": "3" } } ]
{ "AcceptedAnswerId": "11613", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T05:40:04.953", "Id": "11611", "Score": "2", "Tags": [ "php" ], "Title": "Functional testing issue - Feels like one long test" }
11611
<p>I am using PHP to get data from a MySQL database, and use the data to drop multiple markers into Google Maps. Please give me some suggestions for my code.</p> <pre><code>&lt;?php require_once 'Common/system_start.php'; $sql="select * from tab_mem order by sn desc "; $result= mysql_query($sql); $data=mysql_fetch_assoc($result); $row=mysql_num_rows($result); header("Content-type: text/xml"); // Iterate through the rows, adding XML nodes for each while ($row = @mysql_fetch_assoc($result)){ // ADD TO XML DOCUMENT NODE $node = $dom-&gt;createElement("marker"); $newnode = $parnode-&gt;appendChild($node); $newnode-&gt;setAttribute("address", $row['address']); } echo $dom-&gt;saveXML(); ?&gt; </code></pre> <h3>HTML5</h3> <pre><code> &lt;script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var map; var geocoder; //initial GPS navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 }); function onSuccess(position){ //get GPS latlong var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); // display map var gmap = new google.maps.Map( map_div, { zoom:16, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }); //drop the marker function drop() { for (var i = 0; i &lt; a; i++) { setTimeout(function() { addMarker(); }, i * 200); } } //decode address to latlng //pass address data from PHP while (markers.length){ var address=""; geocoder=new google.maps.Geocoder(); alert("..."); } geocoder.geocode({'address':address},function(results,status){ if(status==google.maps.GeocoderStatus.OK){ function addMarker() { markers.push(new google.maps.Marker({ postion:results().geometry.location, map:gmap, animation:google.map.animation.DROP })); } // Sets the map on all markers in the array. // function setAllMap(map) { // for (var i = 0; i &lt; markers.length; i++) { // markers[i].setMap(map); //} // } //markerNearBy.setMap(map); }else{ alert("Geocode was not sucessful for the following reason:"+status); } }); } } function onError(error) { alert('code: '+ error.code+ '\n' +'message: ' + error.message + '\n'); } &lt;/script&gt; &lt;/head&gt; &lt;body onLoad="load()"&gt; &lt;!-- map display here--&gt; &lt;div id="map_div""&gt;&lt;/div&gt; </code></pre> <p> </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T08:51:35.737", "Id": "18631", "Score": "2", "body": "fixing the whitespace so it's a little easier to read would help" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T13:56:36.713", "Id": "18650", "Score": "0", "body": "Completely agree, its sooo hard to read XD" } ]
[ { "body": "<p><strong>PHP</strong></p>\n\n<p>The commonly accepted approach to SQL statements is to make commands all caps, so I would convert my SQL statements to look like so...</p>\n\n<pre><code>$sql=\"SELECT * FROM tab_mem ORDER BY sn DESC \";\n</code></pre>\n\n<p>In other words, only the information from your tables should be lower case. This makes it easier to read.</p>\n\n<p>You really should <strong>never</strong> use error suppression. Sure if it isn't a fatal error its nice to ignore those errors and let the program continue running, but you should never, no matter how minor, let an error go unresolved. It doesn't help your program and could potentially cause more problems rather than less.</p>\n\n<p>You just declared <code>$data</code> and <code>$row</code> then turn around name a new <code>$row</code> that you just set <code>$data</code> to, never having used the old ones. Why? If you aren't going to use that information, don't set it. I'd just remove the <code>$data</code> and first <code>$row</code> variables. This is one of the few times I think its ok to set variables in an expression, otherwise I'd point this out too.</p>\n\n<p>Don't know if it is just stackoverflow messing with your code or not, but ensure that your code is indented! If it is you can ignore this line, but judging from later bits of code, I have to assume that its not just stackoverflow. Examples given in JavaScript section.</p>\n\n<p>Where in the world did <code>$dom</code> and <code>$parnode</code> come from? Does this even work?</p>\n\n<p><strong>JavaScript</strong></p>\n\n<p>I'll admit to not being well versed in JavaScript myself, only enough to write minor scripts for myself. However a lot of what I know from PHP can be trasferred over to JavaScript, and my first problem here is that you have JavaScript functions within your JavaScript functions. Move those! I can't imagine when that would be necessary. All functions should be within the same scope. Minor exceptions would be lamda functions, though I hold that if you can make it into a function to be reused, do so.</p>\n\n<p>Your code indentation here is really lacking. If I did not have a text editor with matching-brace highlighting there is no way in the world I could read this. An I'm still having trouble anyways. Here's a couple of examples of good indentation:</p>\n\n<pre><code>var gmap = new google.maps.Map(\n map_div, {\n zoom:16,\n center: latlng,\n mapTypeId: google.maps.MapTypeId.ROADMAP\n }\n);\n//etc...\nwhile (markers.length){\n var address=\"\";\n geocoder=new google.maps.Geocoder();\n alert(\"...\");\n}\n</code></pre>\n\n<p>Proper indentation would also show you that you have an extra closing brace <code>}</code> on the end of your <code>onSuccess()</code> function. Which probably causes errors.</p>\n\n<p>I'm going to stop here. I've already pointed out quite a bit for you to look at. If after you have corrected these things you want me to look over it again you can update your question with the new code and drop me a comment and I'll try to come back to it. Good Luck!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T13:56:15.917", "Id": "11619", "ParentId": "11612", "Score": "1" } }, { "body": "<p>+1 to @showerhead, and:</p>\n\n<ol>\n<li><p>I would use longer table and attribute names than <code>tab_mem</code> and <code>sn</code>. Longer names would make the code more readable since readers don't have to decode the abbreviations every time.</p></li>\n<li><p>I'd check the result of <code>mysql_query($sql)</code>. It returns <code>FALSE</code> on error. The code could write an error message and a proper HTTP error code (<code>500 Internal Server Error</code>, for example) to the user and could stop the execution of the script. I think there is no point to continue the execution.</p></li>\n<li><p><code>header(\"Content-type: text/xml\")</code> should be at the beginning of the script. Previous error messages or notices could cause a <code>Warning: Cannot modify header information - headers already sent</code> error message here. See: <a href=\"https://stackoverflow.com/a/8028987/843804\">Headers already sent by PHP</a></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T20:01:14.577", "Id": "18670", "Score": "1", "body": "@ShuyouChang: I actually meant to touch on that #1 but got sidetracked. I would just add that should also include variable names. `$parnode` while obvious if you sat down to think about it, should probably still be expanded to `$parentnode` or if you want to keep it short then just `$parent`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T20:13:23.540", "Id": "18672", "Score": "0", "body": "@showerhead: Or it could be `$parentNode`. Camelcase is easy to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T20:22:01.977", "Id": "18673", "Score": "1", "body": "I guess my finger missed the shift key, cause I could have sworn I capped that, but good point!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T19:23:30.607", "Id": "11630", "ParentId": "11612", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T08:02:28.817", "Id": "11612", "Score": "1", "Tags": [ "php", "beginner", "html5", "google-apps-script", "google-maps" ], "Title": "Markers on Google Maps" }
11612
<p>I am looking for ways to enhance this function in C++. </p> <p>The function gets a date and returns the total number of seconds since the epoch (01/01/1970).</p> <p>Do you have any suggestion regarding the algorithm, the code style, etc ?</p> <p>Note: I use this function instead of the standard library functions because it can handle negative dates and dates before 1900.</p> <pre><code>static int NDaysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; double getUnixTimeStamp(int y, int m, int d, int h, int mn, int s) { // Begin bounds checking if (y &lt; 0 || m &lt; 1 || d &lt; 1 || h &lt; 0 || mn &lt; 0 || s &lt; 0) return -1; // End bounds checking int ye = 1970; //UNIX epoch 01/01/1970 int sign = y &gt; ye ? 1 : -1; int maxY = std::max(y, ye); int minY = std::min(y, ye); int nleapYears = 0; for (int i = minY; i &lt; maxY; i++) if ((i % 100 != 0 &amp;&amp; i % 4 == 0) || i % 400 == 0) nleapYears++; if (m &gt; 2) if ((y % 100 != 0 &amp;&amp; y % 4 == 0) || y % 400 == 0) nleapYears += sign; nleapYears = std::max(0, nleapYears); double monthsNDays = 0; for (int i = 1; i &lt; m; i++) monthsNDays += NDaysInMonth[i - 1]; return ((y - ye) * 365 + sign * nleapYears + monthsNDays + d - 1) * 86400 + h * 3600 + mn * 60 + s; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T18:07:19.157", "Id": "18661", "Score": "1", "body": "Its a leap year if divisible by 400. Thus 1900 is not but 2000 was a leap year." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T18:10:45.440", "Id": "18662", "Score": "0", "body": "If you are before 1970 then monthsNDays is wrong (as you will be counting backwards from Dec-31)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T18:11:15.410", "Id": "18663", "Score": "0", "body": "You forget to check if this year is a leap year (and only apply it after Feb-29)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T18:11:27.000", "Id": "18664", "Score": "0", "body": "What about leap seconds. There have been 25 since 1970." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T18:13:35.873", "Id": "18665", "Score": "0", "body": "Why is (y < 0) special? What about bounds checking at the high end ( m > 12)? Don't forget s usually has bounds (s > 60) but sometime is (s > 61)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T18:15:56.590", "Id": "18666", "Score": "0", "body": "If y < 1970 and a leap year you automatically count it. Even if you have not passed Feb-29" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T18:19:37.613", "Id": "18667", "Score": "1", "body": "Have you looked at: `mktime()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T00:04:03.020", "Id": "18680", "Score": "0", "body": "@S Hubble: Undelete your post. Its worth an upvote." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T13:50:10.300", "Id": "18703", "Score": "0", "body": "@LokiAstari Thanks for the suggestions. I have updated the code. Yes I looked at mktime() but it's unable to handle years before 1900." } ]
[ { "body": "<p>Edit: I very wrongly accused Jacobi of posting a flawed algorithm. So I removed my ranting and replaced by:</p>\n\n<p>I had a try compiling your code and I worked on it to represent how I would have written it. See below. I hope this gives you hints about a different possible coding style. I hope to demonstrate some benefits. The main differences are:</p>\n\n<ul>\n<li>Comment for readability. In six months you might be very much in doubt yourself of all the intricacies of an algorithm. I had a hard time deciphering your algorithm. I am also in favor of including references to the definitions of formulas etc, which allows reviewers to check them more quickly.</li>\n<li>A good practice that I still don't manage to discipline myself to is to write commenting immediately for doxygen or another doc generator, so you can save yourself the hassle later. It usually forces you to document all parameters, return values, ... which is good practice anyway.</li>\n<li>Code formatting to represent the structure of the code. I am a big fan of lots of spacing and horizontal alignment to spot the difference between similar lines easily.</li>\n<li>I would refactor to avoid repeating the same code twice, even in the case of isLeapYear. I think the algorithm also becomes more readable when you change the condition by a clear function name. For reading how the algorithm works, I actually don't care about the implementation of the leapyear test.</li>\n<li>Instead of testing for <code>m &lt; 2</code> to add or remove extra leapyears, I think it is beneficial to try and represent the reality in your code. I do this here by creating <code>N_DAYS_IN_LEAP_MONTH</code>. This benefits not only in simplifying the code, it also serves in multiple places, as now the input validation is more correct as well.</li>\n<li>Returning -1 on error is misleading because it could also be a valid outcome. I would propose in any case to return 0 on error instead of -1, so it can be distinguished from valid output with a Boolean test as <code>if( x = getUnixTimeStamp(...) ) -&gt; valid</code>. If you want to garantee no ambiguity, you should probably return a struct with an error status, an error message and a result.</li>\n<li>Personally I prefer longer variable names for clarity, but I suppose that has to do with taste. I also changed nleapyears to nleapdays, which corresponds more to what is is.</li>\n<li>I try to use const where I can. In this example it is a bit trivial, and compilers would probably compile it to the exact same assembler code without these consts, so you have to see if you find it worth the extra code. If your parameters aren't basic types, but objects however starting to take them as const refernces really starts making a difference. </li>\n</ul>\n\n<p>Not implemented but advised:</p>\n\n<ul>\n<li>Allow supporting inputs for the whole range of double. This makes your function more general, and thus more useful. If a program logic needs to restrict more, that should not be done in this function.</li>\n</ul>\n\n<hr>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n\n\ndouble getUnixTimeStamp( int year, int month, int day, int hour, int minute, int second );\n\n\nint main()\n{\n std::cout &lt;&lt; std::fixed &lt;&lt; getUnixTimeStamp( 1979, 12, 31, 23, 59, 59 ) &lt;&lt; std::endl;\n\n return 0;\n}\n\n\n\n// start of getUnixTimeStamp code\nstatic const int N_DAYS_IN_MONTH [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\nstatic const int N_DAYS_IN_LEAP_MONTH[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n\n\n// Is the passed in year a leap year?\n// https://en.wikipedia.org/wiki/Leap_year#Algorithm\ninline\nbool\nisLeapYear( const int year )\n{\n return\n\n year % 400 == 0\n || ( year % 4 == 0 &amp;&amp; year % 100 != 0 )\n\n ;\n}\n\n\n\n// returns the epoch timestamp for a given date in UTC\n// reference: https://en.wikipedia.org/wiki/Unix_time\n\n// current minimum supported date = 0000-01-01 00:00:00\n// current maximum supported date = 2999-12-31 59:00:00\n// returns 0 on faulty input, as well as for epoch input\n\n// TODO: support full range of double rather than limiting arbitrarily\n\n\ndouble\ngetUnixTimeStamp( const int year, const int month, const int day, const int hour, const int minute, const int second )\n{\n // Do some bounds checking\n // Note that double will still not be indefinite, and you should check what the boundaries for double are.\n // (this also changes per implementation, so you need to check limits.h or something like that)\n // It would be more logical and correct to limit to the range permitted by double than to arbitrarily limit a 0y.\n // If your program needs this limit, you should enforce it outside this function, because it doesn't belong here.\n\n const int* const DAYS_PER_MONTH = isLeapYear( year ) ? N_DAYS_IN_LEAP_MONTH : N_DAYS_IN_MONTH;\n\n if\n (\n year &lt; 0 || year &gt; 3000\n || month &lt; 1 || month &gt; 12\n || day &lt; 1 || day &gt; DAYS_PER_MONTH[ month-1 ]\n || hour &lt; 0 || hour &gt; 24\n || minute &lt; 0 || minute &gt; 60\n || second &lt; 0 || second &gt; 60\n )\n\n return 0;\n // it is problematic to do error handling with the return value, as all possible return values could be valid epochs as well.\n // at least by taking 0 you can use a boolean check like if( x = getUnixTimeStamp(...) ) -&gt; valid.\n // The check will fail for 1970-01-01-00-00-00\n\n\n\n // Calculate the seconds since or to epoch\n // Formula for dates before epoch will subtract the full years first, and then add the days passed in that year.\n\n int epoch = 1970 ; // UNIX epoch 01/01/1970\n int sign = year &gt; epoch ? 1 : -1 ; // So we know whether to add or subtract leap days\n\n int nleapdays = 0 ; // The number of leap days\n int monthsNDays = 0 ; // The number of days passed in the current year\n\n\n // Count the leap days\n for( int i = std::min( year, epoch ); i &lt; std::max( year, epoch ); i++ )\n\n if( isLeapYear( i ) )\n\n ++nleapdays;\n\n\n // Calculate the number of days passed in the current year\n for( int i = 1; i &lt; month; i++ )\n\n monthsNDays += DAYS_PER_MONTH[ i - 1 ];\n\n\n\n return\n\n (\n ( year - epoch ) * 365 // add or subtract the full years\n + sign * nleapdays // add or subtract the leap days\n + monthsNDays // The number of days since the beginning of the year for full months\n + day - 1 // The number of full days this month\n\n ) * 86400 // number of seconds in 1 day\n\n + hour * 3600\n + minute * 60\n + second\n ;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T09:11:45.293", "Id": "18727", "Score": "0", "body": "Hi, have you ever tried the code ? Yes there is flaws, but you definitively haven't understood the code. No you don't need to count backward and yes testing for month > 2 have some sense (when the actual year is leap)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T09:16:23.413", "Id": "18728", "Score": "0", "body": "Your comments regarding the style and the structure are correct. But regarding unit testing do you have an example when the function returns incorrect output ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:06:06.793", "Id": "18753", "Score": "0", "body": "Hi, I am very sorry. You are completely right. I didn't understand that you were subtracting full years first. I owe you a proper review and have updated my answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T16:25:36.863", "Id": "11662", "ParentId": "11614", "Score": "4" } } ]
{ "AcceptedAnswerId": "11662", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T10:36:08.273", "Id": "11614", "Score": "2", "Tags": [ "c++", "datetime", "reinventing-the-wheel" ], "Title": "Determine total number of seconds since the epoch" }
11614