body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Is the test flexible?</p> <pre><code> describe "self.sort" do before(:each) do @tee = FactoryGirl.create :author, nickname: "tee jia hen", user: FactoryGirl.create(:user) @jon = FactoryGirl.create :author, nickname: "jon", user: FactoryGirl.create(:user) @tee_article1 = FactoryGirl.create :article, author: @tee, title: "3diablo" @tee_article2 = FactoryGirl.create :article, author: @tee, title: "1people" @jon_article = FactoryGirl.create :article, author:@jon, title: "2game" end it ", it should sort articles base on title" do Article.sort("title", "asc").should == [@tee_article2, @jon_article, @tee_article1] end end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T06:47:13.077", "Id": "23610", "Score": "0", "body": "As far as I can tell, that is a perfectly well-written rspec test. But we can't decided if it's flexible until you tell us what you might do with it." } ]
[ { "body": "<p>Provided you sort the active record results (as you have done), comparing to an array works fine. I'm not sure what you mean by 'flexible', but the test you've written looks pretty good (without knowing the internals of your 'sort' function).</p>\n\n<p>I'd only suggest adding some more tests to cover reverse sorting, sorting by author.nickname (if that's part of the default scope, or pulled in via delegation), and passing invalid values to the sort function.</p>\n\n<p>Being a little pedantic, you don't need to repeat the word \"it\" in the spec declaration.\nThe word \"it\" will be prepended to the message in the case of failures.</p>\n\n<pre><code> describe \"self.sort\" do\n before(:each) do\n @tee = FactoryGirl.create :author, nickname: \"tee jia hen\", user: FactoryGirl.create(:user)\n @jon = FactoryGirl.create :author, nickname: \"jon\", user: FactoryGirl.create(:user)\n @tee_article1 = FactoryGirl.create :article, author: @tee, title: \"3diablo\"\n @tee_article2 = FactoryGirl.create :article, author: @tee, title: \"1people\"\n @jon_article = FactoryGirl.create :article, author:@jon, title: \"2game\"\n end\n\n it \"should sort articles base on title\" do\n Article.sort(\"title\", \"asc\").should == [@tee_article2, @jon_article, @tee_article1]\n end\n\n it \"should reverse-sort articles base on title\" do\n Article.sort(\"title\", \"desc\").should == [@tee_article1, @jon_article, @tee_article2]\n end\n end\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T05:24:05.817", "Id": "14974", "ParentId": "14548", "Score": "3" } } ]
{ "AcceptedAnswerId": "14974", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T03:22:11.153", "Id": "14548", "Score": "2", "Tags": [ "ruby", "ruby-on-rails", "rspec" ], "Title": "Comparing an active record result with an array of object in a rspec test" }
14548
<p>I'm creating a MVC structured content management system as both a means to learn better OOP and redesign my tacky website to me more modular and simplistic. My aim is to approach everything with regard for minimalism so I want all my code to be precise and to the point. As this is my first go at both MVC and true OOP php I'd like to get some feedback on my progress thus far. Below is a sample of my websites blog code, this is been my main area of focus and is where I try out new code before implementing them elsewhere. If other snippets of code are required I'll append them at the bottom. </p> <blockquote> <p><strong>Controller - controllers/Blog.php</strong></p> </blockquote> <pre><code>&lt;?php class Blogs extends AdminController { function __construct(Request $request, $config) { parent::__construct($request, $config); } function show() { $blog = new Blog(); $post['title'] = "TITLE"; $post['id'] = "IDENT"; $blog-&gt;newPost(1, $post); $content['blogs'] = $blog-&gt;get_where(); $al = new Post(); $content['posts'] = $al-&gt;get_where(); $this-&gt;view-&gt;load('content', 'blogs/list', $content); $this-&gt;view-&gt;render("theme_admin"); } function edit() { $id = $this-&gt;request-&gt;segment(2); $al = new Post($id); $content['post'] = $al; $this-&gt;view-&gt;load('content', 'blogs/edit', $content); $this-&gt;view-&gt;render("theme_admin"); } function save() { $al = new Post(); $_POST['title'] = htmlspecialchars($_POST['title'], ENT_QUOTES); $_POST['content'] = htmlspecialchars($_POST['content'], ENT_QUOTES); $_POST['likes'] = htmlspecialchars($_POST['likes'], ENT_QUOTES); $al-&gt;save($_POST); // redirect('admin/blogs'); } function delete() { $id = $this-&gt;request-&gt;segment(2); $al = new Post($id); $al-&gt;delete(); last_page(); } } </code></pre> <blockquote> <p><strong>View - views/blog/list.php</strong></p> </blockquote> <pre><code>&lt;div class="box"&gt; &lt;div class="box-header"&gt; &lt;h1&gt;Typography&lt;/h1&gt; &lt;/div&gt; &lt;div class="box-content"&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;ID&lt;/th&gt; &lt;th&gt;Blog&lt;/th&gt; &lt;th&gt;Title&lt;/th&gt; &lt;th&gt;Content&lt;/th&gt; &lt;th&gt;Likes&lt;/th&gt; &lt;th&gt;Actions&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;? if ($posts): ?&gt; &lt;? foreach ($posts as $post) : ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?= $post-&gt;id ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?= $post-&gt;blogID ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?= $post-&gt;title ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?= $post-&gt;content ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?= $post-&gt;likes ?&gt;&lt;/td&gt; &lt;td&gt; &lt;a href="&lt;?= url('admin/blogs/edit/' . $post-&gt;id) ?&gt;" class="button plain"&gt;Edit&lt;/a&gt; &lt;a href="&lt;?= url('admin/blogs/delete/' . $post-&gt;id) ?&gt;" class="button plain"&gt;Delete&lt;/a&gt; &lt;a href="&lt;?= url('blogs/' . $post-&gt;id) ?&gt;" class="button plain"&gt;View&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;? endforeach; ?&gt; &lt;? endif; ?&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;div class="action_bar"&gt; &lt;a href="&lt;?= url('admin/blogs/edit') ?&gt;" class="button blue"&gt;Add New Post&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;? if ($blogs): ?&gt; &lt;? foreach ($blogs as $blog) : ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?= $blog-&gt;id ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?= $blog-&gt;title ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;? endforeach; ?&gt; &lt;? endif; ?&gt; &lt;form enctype="multipart/form-data" action="&lt;?= url('admin/blogs/upload') ?&gt;" method="post"&gt; &lt;input type="hidden" name="MAX_FILE_SIZE" value="2000000" /&gt; &lt;p&gt;File to upload &lt;input name="userfile" type="file" /&gt; &lt;input type="submit" name="send" value="Upload File" /&gt;&lt;/p&gt; &lt;/form&gt; </code></pre> <blockquote> <p><strong>Models models/Blog.php</strong></p> </blockquote> <pre><code>&lt;?php class Blog extends Model { } </code></pre> <p>Right now there's no actual unique code for the blog, everythings simply loaded through the main model class below. <strong>This is something that I've probably messed up so I'd love to get feedback here</strong></p> <blockquote> <p><strong>Models lib/Model.php</strong></p> </blockquote> <pre><code>&lt;?php require LIB . 'Database.php'; class Model { public $model; public $table; public $fields; public $db; function __construct($id = null) { $this-&gt;db = new Database(); $this-&gt;model = get_class($this); $this-&gt;table = strtolower($this-&gt;model) . 's'; $this-&gt;init_fields($id); } function init_fields($id = null) { $this-&gt;fields = $this-&gt;fields(); if (!empty($id)) { $this-&gt;get($id); } else { foreach ($this-&gt;fields as $field) { $this-&gt;{$field} = null; } } } function fields() { $res = $this-&gt;db-&gt;query('SHOW COLUMNS FROM ' . $this-&gt;table); $fields = array(); while ($row = $res-&gt;fetch()) { // var_dump($row); $fields[] = $row-&gt;Field; } return $fields; } function get($id) { $res = $this-&gt;db-&gt;query('SELECT * FROM ' . $this-&gt;table . ' WHERE id=?', array($id)); $row = $res-&gt;fetch(); if ($row) { foreach ($row as $key =&gt; $val) { $this-&gt;{$key} = $val; } } return $this; } function exists() { if (!empty($this-&gt;id)) { $res = $this-&gt;db-&gt;query('SELECT * FROM ' . $this-&gt;table . ' WHERE id=?', array($this-&gt;id)); return $res-&gt;num_rows() ? true : false; } return false; } function get_where() { $res = $this-&gt;db-&gt;query('SELECT * FROM ' . $this-&gt;table); $arr = array(); while ($row = $res-&gt;fetch()) { $arr[] = $row; } return $arr; } function save($arr = null) { //append values from assoc array if ($arr) { foreach ($this-&gt;fields as $key) { if (array_key_exists($key, $arr)) { $this-&gt;{$key} = $arr[$key]; } } } $update_arr = array(); $update_str = array(); foreach ($this-&gt;fields as $key) { if (!empty($this-&gt;{$key})) { $update_str[] = "$key = ?"; $update_arr[] = $this-&gt;{$key}; } } $sql = ' SET ' . implode(',', $update_str); if ($this-&gt;exists()) { $sql = "UPDATE " . $this-&gt;table . $sql . " WHERE id=?"; $update_arr[] = $this-&gt;id; } else { $sql = "INSERT INTO " . $this-&gt;table . $sql; } $res = $this-&gt;db-&gt;query($sql, $update_arr); if (empty($this-&gt;id)) { $this-&gt;id = $res-&gt;insert_id(); } return $res-&gt;affected_rows(); } function delete() { if( isset($this-&gt;id) ) { $res = $this-&gt;db-&gt;query('DELETE FROM ' . $this-&gt;table . ' WHERE id=?', $this-&gt;id); return $res-&gt;affected_rows(); } return false; } } </code></pre>
[]
[ { "body": "<p>Woah boy, sorry about the wall.</p>\n\n<p><strong>View</strong></p>\n\n<p>I'll start with the easiest section first to get it out of the way. Short tags should be avoided, even in views. Not all servers support them and its just easier to write it out the first time rather than worry about something being unsupported in the future. There are ways of changing this setting via a file, but again, not all servers allow that file to be modified. If you can guarantee that your server will always support these, then I guess it wont be an issue, but this is typically avoided and many developers will flag you for it (though many wont).</p>\n\n<p>If you can guarantee that <code>$posts</code> and <code>$blogs</code> are always set, which it appears that you can since you aren't explicitly doing an <code>isset()</code> check, then you can just call the foreach loop without needing the if statement. You'll need to ensure that they are always at least an empty array. Foreach can't loop over an empty array so it will just skip it. Some people would also complain that you are using separate PHP tags to escape the if and foreach blocks. I'm not going to say one way or the other as I agree with your method of separating them, just figured I'd mention it.</p>\n\n<p><strong>Controller</strong></p>\n\n<p>When defining a class, you should always specify the access level of your properties and methods (public, private, protected). By default it sets everything to public, which isn't always desirable. But that isn't the big issue here, well, not the only big issue. Eventually PHP is going to deprecate support for the \"default\" property/method declarations and it will be mandatory (as it should have been from the beginning). Plan for the future and make sure your code is compatible now. Besides, its just good coding practice.</p>\n\n<p>When extending a class, it is not necessary to redefine an inherited method unless you are going to do something extra with it. As it stands this is just redundant. I show an example of how to properly override the contructor a little later.</p>\n\n<p>Your method names are a little misleading, not just here, but in the other files too. If we follow the Single Responsibility Principle, as we should with OOP, then we know that a method which says they are going to \"show\" us something should only be concerned with \"showing\" us something. You have it creating a new blog, new post, and setting up the view variables. All of this is necessary to render the final view, but its not necessary for the <code>show()</code> method to be concerned with how each part is done. It just needs it done. So you should delegate these tasks to the right methods.</p>\n\n<p>There's another issue in your <code>show()</code> method. The <code>$post</code> array came out of no where. It was never defined, it just started getting indices defined to it. I hope its just that you didn't know any better rather than that you are using globals. If the later, stop immediately and ask for help on that subject specifically before proceeding, you should never use globals. If the former, keep reading. The reason this works is because PHP is so lenient and allows you to create things on the fly. Sometimes this is good, sometimes bad. Its bad in this situation. I believe you may even be receiving silent warnings in the background. But what would happen if you had mistakenly defined the <code>$post</code> variable as a string earlier? Or this was implemented in an environment with a global <code>$post</code> (which I just said were bad, this being one of the reasons)? I'm honestly not sure, but I would imagine chaos would ensue. I know with numerical indices you can read and write to strings using the array syntax, but I don't know how associative array syntax would work. With the globals you would have similar issues. Always define your arrays before using them, this isn't as important with variables, but even those should be defined before attempting to modify them. The proper way to initialize an associative array with predefined data is like so:</p>\n\n<pre><code>$post = array(\n 'title' =&gt; 'TITLE',\n 'id' =&gt; 'IDENT'\n);\n</code></pre>\n\n<p>Now, if you were to delegate these tasks like I mentioned earlier, this would become even easier. Imagine the above code was in one of those new methods. You wouldn't always want to use the same title and id, so you would pass those as parameters. And an easy way to get parameters or variables into an associative array using their names as keys, is to use <code>compact()</code>.</p>\n\n<pre><code>public function createPost( $title, $id ) {\n $this-&gt;blog-&gt;newPost( 1, compact( 'title', 'id' ) );\n}\n</code></pre>\n\n<p>Now, I introduced something new above, the <code>$this-&gt;blog</code> property. Another key principle of OOP is the \"Don't Repeat Yourself\" (DRY) Principle. The name is pretty self explanatory. It usually refers to duplicate code being refactored to functions/methods. This is similar. This principle goes hand-in-hand with the first one I mentioned. If your methods follow the first principle, they are ready to accept DRY code. So, all these methods where you are creating and recreating the same objects can more easily be done by implementing them as class properties. For instance, if we define a <code>new Post()</code> in our constructor and set it as a class property, then we can reuse that property anywhere throughout the rest of the class simply by referring to it by <code>$this-&gt;</code>. It doesn't have to be in the constructor, this just ensures that it has been initialized before we try using it.</p>\n\n<pre><code>private\n $blog,\n $al\n;//define your properties\n\npublic function __construct( Request $request, $config ) {\n parent::__construct( $request, $config );\n\n $this-&gt;blog = new Blog();\n $this-&gt;al = new Post();\n}\n\nfunction show() {\n //$blog = new Blog();//unnecessary now\n //your code\n $this-&gt;blog-&gt;newPost( 1, $post );\n //$al = new Post();//unnecessary now\n $content[ 'posts' ] = $this-&gt;al-&gt;get_where();\n //your code\n}\n</code></pre>\n\n<p>I would suggest not directly modifying the POST data. If you want to clean and sanitize, by all means do, but make a copy of it and change that. I'm not entirely sure, but I believe some browsers allow you to access this information. So POST information, which is normally private, would be available with any changes we made to it. While this may not be too important with sanitizing, it is important if you do something like, hash and salt a password. There are other reasons, such as data integrity. Perhaps a more efficient way to go about this would be to use the <code>filter_input_array()</code> function PHP provides (assuming your PHP version >= 5.2). I've played with the <code>filter_input()</code> function, but haven't used the other yet, so I don't want to demonstrate something I'm not 100% on. See the documentation and google if you are curious.</p>\n\n<p><strong>Model</strong></p>\n\n<p>A parent class should declare only the base functionality necessary to do something. A child class should extend the parent by adding more specific functionality. For instance, a database class would only have functionality available to all databases (add, delete, find, etc...). A SQL database would specifically define how the parent functionality would work for SQL and would add any additional functionality it would need. How does this relate to your code? Well, if all of your models use a SQL database, the SQL specific functionality is reasonable, but, depending on the scope of this project, you might consider defining a new SQL class that extends the database class as I described above, then have your models extend the SQL class. That way, if you ever decide to change the type of database you are using, you can do so with very little refactoring. Of course, you'll probably want to rename the SQL database to something more generic, that way you won't have to change all the \"extends\".</p>\n\n<p>There are so many minor things here that would just help with code flow. For instance, don't create something you aren't going to use. In your <code>init_fields()</code> method you define the <code>$fields</code> property, but then only use it if the <code>$id</code> is empty. Move that into the else statement where it belongs. And you shouldn't be checking if <code>$id</code> is empty but if it <code>isset()</code>. Unless its an array, but then you should have the default be an empty array not null. And you shouldn't use the \"not\" <code>!</code> operator unless its necessary. Here you have an else clause, just switch the conditions around and lose the \"not\". Although <code>isset()</code> will probably do this for you. Just remember it for future code.</p>\n\n<p>Variable variables are mostly considered bad. If you are confused as to what a variable variable is, see below. Sometimes, such as in controllers, it is acceptable. But in other cases you want to avoid it. I didn't see you doing it elsewhere, but I just wanted to make sure you understood that. A more common way is to use <code>extract()</code> in your render method just before you include the view. This is the companion method to the <code>compact()</code> function I explained earlier, it dumps all the array keys/values into the local scope as variables with the keys for names and the values as the new values for those variables.</p>\n\n<pre><code>$this-&gt;{$field} = null;\n//Could also be rewritten like this\n$this-&gt;$field = null;\n//More common way\nextract( $this-&gt;fields );\ninclude $templateFile;\n</code></pre>\n\n<p>Method <code>get()</code> is oddly named, it isn't getting anything. It is setting quite a bit. But get and set should be avoided as method names altogether. They could be confused with the magic <code>__get()</code> and <code>__set()</code> methods. Again, the if statement is unnecessary, I believe the fetch method returns an empty array if no results were found (may be wrong). Returning <code>$this</code> is only useful for chaining methods together or returning the entire object so that it can be cloned. You are doing neither here so the return is one unnecessary and two inefficient.</p>\n\n<p><strong>Conclusion</strong></p>\n\n<p>Now, I stopped right about here because I've already written quite a bit and I was starting to feel lost. I'm not really sure about your framework because none of it looks exactly right. I tried covering specific problems in each section, but there are some overall problems I did not address.</p>\n\n<p>You've got your controller, which is ALMOST a controller, but relies on other classes to render the page for it. It appears that you have a \"master\" controller for a set of \"subcontrollers\" that each focuses on a different view. This is backwards from how it should be. Traditionally, you would cut out the \"master\" controller and just use the \"subcontrollers\" directly. Any code you find yourself needing in multiple controllers can be added to a parent controller for that group of pages, and any code you need in ALL controllers would be in the \"base\" controller class. As it is, each page can potentially render any other page just by calling a specific method. This is bad for two reasons. First because this adds unnecessary overhead to each view using this controller. Second, because your controllers should all be set up the same. Controllers typically have two constant methods. A \"main\" or \"init\" method that initiates the specific session needed before calling the second constant method, the render method, which extracts the variables for the view before including it. And then any helper methods you may need to help interface your controller with your model.</p>\n\n<p>You've got your model, which COULD be a model, but it is too specific to the application. For one, it is doing things that the controller should actually be doing such as setting the variables for the view. Think of a model as the interface to your database. It should accept commands from the controller with the parameters necessary to complete that command. The commands should be common tasks associated with databases, such as <code>add()</code>, <code>delete()</code>, <code>update()</code>, etc... In other words, the model is only concerned with reading and writing data, not with how it is displayed or where it is coming from (though to a lesser extent).</p>\n\n<p>Only your views look right. Though, as I said, the preferred method is to extract the variables so that the view is not concerned with the class being instantiated.</p>\n\n<p>When starting off on such a large task you should start small and expand gradually. Instead you started large and now you are having to go back to the smaller things. I don't know about you, but that a very daunting task. When I make MVC frameworks, I start off with the views because they are the easiest and provide immediate results. I create the page as I want it to look, and define all the variables I think I'm going to need. I say think, because I always find I either don't need as many as I think I do, or because I need more. In other words, be prepared for things to change. Then I create a skeleton Controller. The first thing I do in the new controller is create the <code>init()</code> method. Inside this method I hard code all the variables my view will need into a <code>$data</code> array property. Then I create the <code>render()</code> method to <code>extract()</code> my <code>$data</code> array into the local scope and include the view. After that I work on getting my model fleshed out. Once the model is completely done I go back to the controller and remove all those hard coded variables, one at a time, and replace them with the proper sequences necessary to retrieve them from the Model. This way, at the conclusion of each step, I have a fully functional test I can touch and tweak as the code progresses.</p>\n\n<p>Again, sorry for the long wall of text. I got a bit carried away. Hope it helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T02:53:19.823", "Id": "23832", "Score": "1", "body": "Don't apologize on the wall of text. I'd much rather an excess of information then just a trickle of issues. This has been very helpful. Cheers!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T20:52:42.773", "Id": "14670", "ParentId": "14550", "Score": "2" } } ]
{ "AcceptedAnswerId": "14670", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T10:14:49.520", "Id": "14550", "Score": "1", "Tags": [ "php", "object-oriented", "mvc" ], "Title": "MVC Structured CMS" }
14550
<p>I have written some code in Java that consists of two classes. I have tried my best and I want you to tell me if I can improve and how good this is.</p> <p>Also, how important is OOP? Java is an object oriented language, so I have also tried my best to use it that way (although I don't know whether I have succeeded or not).</p> <p><strong>MainClass</strong></p> <pre><code>import java.util.Scanner; class MainClass{ public static void main(String args[]){ RandomDice dice = new RandomDice(); Scanner scan = new Scanner(System.in); System.out.print("Please enter the number of times you want to roll the dice:"); int arg0 = scan.nextInt(); dice.roll(arg0); } } </code></pre> <hr> <p><strong>RandomDice</strong></p> <pre><code>/*This program will help you to imitate the randomness of a dice roll, *and to represent the frequency of each face appearing in a tabular form. */ import java.util.Random; public class RandomDice{ private int diceRoll; Random rand = new Random(); /// the method below takes an argument arg0 which indicates the amount of times the dice has to be rolled. public void roll(int arg0){ diceRoll = arg0; int ObservationArray[] = {0,0,0,0,0,0}; ObserveRandom(diceRoll,ObservationArray); DisplayResult(ObservationArray); } ///this method creates random numbers from 0 to 5 and respectively stores them in the array index stimulating a dice being rolled. public void ObserveRandom(int arg1,int ObservationArray[]){ for(int counter=0;counter&lt;arg1;counter++){ ++ObservationArray[rand.nextInt(6)]; } } ///this method displays the data collected in a tabular form. public void DisplayResult(int arg1[]){ System.out.println("face\tfrequency"); for(int counter=0;counter&lt;arg1.length;counter++){ System.out.println(1+counter+"\t"+arg1[counter]); } } } </code></pre>
[]
[ { "body": "<p>Your code is clear and readable. You are asking about how much your code fit with OOP and this is a good mindset.</p>\n\n<p>I won't be writing here abstract and theoretical concepts about OOP or design patterns, but just the first ideas which came up to my mind while I read your code.</p>\n\n<p><strong>1) First, about naming</strong></p>\n\n<p>In Java, method, variable and parameter names all start with a lower case letter (as opposed of methods in C++ for instance). You need to change the variable name <code>ObservationArray</code> and the method names <code>ObserveRandom</code> and <code>DisplayResult</code> accordingly.</p>\n\n<p>Also, you should provide a better name for the integer variable which stores the number of dice rolls, like, for instance, <code>diceRollCount</code> instead of <code>arg0</code>. The same remark applies for code wihtin the <code>RandomDice</code> object.</p>\n\n<p><strong>2) About design</strong></p>\n\n<p><em>Separation of concern and specialization of objects</em> is one of the core concept in OOP.\nHere, your code is showing a rather procedural approach:</p>\n\n<ol>\n<li>Ask the user how many dice rolls to do </li>\n<li>Create an <code>ObservationArray</code></li>\n<li>Roll dice as many time as expected</li>\n<li>Print the result</li>\n</ol>\n\n<p>In OOP, you need rather to think in term of components which you can see as black boxes with a limited responsibility and which share well-established relationships with other objects. Other objects should not rely on the concrete implementation of these black boxes but only on the contract which describes how to use them and for which intent.</p>\n\n<p>With this in mind, we can extract a couple of conceptual objects for your purpose:</p>\n\n<ol>\n<li>An object which state will represent the result of the computation (=the dice rolls).</li>\n<li>An object which will produce the computation result (the \"computer\" object)</li>\n<li>An object which will provide the computer with the number of times it should roll dice.</li>\n<li>An object which will consume the computation result.</li>\n</ol>\n\n<p>With this separation of concern, you can see that it is not that important where the number of times to roll dice is taken from : be it from the keyboard input, from a file, from a program argument, a text field in a GUI or whatever. Where you print the result can also be abstracted.\nWhat emerges also from this design is the state object which purpose is to hold the computation result. It is an example of what we could call a <em>domain object</em>, which here contains the value-added by your business logic and is designed on purpose. It is used to convey information between the different components of your architecture : the producer (which computes the result) and the consumer (which prints the result or do whatever else).</p>\n\n<p>To make it more concrete, we could end up with the following objects:</p>\n\n<pre><code>class RollCountProvider {\n\n public int getRollCount() { ... }\n}\n\nclass DiceRollResult {\n\n private final Map&lt;Integer, Integer&gt; frequencies;\n\n public DiceRollResult(Map&lt;Integer, Integer&gt; frequencies) {\n this.frequencies = frequencies;\n }\n\n public int getFrequency(int face) { \n // Check bounds\n return frequencies.get(face);\n }\n}\n\nclass DiceRoller {\n\n private static final int DICE_FACES_COUNT = 6;\n\n public static DiceRollResult roll(RollCountProvider rcProvider) { \n final Map&lt;Integer, Integer&gt; frequencies = new HashMap&lt;Integer, Integer&gt;();\n\n for (int i = 0 ; i &lt; rcProvider.getRollCount() ; i++) {\n int face = rand.nextInt(DICE_FACES_COUNT); // Avoid magic number\n Integer frequency = frequencies.get(face);\n\n if (null == frequency) // Take care to check for null reference\n frequency = 0; // use autoboxing\n\n frequencies.put(face, ++frequency);\n }\n\n return new DiceRollResult(frequencies);\n }\n}\n\nclass RollResultPrinter {\n\n public static void printResult(DiceRollResult result) { ... }\n}\n</code></pre>\n\n<p>Few remarks about these classes: </p>\n\n<ol>\n<li>As you can see, some methods used the <code>static</code> modifier since their class does not hold any particular state.</li>\n<li>You do not need to stick to an array of integer but can use a Map instead.</li>\n<li>Your domain object <code>DiceRollResult</code> should be immutable (which is not in this implementation: this is a design flaw. The object should copy the map provided to the constructor to ensure immutability).</li>\n<li>Avoid magic number (always prefer constants to literals when the inference of their meaning from the context is not straightforward).</li>\n</ol>\n\n<p>All of this is rather overdesigned for this particular program, but I hope it will help you to build your own insights about OOP design.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T12:53:37.227", "Id": "14552", "ParentId": "14551", "Score": "7" } }, { "body": "<p>Thanks for submitting your code for review — it shows that you care about code quality and you're willing to improve and learn.<br>\n<sub>Note that OOP stands for object-oriented programming and does not have a plural form ;-)</sub></p>\n\n<p>Alexandre has given you some good advice and one possible implementation. I'd like to critique your code a bit more thoroughly and offer another, more lightweight possibility. </p>\n\n<hr>\n\n<h1>Criticism</h1>\n\n<h2>Concept</h2>\n\n<p>An important idea in software development is that code should be reusable. Your code seems like a specific application of a general idea that applies not only to throwing the dice but just as well to tossing a coin or drawing a card (and gathering statistics).</p>\n\n<p>So you should consider designing your code in a way that allows it to work for all these (and other) scenarios. That is to say, the number of elements in the input sequence (currently 6) and the element names themselves (currently <code>{1,2,3,4,5,6}</code>) should be configurable by the caller of the code. </p>\n\n<h2>Separation of concerns</h2>\n\n<p>I'll keep this part short since Alexandre has already elaborated on it. Just remember a few key points:</p>\n\n<ul>\n<li><strong>Never put any user interface related code into your core business logic</strong> <sup>(<code>RandomDice</code> class)</sup><br>\nIf you mix up these concerns, you'll find it hard to reuse your code for applications based on other UI frameworks than the Console (for instance, Swing, SWT or AWT or Servlets).</li>\n<li><strong>Instead of outputting data, use return values</strong><br>\nJust replace occurrences of <code>System.out.println</code> with an appropriate return value (e.g. String) </li>\n<li><strong>Choose one responsibility per object</strong> <em>and refactor others into new objects</em><br>\nThe class that calculates the statistics should not be in charge of formatting the output — you need to introduce a new <strong>Collaborator</strong> (an object that encapsulates that responsibility)</li>\n</ul>\n\n<h2>Comments</h2>\n\n<ul>\n<li><strong>Use them sparingly</strong> <em>or they will cause clutter and be ignored</em></li>\n<li><strong>Check your spelling and grammar</strong><br>\n<ul>\n<li><code>amount of times</code> should be <code>number of times</code> </li>\n<li><code>stimulating</code> should be <code>simulating</code></li>\n</ul></li>\n<li><p><strong>Format them properly</strong><br>\nFor summaries above class and method definitions <em>(don't put them between <code>package</code> and <code>import</code> but <strong>directly</strong> above the relevant code!)</em> always use the same (<a href=\"http://research.cs.queensu.ca/home/cisc124/2001f/Javadoc.html\">Javadoc</a>) syntax: </p>\n\n<pre><code>/** \n * This program will help you to imitate the randomness of a dice roll,\n * and to represent the frequency of each face appearing in a tabular form.\n */\n</code></pre></li>\n<li><p><strong>Choose better names to avoid writing a comment</strong> </p></li>\n</ul>\n\n<h1>Naming</h1>\n\n<ul>\n<li><p><strong>Be expressive</strong> <em>and avoid junk names such as <code>arg0</code> or <code>arg1</code></em><br>\nInstead of the following obsolete comment:</p>\n\n<pre><code>// / the method below takes an argument arg0 which indicates the amount of\n// times the dice has to be rolled.\npublic void roll(int arg0) {\n diceRoll = arg0;\n</code></pre>\n\n<p>Why not get rid of the field <code>diceRoll</code> and write</p>\n\n<pre><code>public void roll(int numberOfTimes) {\n</code></pre></li>\n<li><p><strong>Avoid stating the obvious</strong> <em>(that applies to comments, too!)</em><br>\n<code>Dice</code> can reasonably be assumed to be random, so <code>RandomDice</code> is unnecessary<br>\n<code>MainClass</code> also states the obvious, just use <code>Main</code></p></li>\n<li><strong>Follow conventions</strong> <em>(methods and variables are <code>camelCase</code>, classes are <code>PascalCase</code>)</em></li>\n</ul>\n\n<h2>Also</h2>\n\n<ul>\n<li><p><strong>Always specify access modifiers</strong><br>\nUse the most restrictive access modifier possible <em>(in your code, <code>rand</code> was accessible from other classes!)</em>:</p></li>\n<li><p><strong>Don't declare your arrays C-Style</strong> <em>(keep the data type before the variable instead)</em></p>\n\n<pre><code>int ObservationArray[] = { 0, 0, 0, 0, 0, 0 }; // don't do this\nint[] ObservationArray = { 0, 0, 0, 0, 0, 0 }; // this form is clearer\n</code></pre></li>\n</ul>\n\n<hr>\n\n<h1>Alternative implementation</h1>\n\n<p>By refactoring step-for-step and slowly introducing changes, I arrived at the implementation shown below that aims to illustrate the points made in this answer. <code>RandomDice</code> was renamed to <code>DistributionCalculator</code> and is now generic (it can work with any type of elements, as illustrated in the <strong>Usage</strong> section). It accepts an Array of elements in the static convenience method <code>with</code>. After initialization, the frequencies can be calculated by calling <code>calculateDistribution</code>. </p>\n\n<p>That method returns a <code>Distribution&lt;K,V&gt;</code> which is the class that encapsulates the string formatting (I went ahead and made the output a bit more pretty). </p>\n\n<p>The naming could probably be more accurate from a mathematical perspective — go ahead and rename things if you feel that these terms aren't quite correct (probably <code>UniformDistributionCalculator</code> or something would have been more exact).</p>\n\n<p>The frequencies are now stored as <code>long</code>s to allow for bigger calculations, though that can be changed easily if you don't agree with the decision. </p>\n\n<p>If something requires further explanation, go ahead and ask in the comments.</p>\n\n<h2>Usage</h2>\n\n<pre><code>public class Main {\n private static final Scanner scan = new Scanner(System.in);\n private static long iterations;\n\n public static void main(String args[]) {\n System.out.print(\"Please enter the number of times you want to iterate: \"); \n iterations = scan.nextLong();\n test(DistributionCalculator.with(1, 2, 3, 4, 5, 6));\n test(DistributionCalculator.with(\"hearts\", \"spades\", \"clubs\", \"diamonds\"));\n test(DistributionCalculator.with(true, false, null));\n }\n\n private static &lt;T&gt; void test(DistributionCalculator&lt;T&gt; calculator) {\n System.out.println(calculator.calculateDistribution(iterations));\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Output</h2>\n\n<blockquote>\n<pre><code> Please enter the number of times you want to iterate: 200000\n\n element frequency\n 1 33129\n 2 33156\n 3 33539\n 4 33469\n 5 33346\n 6 33361\n\n element frequency\n hearts 50100\n diamonds 49857\n spades 49752\n clubs 50291\n\n element frequency\n null 66560\n false 66726\n true 66714\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h2>Calculation of frequencies</h2>\n\n<pre><code>public class DistributionCalculator&lt;T&gt; {\n\n private static final Random random = new Random();\n private final Map&lt;T, Long&gt; map = new HashMap&lt;T, Long&gt;();\n private final T[] keys;\n\n public static &lt;T&gt; DistributionCalculator&lt;T&gt; with(T... elements) {\n return new DistributionCalculator&lt;T&gt;(elements);\n }\n\n private DistributionCalculator(T... elements) {\n keys = elements;\n for (T key : keys) {\n map.put(key, Long.valueOf(0));\n }\n }\n\n public Distribution&lt;T, Long&gt; calculateDistribution(long numberOfIterations) {\n for (long i = 0; i &lt; numberOfIterations; i++) {\n T key = keys[random.nextInt(keys.length)];\n map.put(key, map.get(key) + 1);\n }\n return new Distribution&lt;T, Long&gt;(map);\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Result formatting</h2>\n\n<pre><code>public class Distribution&lt;K, V&gt; {\n private final Map&lt;K, V&gt; map;\n private final String table;\n\n public Distribution(Map&lt;K, V&gt; distribution) {\n map = distribution;\n table = generateTable();\n }\n\n public Map&lt;K, V&gt; asMap() {\n return map;\n }\n\n @Override\n public String toString() {\n return table;\n }\n\n private String generateTable() {\n final String line = \"%n%-20s%s\";\n String result = String.format(line, \"element\", \"frequency\");\n for (K key : map.keySet()) {\n // it would be better to use a StringBuilder if you have a lot of keys\n result += String.format(line, key, map.get(key));\n }\n return result;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T03:55:57.953", "Id": "23641", "Score": "0", "body": "+1 for the great review. A small note: http://stackoverflow.com/q/46898/843804 It may be worth using `StringBuilder` in the `generateTable` too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T05:27:57.907", "Id": "23643", "Score": "0", "body": "thanks, and that's an important point (I originally did use a `StringBuilder` but removed it to simplify). Added a comment to make that clear." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T02:53:05.997", "Id": "14572", "ParentId": "14551", "Score": "8" } }, { "body": "<ol>\n<li><pre><code>System.out.println(1 + counter + \"\\t\" + arg1[counter]);\n</code></pre>\n\n<p>Using <code>+</code> as addition in a <code>println</code> is fragile. A small modification could broke the addition:</p>\n\n<pre><code>System.out.println(\"\\t\" + 1 + counter + \"\\t\" + arg1[counter]);\n</code></pre></li>\n<li><p>Proper and consistent indentation would improve the readability a lot.</p></li>\n<li><p>Consider using <a href=\"http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset\" rel=\"nofollow\">Guava's <code>MultiSet</code></a> for the counting.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T05:35:20.597", "Id": "23644", "Score": "1", "body": "MultiSet would simplify things a lot. Just one more reminder that I should finally download Guava..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T04:15:41.470", "Id": "14573", "ParentId": "14551", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T11:43:20.703", "Id": "14551", "Score": "8", "Tags": [ "java", "object-oriented", "random", "simulation", "dice" ], "Title": "Imitate randomness of a dice roll" }
14551
<p>I've written my first class to interact with a database. I was hoping I could get some feedback on the design of my class and areas that I need to improve on. Is there anything I'm doing below that is considered a bad habit that I should break now?</p> <ul> <li><code>public IEnumerable&lt;string&gt; ReturnSingleSetting(int settingCode)</code> interacts with a normalized table to populate combo boxes based on the setting value passed to it (for example, a user code of 20 is a user, sending that to this method would return all users (to fill the combobox).</li> <li><code>public void InsertHealthIndicator(string workflowType, string workflowEvent, int times, string workflowSummary)</code> interacts with a stored procedure to write a workflow error type into another normalized table.</li> <li><code>public DataView DisplayHealthIndicator(DateTime startDate, DateTime endDate)</code> uses another stored procedure to return the workflow error types between specific dates.</li> </ul> <p><strong>Note:</strong> Although this seems like I likely shouldn't use stored procedures in some areas here, I've done so so I can base some SSRS reports off the same stored procedures (so a bug fixed in one area is a bug fixed in both).</p> <pre><code>using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Data.SqlClient; using System.Windows; namespace QIC.RE.SupportBox { internal class DatabaseHandle { /// &lt;summary&gt; /// Class used when interacting with the database /// &lt;/summary&gt; public string GetConnectionString() { // todo: Integrate into settings.xml return "Data Source=FINALLYWINDOWS7\\TESTING;Initial Catalog=Testing;Integrated Security=true"; } public IEnumerable&lt;string&gt; ReturnSingleSetting(int settingCode) { var returnList = new List&lt;string&gt;(); string queryString = " select setting_main" + " from [marlin].[support_config]" + " where config_code = " + settingCode.ToString(CultureInfo.InvariantCulture) + " and setting_active = 1" + " order by setting_main"; using (var connection = new SqlConnection(GetConnectionString())) { var command = new SqlCommand(queryString, connection); try { connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { returnList.Add(reader[0].ToString()); } reader.Close(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); throw; } connection.Close(); } return returnList; } public void InsertHealthIndicator(string workflowType, string workflowEvent, int times, string workflowSummary) { string queryString = "EXEC [marlin].[support_add_workflow_indicator]" + "@workflow_type = @workflowType," + "@workflow_event = @workflowEvent," + "@event_count = @eventCount," + "@event_summary = @eventSummary"; using (var connection = new SqlConnection(GetConnectionString())) { try { connection.Open(); using(var cmd = new SqlCommand(queryString, connection)) { cmd.Parameters.AddWithValue("@workflowType", workflowType); cmd.Parameters.AddWithValue("@workflowEvent", workflowEvent); cmd.Parameters.AddWithValue("@eventCount", times); cmd.Parameters.AddWithValue("@eventSummary", workflowSummary); cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); } connection.Close(); } catch(SqlException ex) { string msg = "Insert Error: "; msg += ex.Message; throw new Exception(msg); } } } public DataView DisplayHealthIndicator(DateTime startDate, DateTime endDate) { string queryString = "[marlin].[support_retrieve_workflow_history]"; using (SqlConnection connection = new SqlConnection(GetConnectionString())) { using (var cmd = new SqlCommand(queryString, connection)) { connection.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("date_from", startDate.Date); cmd.Parameters.AddWithValue("date_to", endDate.Date); var reader = cmd.ExecuteReader(); var dt = new DataTable(); dt.Load(reader); connection.Close(); return dt.DefaultView; } } } } } </code></pre>
[]
[ { "body": "<p>I believe it's much better to use some ORM together with LINQ, rather than writing raw SQL. It means more errors are checked at compile time, it will help you avoid some common mistakes and it will make your code much shorter.</p>\n\n<p>I would also always use parametrized SQL queries and never concatenate them by hand. You do use them most of the time, and in the one case where you don't, there is no danger of SQL injection, because the parameter is an integer, but I still think it's better to use parameters everywhere. (I think it may also make your query faster thanks to caching, but I'm not completely sure about that.)</p>\n\n<p>Also, you shouldn't throw <code>Exception</code>, you should create a custom class that inherits from <code>Exception</code>. And, if possible, include the original exception as inner exception, to make debugging the original source of the error easier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T14:12:45.597", "Id": "23619", "Score": "0", "body": "I've been playing around with LINQ but what do you mean by 'ORM' (sorry, new)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T14:15:16.030", "Id": "23620", "Score": "0", "body": "and sorry, I know I'm asking a lot - but can you provide an example of an exception class that inherits from exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T18:33:41.023", "Id": "23629", "Score": "2", "body": "ORM means [Object-relational mapping](http://en.wikipedia.org/wiki/Object-relational_mapping). Examples in .Net are LINQ to SQL, Entity Framework or NHibernate. And for an example of creating custom exception, see [How to: Create User-Defined Exceptions](http://msdn.microsoft.com/en-us/library/87cdya3t.aspx)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T16:19:31.450", "Id": "23661", "Score": "0", "body": "In the code above, exception catching/throwing is fine. You only need a custom exception if you want to indicate such a thing. `catch(Exception ex)` is just a catch all & throw will re-throw the original exception." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T14:06:13.813", "Id": "14554", "ParentId": "14553", "Score": "7" } }, { "body": "<p>There are so many things you can get wrong when you use raw SQL, for instance:</p>\n\n<ol>\n<li>vulnerable to SQL injection</li>\n<li>you need to take care of messy details, such as concatenating a query string</li>\n<li>you aren't calling <code>Dispose</code> on the <code>SQLCommand</code> (should be in a using statement)</li>\n<li>the using statement will close the connection for you, no need for the <code>close</code> call</li>\n<li>everything is much longer and more complicated than it needs to be</li>\n</ol>\n\n<p>As svick suggested, use <a href=\"http://msdn.microsoft.com/en-us/library/bb384470.aspx\">LINQ to SQL</a>. The entity classes and stored procedures (<code>SupportConfig</code>, <code>db.SupportRetrieveWorkflowHistory</code>) can be generated automatically in the ORM designer.</p>\n\n<p>Here is how your code could look like using LINQ to SQL (adjustments may be required):</p>\n\n<pre><code>public IEnumerable&lt;string&gt; ReturnSingleSetting(int settingCode)\n{\n using (var db = new TestingDataContext(GetConnectionString()))\n {\n var result = from row in db.SupportConfig\n where row.ConfigCode == settingCode\n &amp;&amp; row.SettingActive\n orderby row.SettingMain\n select row.SettingMain;\n return result;\n }\n}\n\npublic IEnumerable&lt;WorkflowItem&gt; DisplayHealthIndicator(DateTime startDate, DateTime endDate)\n{\n using (var db = new TestingDataContext(GetConnectionString()))\n {\n return db.SupportRetrieveWorkflowHistory(startDate.Date, endDate.Date);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T15:02:31.077", "Id": "23621", "Score": "0", "body": "I've been told by one of the senior developers at work that I should avoid linq to sql as it's now depreciated - is there much truth to this statement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T20:26:14.970", "Id": "23633", "Score": "0", "body": "@Michael I haven't seen any mention of it being decpreciated officially however it appears most recommendations are for use of EF. There are benefits of both depending on the requirements of the solution and architecture" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T21:16:30.490", "Id": "23637", "Score": "2", "body": "@Michael LINQ to SQL [_is **neither dead nor deprecated**_](http://stackoverflow.com/a/3041035/1106367) and will not go away in the foreseeable future. [*StackExchange uses LINQ to SQL*](http://blog.stackoverflow.com/2008/09/what-was-stack-overflow-built-with/) (yes, it [still does](http://meta.stackexchange.com/questions/7202/is-stackoverflow-still-using-linq-to-sql-as-the-orm)). It is possible that LINQ to SQL and Linq to Entities (EF) may *merge* in the future — until then, it's good to use whichever fits best." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-28T23:55:28.740", "Id": "200638", "Score": "0", "body": "I'd also note that Linq-To-SQL continues to support stored procedures better than EF does." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T14:41:45.847", "Id": "14555", "ParentId": "14553", "Score": "5" } } ]
{ "AcceptedAnswerId": "14554", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T13:00:59.323", "Id": "14553", "Score": "5", "Tags": [ "c#", "sql", "ado.net" ], "Title": "Interacting with a database" }
14553
<p>Basically, I have a list, <code>newtry</code> of blocks, and I want to find a value of <code>catchtype</code> that makes them all return true for <code>block.isCatchExtendable(newhandler, catchtype)</code> or report an error if this can't be done. <code>block.isCatchExtendable</code> returns two values, success and a new type to try on failure.</p> <p>My current code works, but the control flow is very convoluted, with numerous breaks and elses. I was wondering if anyone could think of a better way to arrange things. Also, these are all my own functions, so I am free to change the interfaces, etc.</p> <pre><code>while 1: ct_changed = False for block in newtry: success, newcatchtype = block.isCatchExtendable(newhandler, catchtype) if not success: if catchtype == newcatchtype: #no success and no other types to try, so just break and fail break catchtype, ct_changed = newcatchtype, True else: if ct_changed: continue else: break error('Unable to extend try block completely') </code></pre> <p><strong><code>isCatchExtendible</code>:</strong></p> <pre><code>def isCatchExtendable(self, newhandler, catchtype): return self.catchset.extendible(newhandler, catchtype, self.currentHandlers) </code></pre> <p>This then calls:</p> <pre><code>#If not extendible with current catchtype, returns suggested type as second arg def extendible(self, newhandler, catchtype, outerhs): if catchtype is None: temp = self.catchsets.get(newhandler) if temp is None: return True, None return False, temp.getSingleTType()[0] proposed = ExceptionSet.fromTops(self.env, catchtype) inner = [h for h in self.handlers if h != newhandler and h not in outerhs] outer = [h for h in self.handlers if h in outerhs] sofar = ExceptionSet.fromTops(self.env) for h in inner: sofar = sofar | self.catchsets[h] if (proposed - sofar) != self.catchsets[newhandler]: #Get a suggsted catch type to try instead suggested = (self.catchsets[newhandler] | sofar).getSingleTType() suggested = objtypes.commonSupertype(self.env, suggested, (catchtype, 0)) assert(self.env.isSubClass(suggested[0], 'java/lang/Throwable')) return False, suggested[0] for h in outer: if not proposed.isdisjoint(self.catchsets[h]): return False, catchtype return True, catchtype </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T15:31:44.010", "Id": "23656", "Score": "0", "body": "Could you share the code or algorithm for isCatchExtendable?, I suspect a better interface for that could help here. But I don't know what its doing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T16:01:32.380", "Id": "23657", "Score": "0", "body": "@Winston I added the code for isCatchExtendable. The basic idea is to determine whether adding another catch handler to a try block will preserve the semantics." } ]
[ { "body": "<p>First off, a pet peeve of mine: <code>while 1</code> makes no semantical sense. You want <code>while True</code>.</p>\n\n<p>However, in your case you actually want <code>while ct_changed</code>:</p>\n\n<pre><code>ct_changed = True\nwhile ct_changed:\n ct_changed = False\n for block in newtry:\n success, newcatchtype = block.isCatchExtendable(newhandler, catchtype)\n if not success:\n if catchtype == newcatchtype:\n break\n else:\n catchtype = newcatchtype\n ct_changed = True\n</code></pre>\n\n<p>Alternatively, you can flatten the nesting level by inverting the <code>if not success</code> conditional, and continuing:</p>\n\n<pre><code> …\n if success:\n continue\n\n if catchtype == newcatchtype:\n break\n\n catchtype = newcatchtype\n ct_changed = True\n</code></pre>\n\n<p>(In fact, I’d probably go for this.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T16:05:00.333", "Id": "23659", "Score": "0", "body": "How do you detect the error condition then? Edit: Nevermind, you can just put the error immediately after the `if catchtype == newcatchtype` instead of breaking." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T16:03:05.340", "Id": "14559", "ParentId": "14556", "Score": "6" } }, { "body": "<p>I think your algorithm suffers from awkward splitting of code. The suggestion logic really should be part of your algorithm, not hidden in some other code.</p>\n\n<p>If I'm understanding correctly, <code>isExtendable</code> really considers three different sets of exception classes</p>\n\n<ol>\n<li>May Catch: These exceptions are caught by handlers before the one of interest, it is safe to catch these as they will already be caught</li>\n<li>Should Catch: These are the exceptions which the given handler should be catching</li>\n<li>Must Not Catch: These are the exceptions which handlers after the one of interest catch. These must not be caught, as that would prevent the current handler from catching them.</li>\n</ol>\n\n<p>We want to pick a single exception type that fulfills the requirement. It must catch everything in Should Catch, some subset of things in May Catch, and nothing in Must Not Catch.</p>\n\n<p>We can combine all May Catch exceptions by taking their intersection across all blocks. Its only safe to catch them if they will already have been caught across all the blocks.</p>\n\n<p>We can combine all the Must Not Catch, by taking their union across all blocks. The should catch, I assume, is the same across all blocks.</p>\n\n<p>Hence your algorithm looks something like:</p>\n\n<pre><code>may_catch = intersection(block.may_catch for block in blocks)\nmay_not_catch = union(block.may_not_catch for block in blocks)\n\nfor catch_type in catch_types.iterparents():\n will_catch = catch_type.catchset()\n if will_catch - may_catch == should_catch and will_catch.isdisjoint(may_not_catch):\n break # found it\nelse:\n error('no type suffices')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:37:32.630", "Id": "23704", "Score": "0", "body": "Nice idea. I didn't think of taking the intersections across multiple blocks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:04:55.387", "Id": "14615", "ParentId": "14556", "Score": "3" } } ]
{ "AcceptedAnswerId": "14615", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T14:58:00.427", "Id": "14556", "Score": "4", "Tags": [ "python" ], "Title": "Checking if blocks are catch extendable" }
14556
<p>I'm currently in the process of learning scala, and I'm looking for some best practices/proper idioms for the use of pattern matching with <code>BigInt</code>s. I'm writing some algorithmic code (for Project Euler) as a way to learn the language.</p> <p>The problem I am running into is what is the best idiomatic way to match a <code>BigInt</code>, since there's a type conversion problem if I try to write <code>case 1 =&gt;</code> and <code>BigInt</code> isn't a <code>case class</code>. Is there a canonical way to do this, or should I just give up and use <code>if</code> statements?</p> <p>The following is one possible pattern:</p> <pre><code>def pollardRho(n: BigInt): BigInt = { val one = BigInt(1) n match { case `one` =&gt; n //additional cases here } } </code></pre> <p>This one just feels wrong: A hack to get around the fact that I can't match it directly, especially with the backticks in there to keep scala from trying to assign the resulting value to <code>one</code> or when I have to do it for more than a single value or in a single case.</p> <p>Another possibility:</p> <pre><code>def pollardRho(n: BigInt): BigInt = { n match { case _ if n == 1 =&gt; n //additional cases here } } </code></pre> <p>This sort of pattern appeals to the Erlang programmer in me, but I have some concerns:</p> <ol> <li>Given the <a href="http://twitter.github.com/effectivescala/#Introduction">warnings I've read not to treat Scala like any other language</a>, I am not sure that my instinct here is not an anti-pattern (or at least considered less readable) in the scala world.</li> <li>It feels like there might be cleaner way to use a custom <code>PartialFunction</code> instead of <code>n match</code> if what I am fundamentally going to do is just a series of tests around <code>n</code>. I am not sure, however, exactly what that would look like (most of the examples of <code>PartialFunction</code>s I've seen don't look quite like this application).</li> </ol> <p>My question is, out of the array of possibilities in scala, which one is the best/most readable/most idiomatic? </p>
[]
[ { "body": "<p>Write your own <a href=\"http://codemonkeyism.com/scala-goodness-extractors/\">extractor</a>:</p>\n\n<pre><code>object Big {\n def unapply(n:BigInt) = Some(n.toInt)\n}\n\n//usage\ndef f(b:BigInt) = b match {\n case Big(0) =&gt; \"none\"\n case Big(1) =&gt; \"one\"\n case _ =&gt; \"many\"\n}\n</code></pre>\n\n<p>Obviously, this isn't the fastest solution, but I think, it's quite idiomatic...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T20:18:46.743", "Id": "23632", "Score": "1", "body": "This also doesn't produce the desired output, since it assumes that I am working with something that can convert to `Int` without overflow, e.g., `BigInt(\"4294967297\")` will match `Big(1)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T21:01:41.807", "Id": "23636", "Score": "0", "body": "The logic in this one might not be 100% correct but extract is definitely the way to go if you want to be able to use match." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-06T14:31:01.417", "Id": "126132", "Score": "0", "body": "I'd use `n.toLong` as you can't write literal number, bigger than `Long`. Besides it's natural to use `String` extractor along with `Long` one, so you could use use `case Big(\"123\") => ` as well." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T20:02:02.427", "Id": "14563", "ParentId": "14561", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T18:40:52.857", "Id": "14561", "Score": "5", "Tags": [ "scala" ], "Title": "Matching BigInts in Scala" }
14561
<p>Is there any room for improvement on this code?</p> <p>I use mechanize to get the links of a job listing web site. There are pages with pagination (when jobs > 25) and pages without.</p> <p>If there is, then the link number 5 is labelled after "Next >" and link number 6 is "Last >>". In order to identify them, I make assertions on their name and act accordingly. I then check how many pages the pagination occurs, and then, taking the numbers, I scrape the pages one by one.</p> <pre><code> def scrape_duty_station agent = Mechanize.new page=agent.get(self.web_link) if page.links[5].text =~ /^next/i pagestart=page.links[5].href.match(/\d+/).to_s.to_i pageend=page.links[6].href.match(/\d+/).to_s.to_i @page=page.links[7...31] scrape_single_page (pagestart..pageend).each do |i| @page=agent.get(self.web_link+"/#{i}") @page=@page.links[7...31] scrape_single_page end else @page=page.links[5...30] scrape_single_page end end def scrape_single_page @page.each do |i| p=Position.new p.title = i.text p.web_link = i.href p.job_id = i.href.match(/\d+/).to_s p.station = Station.where(:web_link =&gt; self.web_link).first p.save end end </code></pre>
[]
[ { "body": "<p>Here are some comments.\n- If you are only @page as a way to communicate with <code>scarpe_single_page</code>, why not make it a parameter?</p>\n\n<pre><code>def scrape_duty_station\n agent = Mechanize.new \n page = agent.get(web_link)\n</code></pre>\n\n<p>Avoid extra indent when one of the cases is simpler and can be dealt with easily.</p>\n\n<p>Also, about your ranges. They should really be named constants.</p>\n\n<pre><code> return scrape_single_page(page.links[5...30]) unless page.links[5].text =~ /^next/i\n arr = [page] + (l_i(page,5)..l_i(page,6)).collect{|i|agent.get(web_link+\"/#{i}\")}\n arr.each {|p| scrape_single_page p.links[7...31] }\n end\n</code></pre>\n\n<p>If you are using any statement more than once, it may be worthwhile to facter it out to a function.</p>\n\n<pre><code> def l_i(page, link)\n page.links[link].href.match(/\\d+/).to_s.to_i\n end\n</code></pre>\n\n<p>Does position have a constructor? If not, it would be nice to create one for it. If yes, it would be better to use it.</p>\n\n<pre><code> def scrape_single_page(pages)\n pages.each do |p|\n Position.new(p.text,p.href,p.href.match(/\\d+/).to_s,\n Station.where(:web_link =&gt; self.web_link).first).save\n end\n end\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T07:48:42.407", "Id": "14574", "ParentId": "14562", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T10:38:50.197", "Id": "14562", "Score": "4", "Tags": [ "optimization", "ruby", "web-scraping" ], "Title": "Web scraper for job listings" }
14562
<p>I've spend the last several hours working on a <code>loop</code> designed to take items in an array and arrange them as a so to speak "gird" of <code>UIButton</code>s. As far as I've been able to see through testing this code works perfectly.</p> <p>However, I am new to creating loops and I was wondering if anyone could give me any pointers on how I could make this code cleaner/more efficient for future coding purposes.</p> <p>I know my question is very similar to <a href="https://codereview.stackexchange.com/questions/13088/optimize-sorting-of-array-according-to-distance-cllocation">Optimize sorting of Array according to Distance (CLLocation)</a>, but I'm really hoping to get some tips on a "per case" basis. Thank you for your time.</p> <pre><code>- (void)myMethod { NSArray *array = [[NSArray alloc] initWithObjects:@"Item #1", @"Item #2", @"Item #3", @"Item #4", @"Item #5", @"Item #6", @"Item #7", @"Item #8", nil]; BOOL leftOkay = NO; BOOL centerOkay = NO; BOOL rightOkay = NO; int left = 0; int center = 1; int right = 2; int yOrigin = 0; int spaceBetweenItems = 5; UIButton *leftButton; UIButton *centerButton; UIButton *rightButton; for (int i = 0; i &lt; [array count]; i++) { if (left &lt; [array count]) { leftButton = [[UIButton alloc] initWithFrame:CGRectMake(spaceBetweenItems, yOrigin + spaceBetweenItems, 100, 150)]; [leftButton setTitle:[array objectAtIndex:left] forState:UIControlStateNormal]; [leftButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [leftButton setBackgroundColor:[UIColor cyanColor]]; [myScrollView addSubview:leftButton]; leftOkay = YES; } if (center &lt; [array count]) { centerButton = [[UIButton alloc] initWithFrame:CGRectMake(110, yOrigin + spaceBetweenItems, 100, 150)]; [centerButton setTitle:[array objectAtIndex:center] forState:UIControlStateNormal]; [centerButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; [centerButton setBackgroundColor:[UIColor yellowColor]]; [myScrollView addSubview:centerButton]; centerOkay = YES; } if (right &lt; [array count]) { rightButton = [[UIButton alloc] initWithFrame:CGRectMake(215, yOrigin + spaceBetweenItems, 100, 150)]; [rightButton setTitle:[array objectAtIndex:right] forState:UIControlStateNormal]; [rightButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal]; [rightButton setBackgroundColor:[UIColor purpleColor]]; [myScrollView addSubview:rightButton]; rightOkay = YES; } if (leftOkay == YES &amp;&amp; centerOkay == YES &amp;&amp; rightOkay == YES) { yOrigin = yOrigin + leftButton.frame.size.height + (spaceBetweenItems * 2); leftOkay = NO; centerOkay = NO; rightOkay = NO; } left = left + 3; center = center + 3; right = right + 3; } myScrollView.contentSize = CGSizeMake(myScrollView.frame.size.width, yOrigin + leftButton.frame.size.height + (spaceBetweenItems * 2)); } </code></pre>
[]
[ { "body": "<p>you can write this code dramatically shorter like </p>\n\n<pre><code>self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];\n\nNSArray *array = [[NSArray alloc] initWithObjects:@\"Item #1\", @\"Item #2\", @\"Item #3\", @\"Item #4\", @\"Item #5\", @\"Item #6\", @\"Item #7\", @\"Item #8\", nil];\n\nNSUInteger buttonWidth = 100;\nNSUInteger buttonHight = 100;\nNSUInteger spacer = 5;\nNSUInteger leftOffset = 5;\nNSUInteger topOffset = 5;\n[array enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {\n int row = idx / 3;\n int column = idx %3;\n\n UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];\n button.frame = CGRectMake((buttonWidth + spacer)*column+leftOffset, (buttonHight+spacer)*row +topOffset , buttonWidth , buttonHight);\n [button setTitle:obj forState:UIControlStateNormal];\n [self.view addSubview:button];\n}];\n</code></pre>\n\n<p><sub><strong>Note:</strong> ARC enabled</sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T15:18:03.713", "Id": "23654", "Score": "0", "body": "edited to have central defined variables" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T16:02:28.840", "Id": "23658", "Score": "0", "body": "If you'd like to have some explanations, just go ahead and ask :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T16:19:18.317", "Id": "23660", "Score": "0", "body": "I appreciate it, my implementation of this is fairly simple, the array is actually a list of image file names 0 to x in NSDocumentsDirectory which .jpg is later appended to. So then I'm linking all the buttons to a void with a UIButton argument so I can pass the currently selected images frame property in order to animate the button/image growing to full screen when it is selected. Would you say this is a good way of doing this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T16:27:00.133", "Id": "23662", "Score": "0", "body": "sounds reasonable to me." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T15:13:52.237", "Id": "14583", "ParentId": "14564", "Score": "2" } } ]
{ "AcceptedAnswerId": "14583", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T20:19:07.370", "Id": "14564", "Score": "1", "Tags": [ "optimization", "performance", "objective-c", "ios" ], "Title": "Efficiency of grid generated by for-in loop" }
14564
<p>I redid a Python Reversi move preview routine that is online. I could use comments about using Python better and/or better OOP design since the original did not use classes. There are three main classes:</p> <ol> <li><code>Board</code> for the Reversi board</li> <li><code>Location</code> to hold an x,y coordinate (0-7,0-7)</li> <li><code>Move</code> to store a location to put a disc on a board and how many discs would be affected by that move</li> </ol> <p>I separated out <code>Move</code> because I would like to keep a sequence of <code>Move</code>s in memory to play forward or reverse. <code>Board</code> knows about where the discs are in two bitfields, one for each player, and knows how to turn over discs and return if a disc is at a location.</p> <pre><code>import unittest import copy from bitarray import bitarray INITIAL_BOARD = """ |_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_| |_|_|_|B|W|_|_|_| |_|_|_|W|B|_|_|_| |_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_| """ def other_player(playerId): return 'B' if playerId == 'W' else 'W' class Location: def __init__(self,x=0,y=0): self.valid = True self.x = x self.y = y self.offset = self.convertToOffset(self.x,self.y) def convertToOffset(self,x,y): if self.valid: self.valid = (x &gt;= 0 and x &lt;= 7 and y &gt;= 0 and y &lt;= 7) return x + y * 8 def translate(self,dx,dy): self.x += dx self.y += dy self.offset = self.convertToOffset(self.x,self.y) def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) class Board: def __init__(self, board=INITIAL_BOARD): self.discs = self.parse_board(board) def make_bitstring(self,board,color_current): other_color = other_player(color_current) def parse_to_bit(square): if square == color_current: return '1' elif square == '_' or square == other_color: return '0' return '' return bitarray(''.join(map(parse_to_bit,board))) def parse_board(self,board): return (self.make_bitstring(board,'B'), self.make_bitstring(board,'W')) def show(self): print self.discs def at(self, location, player): return location.valid and self.discs[int(player=='W')][location.offset] def empty(self, location): return not location.valid or (not self.at (location,'B') and not self.at (location,'W')) def turnoverDisc(self, location): offset = location.offset self.discs[0][offset], self.discs[1][offset] = self.discs[1][offset], self.discs[0][offset] def placeDisc(self, location, player): self.discs[int(player=='W')][location.offset] = 1 def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) class Move: def __init__(self, board, location, color_player): self.location = location self.player = color_player self.board = board self.discDelta = self.makeDiscDelta() def makeDiscDelta(self): result = [] other = other_player(self.player) if not self.board.empty(self.location): return result for dir in [(1,0),(1,-1),(0,-1),(-1,-1),(-1,0),(-1,1),(0,1),(1,1)]: next_location = copy.copy(self.location) next_location.translate(dir[0],dir[1]) dirDelta = [] while self.board.at(next_location,other): dirDelta.append(copy.copy(next_location)) next_location.translate(dir[0],dir[1]) if self.board.at(next_location,self.player): result.extend(dirDelta) return result def makeBoard(self): result = copy.deepcopy(self.board) for location in self.discDelta: result.turnoverDisc(location) result.placeDisc(self.location,self.player) return result class ReversiTest(unittest.TestCase): def testMovePreviewWhite(self): board = Board() location = Location(4,5) move = Move(board,location,'W') self.assertEquals([Location(4,4)], move.discDelta) def testMovePreviewBlack(self): board = Board() location = Location(3,2) move = Move(board,location,'W') self.assertEquals([Location(3,3)], move.discDelta) def testMove(self): board = Board() expected_board = """ |_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_| |_|_|_|B|W|_|_|_| |_|_|_|W|W|_|_|_| |_|_|_|_|W|_|_|_| |_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_| """ expected = Board(expected_board) location = Location(4,5) move = Move(board,location,'W') result = move.makeBoard() self.assertEquals(expected, result) self.assertEquals(board, Board()) self.assertEquals(location, Location(4,5)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T17:56:02.157", "Id": "23664", "Score": "0", "body": "You've combined the _representation_ of the reversi board with the _information_ contained in the board. It's a good idea to separate the two. The board good be represented as a 2d list, and to draw the _representation_ contained in `expected_board` for example, you would have a method called, say `drawBoard(data)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T04:57:44.000", "Id": "23764", "Score": "0", "body": "What I could do to address this is add parser and printer classes for creating a board and display output of the board. I don't completely understand the problem though. The final representation I am planning on is html. expected_board is just for testing." } ]
[ { "body": "<pre><code>import unittest\nimport copy\nfrom bitarray import bitarray\n\nINITIAL_BOARD = \"\"\"\n|_|_|_|_|_|_|_|_|\n|_|_|_|_|_|_|_|_|\n|_|_|_|_|_|_|_|_|\n|_|_|_|B|W|_|_|_|\n|_|_|_|W|B|_|_|_|\n|_|_|_|_|_|_|_|_|\n|_|_|_|_|_|_|_|_|\n|_|_|_|_|_|_|_|_|\n\"\"\"\n\ndef other_player(playerId):\n return 'B' if playerId == 'W' else 'W'\n\nclass Location:\n def __init__(self,x=0,y=0):\n</code></pre>\n\n<p>Put spaces after commas: <code>def __init__(self, x=0, y=0):</code></p>\n\n<pre><code> self.valid = True\n self.x = x\n self.y = y\n self.offset = self.convertToOffset(self.x,self.y)\n\n def convertToOffset(self,x,y):\n</code></pre>\n\n<p>Call it <code>convert_to_offset</code>, in accordance with the rest of this code (and PEP 8).</p>\n\n<pre><code> if self.valid:\n self.valid = (x &gt;= 0 and x &lt;= 7 and y &gt;= 0 and y &lt;= 7)\n</code></pre>\n\n<p>This can be simplified a little using Python's operator chaining: <code>0 &lt;= x &lt;= 7 and 0 &lt;= y &lt;= 7</code>. But why is this method changing <code>self.valid</code>, when it doesn't change <code>self.x</code> or <code>self.y</code>? Make <code>self.valid</code> into a property, and <code>convert_to_offset</code> into a static method.</p>\n\n<pre><code> return x + y * 8\n\n def translate(self,dx,dy):\n self.x += dx\n self.y += dy\n self.offset = self.convertToOffset(self.x,self.y)\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return self.__dict__ == other.__dict__\n else:\n return False\n</code></pre>\n\n<p><code>return NotImplemented</code> instead of <code>False</code> - that way, Python will try (the equivalent of) <code>other.__eq__(self)</code> and only give <code>False</code> if that is also <code>NotImplemented</code>. <code>False</code> means \"I know that these two are not equal\"; <code>NotImplemented</code> means \"I don't know how to compare them\".</p>\n\n<pre><code> def __ne__(self, other):\n return not self.__eq__(other)\n</code></pre>\n\n<p>First, this should be <code>not self == other</code>, because of the same comparison sequence above. But more importantly, this is the <em>default behavior</em> for <code>self != other</code>, so you might as well omit it.</p>\n\n<pre><code>class Board:\n def __init__(self, board=INITIAL_BOARD):\n self.discs = self.parse_board(board)\n\n def make_bitstring(self,board,color_current):\n other_color = other_player(color_current)\n def parse_to_bit(square):\n if square == color_current:\n return '1'\n elif square == '_' or square == other_color:\n return '0'\n return ''\n</code></pre>\n\n<p>Consider moving this function up to module level and passing the colours into it (or, if you really feel like it, use a class for the squares and make this a method on it; but that probably isn't overly worthwhile).</p>\n\n<pre><code> return bitarray(''.join(map(parse_to_bit,board)))\n</code></pre>\n\n<p>Consider using a generator expression, especially if you're in Py2 where <code>map</code> builds a list (at least use <code>itertools.imap</code> there) - but I'm quite sure I'm not alone in finding <code>return bitarray(''.join(parse_to_bit(square) for square in board))</code> more direct and easier to read.</p>\n\n<pre><code> def parse_board(self,board):\n return (self.make_bitstring(board,'B'),\n self.make_bitstring(board,'W'))\n\n def show(self):\n print self.discs \n\n def at(self, location, player):\n return location.valid and self.discs[int(player=='W')][location.offset]\n</code></pre>\n\n<p>Consider putting spaces around the <code>==</code>; but more importantly, there's no need to call <code>int</code> here - bools work fine as sequence indexes (in fact, bool is a subclass of int - you can even add and multiply them).</p>\n\n<pre><code> def empty(self, location):\n return not location.valid or (not self.at (location,'B') and not self.at (location,'W'))\n</code></pre>\n\n<p>Do put spaces between arguments (after the commands), don't between the function name (<code>self.at</code>) and the opening bracket.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T04:55:06.953", "Id": "23763", "Score": "0", "body": "I appreciate the effort. I agree the location class needs to be reorganized and the spacing and case should be fixed. I need to experiment much later to see a difference in changing to a generator in the string parser instead of imap. I will certainly try out the default not equals and remove the int casts." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T15:13:25.250", "Id": "14582", "ParentId": "14568", "Score": "2" } } ]
{ "AcceptedAnswerId": "14582", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T22:47:09.977", "Id": "14568", "Score": "1", "Tags": [ "python", "classes" ], "Title": "Reversi move class" }
14568
<p>I'm doing some coding challenges to get better practiced at my coding. I'm trying to do one that requires us to do a ROT13. I've got the implementation correct, and I just want to know a couple of things.</p> <p>The space character is showing up as a crazy character in my terminal screen, which I'm assuming is because of character encoding, although I could be wrong. Also, how does my code look?</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; const int LOWER_A = 97; const int LOWER_M = 109; const int LOWER_N = 110; const int LOWER_Z = 122; const int UPPER_A = 65; const int UPPER_M = 77; const int UPPER_N = 78; const int UPPER_Z = 90; string rot(string input) { int inputSize = input.size(); int index = 0; while(index != inputSize) { if(input[index] &gt;= LOWER_A &amp;&amp; input[index] &lt;= LOWER_M) input[index] = input[index] + 13; else if(input[index] &gt;= LOWER_N &amp;&amp; input[index] &lt;= LOWER_Z) input[index] = input[index] - 13; else if(input[index] &gt;= UPPER_A &amp;&amp; input[index] &lt;= UPPER_M) input[index] = input[index] + 13; else if(input[index] &lt;= UPPER_N &amp;&amp; input[index] &lt;= UPPER_Z) input[index] = input[index] - 13; index++; } return input; } int main() { string plaintext; string cypher; cout &lt;&lt; "input: "; getline(cin,plaintext); cypher = rot(plaintext); cout &lt;&lt; cypher &lt;&lt; endl; return 0; } </code></pre>
[]
[ { "body": "<p>A few fairly minor things:</p>\n\n<hr>\n\n<p><strong>Constants for the characters</strong></p>\n\n<p>Instead of using the constants, you can just use a character inline:</p>\n\n<pre><code>if(input[index] &gt;= 'a' &amp;&amp; input[index] &lt;= 'm')\n</code></pre>\n\n<p>It's worth noting though that a literal character will be a <code>char</code> rather than an <code>int</code> like your constants are (won't affect anything in this program though).</p>\n\n<hr>\n\n<p><strong><code>using namespace std;</code></strong></p>\n\n<p>It's fine in short programs like this, but as you hinted that you're fairly new to C++, I wanted to mention that this can be a bad habit to get into. In particular, in large applications with many different segments of code, this can cause naming clashes.</p>\n\n<p>This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c\">question</a> on SO addresses the problems it can cause.</p>\n\n<hr>\n\n<p><strong>Naming</strong></p>\n\n<p>I would probably call <code>rot</code>, <code>rot13</code> since there are other kinds of rotations. This is mainly me just being overly picky though :).</p>\n\n<hr>\n\n<p><strong>Strange Character For Space</strong></p>\n\n<blockquote>\n <p>The space character is showing up as a crazy character in my terminal screen, I'm assuming it's because of character encoding, although I could be wrong.</p>\n</blockquote>\n\n<p>rot13 traditionally only operates on alpha characters (a-z and A-Z), so your space characters should not be changing. </p>\n\n<p>I believe your program has a bug in it:</p>\n\n<pre><code>else if(input[index] &lt;= UPPER_N &amp;&amp; input[index] &lt;= UPPER_Z)\n</code></pre>\n\n<p>If this is not a bug, you should know that this will be always be true if <code>input[index] &lt;= UPPER_N</code>, so really there's no point in the second conditional.</p>\n\n<p>Anyway, I think what's happening is that the space character (and anything under 'N') is falling into this block when it shouldn't be.</p>\n\n<p>Space is ASCII 32, so it's getting changed to 19, which is not a printable character.</p>\n\n<hr>\n\n<p><strong><code>while</code> vs <code>for</code></strong></p>\n\n<p>Your loop seems to fit the construct of a <code>for</code> loop very well, so I might consider using that:</p>\n\n<pre><code>for (int inputSize = input.size(), index = 0; index != inputSize; ++index) {\n\n}\n</code></pre>\n\n<p>This comes down to personal preference though.</p>\n\n<hr>\n\n<p><strong>You should usually try to match the return type of a method</strong></p>\n\n<p><code>std::string::size()</code> doesn't return an int; it returns a <code>std::string::size_type</code> which is always (in every implementation I've ever seen anyway), a <code>size_t</code> (which is in turn an unsigned 32 or 64 bit integer depending on the platform and compiler).</p>\n\n<p>Anyway, when working with standard containers (or really APIs in general), unless you have a reason to use a different type, I would try to stick with the return type specified. For example:</p>\n\n<pre><code>for (std::string::size_type len = input.size(), idx = 0; idx != len; ++idx) {\n //input[idx] = ...;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>A potential implementation</strong></p>\n\n<p>I suspect that the if-else tree can be simplified a bit using <code>isalpha</code> and family, but this is what I might implement your algorithm like;</p>\n\n<pre><code>std::string rot13(std::string input) {\n\n for (std::string::size_type len = input.length(), idx = 0; idx != len; ++idx) {\n if (input[idx] &gt;= 'a' &amp;&amp; input[idx] &lt;= 'm') {\n input[idx] = input[index] + 13;\n } else if (input[idx] &gt;= 'n' &amp;&amp; input[idx] &lt;= 'z') {\n input[idx] = input[idx] - 13;\n } else if(input[idx] &gt;= 'A' &amp;&amp; input[idx] &lt;= 'M') {\n input[index] = input[index] + 13;\n } else if(input[idx] &gt;= 'N' &amp;&amp; input[idx] &lt;= 'Z') {\n input[index] = input[index] - 13;\n }\n }\n\n return input;\n\n}\n</code></pre>\n\n<p>To get a little carried away for a moment, you could also implement it using iterators. Using iterators would allow you to apply it to any container that implements iterators (all of the standard containers and plain pointers).</p>\n\n<pre><code>template &lt;typename Iter&gt;\nvoid rot13(Iter begin, const Iter&amp; end) {\n\n while (begin != end) {\n\n //Doesn't need to be here, but I'm lazy and don't like\n //typing *begin over and over again.\n char&amp; c = *begin;\n\n if (c &gt;= 'a' &amp;&amp; c &lt;= 'm') {\n c += 13;\n } else if (c &gt;= 'n' &amp;&amp; c &lt;= 'z') {\n c -= 13;\n } else if (c &gt;= 'A' &amp;&amp; c &lt;= 'M') {\n c += 13;\n } else if (c &gt;= 'N' &amp;&amp; c &lt;= 'Z') {\n c -= 13;\n }\n\n ++begin;\n\n }\n\n}\n</code></pre>\n\n<p>Note that this modifies a container in place rather than creating a copy:</p>\n\n<pre><code>char str[] = \"Hello World\";\nrot13(str, str + strlen(str));\nstd::cout &lt;&lt; str &lt;&lt; std::endl;\nrot13(str, str + strlen(str));\nstd::cout &lt;&lt; str &lt;&lt; std::endl;\n</code></pre>\n\n<p>Would output:</p>\n\n<pre><code>Uryyb Jbeyq\nHello World\n</code></pre>\n\n<p>You could of course modify it to operate on a copy instead though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T12:27:32.553", "Id": "23696", "Score": "0", "body": "“always use braces” – I’m against that. It needlessly clutters the code, and the error you conjure up has *never* happened to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T00:07:06.200", "Id": "23747", "Score": "0", "body": "Konrad, from what I can tell, programmers seem divided on the issue. I agree with you though, it seems cluttery to me. What's generally done on larger projects? You're not seeing the same weird character display in your terminal?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T01:26:26.997", "Id": "23751", "Score": "0", "body": "@KonradRudolph Fair enough. I mostly just prefer the look of it more so than the ability to add more lines in without having to add the braces. I have removed the section though as there's not really a point to it in hindsight." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T01:40:35.727", "Id": "23829", "Score": "0", "body": "@Corbin About namespaces, is it bad practice to use something like 'using std::cout' as opposed to writing 'std::cout' a bunch of times? Thanks a lot for your help, I'm already trying to implement some of this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T02:34:06.333", "Id": "23831", "Score": "0", "body": "@Sir_Blake_ Hopefully someone more knowledgeable than I will comment on this. But anyway, the end goal is to leave the global namespace alone as much as possible. Anytime you think of using a `using` statement, basically ask yourself if the statement will affect anything other than the immediate section you're using it in. For example, `using std::cout;` in a header file unwrapped (not in a class or function) is a bad idea. That will mean that any file that includes that file will also have `std::cout` pulled into the global namespace (though I doubt anyone would ever name anything `cout`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T02:55:17.907", "Id": "23833", "Score": "0", "body": "@Corbin Ok, I got it now. I'll just keep that stuff as localized as possible in the future." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T00:27:53.113", "Id": "14571", "ParentId": "14569", "Score": "6" } }, { "body": "<p>To add to Corbin's reply, always prefer passing immutable input parameter by constant reference, this way you'll protect yourself from unwanted copying of the object which often results in some performance penalties.</p>\n\n<pre><code>std::string rot13(const std::string &amp;input)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T12:28:19.947", "Id": "23697", "Score": "1", "body": "The code copies the string anyway, by design. OP’s way is totally legitimate, and just as efficient." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T11:04:13.270", "Id": "14606", "ParentId": "14569", "Score": "0" } }, { "body": "<p>Like I said elsewhere, avoid loops where possible. This reduces the chance of making off-by-one or buffer overflow errors. C++ offers algorithms for ranges which should be used preferably.</p>\n\n<p>In your case, that’d be <code>std::transform</code>. Combined with C++11 lambdas, this makes the code terse, readable and robust.</p>\n\n<pre><code>std::string rot13(std::string text) {\n std::transform(\n begin(text), end(text), begin(text),\n [] (char c) -&gt; char {\n if (not std::isalpha(c))\n return c;\n\n char const pivot = std::isupper(c) ? 'A' : 'a';\n return (c - pivot + 13) % 26 + pivot;\n });\n return text;\n}\n</code></pre>\n\n<p>Alternatively, this lambda could also be written as a free-standing function but I prefer to keep scope limited, and since the function presumably wouldn’t be used anywhere else and is reasonably short, it’s perfectly suited for a lambda.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T01:12:40.853", "Id": "23828", "Score": "0", "body": "I'll look into the new additions to C++. I'm still trying to grasp the basics first. Thanks for your help!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T12:33:50.890", "Id": "14610", "ParentId": "14569", "Score": "4" } } ]
{ "AcceptedAnswerId": "14571", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T23:07:03.887", "Id": "14569", "Score": "4", "Tags": [ "c++", "caesar-cipher" ], "Title": "ROT13 implementation" }
14569
<p>We're preparing for an exam at the moment, and our lecturer has given us a sample problem to work on. I have it completed, but would like to know a) If it is actually doing what it's supposed to, and b) if it could be done more efficiently or there are any questionable coding aspects. It certainly seems to be working, and GDB tells me the extra threads are definitely bring created. </p> <p>The question:</p> <blockquote> <p>Implement a multithreaded car park simulator in C. One thread should move cars into the car park and another thread should take cars out of the car park (these steps can be simulated by simply inserting integers into/removing integers from a buffer). </p> <p>The capacity of the car park should be supplied as a command line parameter to your program. </p> <p>A monitor thread should periodically print out the number of cars currently in the car park.</p> <p>Requirements:</p> <ul> <li>Implement mutual exclusion where appropriate</li> <li>Do not remove cars from an empty car park</li> <li>Do not add cars to a full car park</li> <li>Avoid busy-waiting</li> <li>Have each producer/consumer thread pause for a random period (up to 1s) between inserting/removing a car</li> <li>Have the monitor thread periodically print out the number of cars currently in the car park</li> </ul> <p>Part 2 - Add one additional producer thread and one additional consumer thread to your solution to Q1. Use <code>pthread_barrier_init</code> and <code>pthread_barrier_wait</code> to ensure that all producer/consumer threads begin producing/consuming at the same time.</p> </blockquote> <pre><code>#include &lt;pthread.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;stdio.h&gt; #define ONE_SECOND 1000000 #define RANGE 10 #define PERIOD 2 #define NUM_THREADS 4 typedef struct { int *carpark; int capacity; int occupied; int nextin; int nextout; int cars_in; int cars_out; pthread_mutex_t lock; pthread_cond_t space; pthread_cond_t car; pthread_barrier_t bar; } cp_t; static void * car_in_handler(void *cp_in); static void * car_out_handler(void *cp_in); static void * monitor(void *cp_in); static void initialise(cp_t *cp, int size); int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: %s carparksize\n", argv[0]); exit(1); } cp_t ourpark; initialise(&amp;ourpark, atoi(argv[1])); pthread_t car_in, car_out, m; pthread_t car_in2, car_out2; pthread_create(&amp;car_in, NULL, car_in_handler, (void *) &amp;ourpark); pthread_create(&amp;car_out, NULL, car_out_handler, (void *) &amp;ourpark); pthread_create(&amp;car_in2, NULL, car_in_handler, (void *) &amp;ourpark); pthread_create(&amp;car_out2, NULL, car_out_handler, (void *) &amp;ourpark); pthread_create(&amp;m, NULL, monitor, (void *) &amp;ourpark); pthread_join(car_in, NULL); pthread_join(car_out, NULL); pthread_join(car_in2, NULL); pthread_join(car_out2, NULL); pthread_join(m, NULL); exit(0); } static void initialise(cp_t *cp, int size) { cp-&gt;occupied = cp-&gt;nextin = cp-&gt;nextout = cp-&gt;cars_in = cp-&gt;cars_out = 0; cp-&gt;capacity = size; cp-&gt;carpark = (int *)malloc(cp-&gt;capacity * sizeof(*cp-&gt;carpark)); pthread_barrier_init(&amp;cp-&gt;bar, NULL, NUM_THREADS); if(cp-&gt;carpark == NULL) { perror("malloc()"); exit(1); } srand((unsigned int)getpid()); pthread_mutex_init(&amp;cp-&gt;lock, NULL); pthread_cond_init(&amp;cp-&gt;space, NULL); pthread_cond_init(&amp;cp-&gt;car, NULL); } static void* car_in_handler(void *carpark_in) { cp_t *temp; unsigned int seed; temp = (cp_t *)carpark_in; pthread_barrier_wait(&amp;temp-&gt;bar); while(1) { usleep(rand_r(&amp;seed) % ONE_SECOND); pthread_mutex_lock(&amp;temp-&gt;lock); //while full wait until there is room available while (temp-&gt;occupied == temp-&gt;capacity) pthread_cond_wait(&amp;temp-&gt;space, &amp;temp-&gt;lock); //insert an item temp-&gt;carpark[temp-&gt;nextin] = rand_r(&amp;seed) % RANGE; //increment counters temp-&gt;occupied++; temp-&gt;nextin++; temp-&gt;nextin %= temp-&gt;capacity; //circular buffer here then temp-&gt;cars_in++; //someone may be waiting on data to become available pthread_cond_signal(&amp;temp-&gt;car); //release the lock pthread_mutex_unlock(&amp;temp-&gt;lock); } return ((void *)NULL); } static void* car_out_handler(void *carpark_out) { cp_t *temp; unsigned int seed; temp = (cp_t *)carpark_out; pthread_barrier_wait(&amp;temp-&gt;bar); for(; ;) { usleep(rand_r(&amp;seed) % ONE_SECOND); //acquire the lock pthread_mutex_lock(&amp;temp-&gt;lock); while(temp-&gt;occupied == 0) pthread_cond_wait(&amp;temp-&gt;car, &amp;temp-&gt;lock); //increment counters temp-&gt;occupied--; temp-&gt;nextout++; temp-&gt;nextout %= temp-&gt;capacity; temp-&gt;cars_out++; //somebody may be waiting on toom to become available pthread_cond_signal(&amp;temp-&gt;space); //release the locl pthread_mutex_unlock(&amp;temp-&gt;lock); } return ((void *)NULL); } static void *monitor(void *carpark_in) { cp_t *temp; temp = (cp_t *)carpark_in; for(; ;) { sleep(PERIOD); //acquire the lock pthread_mutex_lock(&amp;temp-&gt;lock); printf("Delta: %d\n", temp-&gt;cars_in - temp-&gt;cars_out - temp-&gt;occupied); printf("Number of cars in carpark: %d\n", temp-&gt;occupied); //release the lock pthread_mutex_unlock(&amp;temp-&gt;lock); } return ((void *)NULL); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T15:09:42.103", "Id": "23653", "Score": "1", "body": "Looks good. Only issues is your indentation is not consistent (probably because you are mixing tabs a char most companies will tell you to pick one or the other but not to mix). Also be consistent. Here you choose two different methods for infinite loop (choose one and use consistently). Also because the child threads never end rather than try and cleanup in main (added a big error message saying threads have unexpectedly ended)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:48:06.530", "Id": "23705", "Score": "0", "body": "Thank you for the feedback. The indentation I think was me getting the four spaces bit wrong in parts." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:57:29.673", "Id": "23793", "Score": "0", "body": "The code above has changed a lot due to the feedback, the original is here is anyone wants to see it - http://pastebin.com/rbnA2QHK" } ]
[ { "body": "<p>I have a few minor points:</p>\n\n<ul>\n<li><p>put main() last to avoid the need for prototypes.</p></li>\n<li><p>any reason for exit(0) instead of return 0 (or EXIT_SUCCESS) in main() ?</p></li>\n<li><p>in initialise() don't cast the return from malloc()</p></li>\n<li><p>create the barrier after checking carpark for NULL ?</p></li>\n<li><p>use EXIT_FAILURE instead of 1</p></li>\n<li><p>in threads, the name <code>temp</code> is badly chosen. I'd prefer cp or carpark.</p></li>\n<li><p>I'd prefer to see temp initialised immediately, as in <code>cp_t *temp =\ncarpark_in;</code> and note that no cast is needed.</p></li>\n<li><p>is your usleep really random? (note that although the number N returned by rand_r() may\nbe random, it may be unsafe to believe that N%100000 is random)</p></li>\n<li><p>I would put the random sleep into a spearate function</p></li>\n<li><p>what is the purpose of the random value in the carpark[] buffer?</p></li>\n<li><p>cars_in/out seem to be redundant</p></li>\n<li><p>no need to cast return values: ((void*) NULL) should be just NULL</p></li>\n<li><p><code>toom</code> and <code>locl</code> typos in car_out_handler</p></li>\n<li><p>in <code>monitor</code>, 'Delta' is not in the spec</p></li>\n<li><p>various spurious/inconsistent blank lines make code look a little sloppy</p></li>\n<li><p>is it necessary to declare variables away from start of functions? I know\nyou can, but does it help at all?</p></li>\n<li><p>some comments seem like 'noise', eg. 'release the lock'</p></li>\n<li><p>I'd like to see a statement of the problem at the top, along with a statement of any assumptions you have made in the solution</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:49:23.813", "Id": "23706", "Score": "0", "body": "Thank you so much for such a detailed response. I'll work on it and see what I can come up with. Should I edit the code above or just post the newer version in a comment?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T03:20:16.907", "Id": "23759", "Score": "0", "body": "@Saf - probably best to edit it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:42:49.053", "Id": "23788", "Score": "0", "body": "OK. I've edited the code and made most of the changes you mentioned, it's a hell of a lot cleaner now, thank you! Perhaps you could have another quick look at it. \n\nIn response to some of your points - \nI changed exit(0) to return(EXIT_SUCCESS) - I'm assuming this point was about readability and not actual code effect (I did some reading after you mentioned it, return only makes a difference in main in C++ ad far as I can tell)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:43:59.550", "Id": "23789", "Score": "0", "body": "On the whole sleep randomness here, it's not a major issue if it not truly random, it's just so that the program doesn't run one car in, one car out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:44:48.800", "Id": "23790", "Score": "0", "body": "The delta was a remnant of an error check that was in bounded buffer code we were given for direction. I've removed it, and the associated variables in the structure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:50:25.237", "Id": "23791", "Score": "0", "body": "I'm not quite sure what you're looking for with \"I'd like to see a statement of the problem at the top, along with a statement of any assumptions you have made in the solution\" - could you clarify, I thought the explanation at the top was enough, but I'm happy to provide more information." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T20:02:16.720", "Id": "23816", "Score": "1", "body": "Looks a lot nicer now :-) As you say, exit/return from main are equivalent. Regarding comments, your statement of the task would be best included in the C file when you submit the work. By 'assumptions' I meant specifying anything that was not explicitly stated in the task (eg. that you put a random number in the next consecutive position in the buffer for each new car; removing a car does not affect the buffer). One minor point is to validate the value passed in argv[1] in some arbitrary way (again, stated in your assumptions). Also minor, `return (NULL);` is better as `return NULL;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T21:54:57.653", "Id": "23927", "Score": "0", "body": "Thank you so much William, I'm very happy with the result and really like the way code looks now." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T03:31:27.277", "Id": "14599", "ParentId": "14570", "Score": "5" } }, { "body": "<p>In addition to @William Morris' great list of points:</p>\n\n<ul>\n<li><p>For clarity and maintainability, I'd rename <code>ONE_SECOND</code> to specify the applicable unit of time. Depending on the particular time function to be used, you may likely need microseconds or nanoseconds or possibly both. If needed, have a macro for both cases.</p></li>\n<li><p><a href=\"http://linux.die.net/man/3/usleep\" rel=\"nofollow\"><code>usleep()</code> has already been declared obsolete</a> and should be replaced with <code>nanosleep()</code>. Compilation under GNU99 mode may also be necessary.</p></li>\n<li><p>Your loops, mostly the <code>for</code> loops, are lacking indentation for some reason. Since curly braces are still in use, indentation is still necessary. Also, be sure to keep it all consistent. There are some lines in these loops that are misaligned with the others.</p>\n\n<p>In addition, consider using curly braces for single-line loops as well. This can help improve maintainability and avoid some bugs associated with this.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-26T23:23:31.450", "Id": "91871", "ParentId": "14570", "Score": "2" } } ]
{ "AcceptedAnswerId": "14599", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T23:10:45.730", "Id": "14570", "Score": "2", "Tags": [ "c", "multithreading", "homework", "linux", "pthreads" ], "Title": "Producer-consumer in C using pthread_barrier" }
14570
<p>I am trying to learn Mongodb and decided to build a simple blog application using Zend Framework and Mongodb (using <a href="https://github.com/coen-hyde/Shanty-Mongo" rel="nofollow">Shanty for ZF</a>).</p> <p>I have the following document for Post</p> <pre><code>class App_Model_Post extends Shanty_Mongo_Document { protected static $_db = 'blog'; protected static $_collection = 'posts'; protected static $_requirements = array( 'Title' =&gt; 'Required', 'Content' =&gt; 'Required', 'CreatedOn' =&gt; 'Required', 'Author' =&gt; array('Document:App_Model_User', 'Required', 'AsReference'), 'Slug' =&gt; 'Required', ); public function preSave() { $title = $this-&gt;Title; $this-&gt;Slug = strtolower($title); } } </code></pre> <p>Document for Comment:</p> <pre><code>class App_Model_Comment extends Shanty_Mongo_Document { protected static $_db = 'blog'; protected static $_collection = 'comments'; protected static $_requirements = array( 'Content' =&gt; 'Required', 'Author' =&gt; array('Required', 'Document:App_Model_User', 'AsReference'), 'Post' =&gt; array('Required', 'Document:App_Model_Post'), ); } </code></pre> <p>In my controller I do the following to get the Post and Comments for this Post:</p> <pre><code>public function viewAction() { $slug = $this-&gt;_getParam('id'); $post = App_Model_Post::one(array('Slug' =&gt; $slug)); $this-&gt;view-&gt;post = $post; $this-&gt;view-&gt;title = 'Post Title : ' . $post-&gt;Title; $comments = App_Model_Comment::all(array('Post.Slug' =&gt; $post-&gt;Slug))-&gt;skip(0)-&gt;limit(10); $this-&gt;view-&gt;comments = $comments; } </code></pre> <p>I wonder if this is a good way to accomplish this. Is it good practice to reference to Post in the Comment or should I inject Comment documents to Post document?</p>
[]
[ { "body": "<p>The correct answer depends on a few application design decisions.</p>\n\n<p>Reasons why you should embed Comments in Posts:</p>\n\n<ul>\n<li>You have a limit on the number of comments that can be on a post</li>\n<li>The comment limit is relatively small (mongodb docs have a hard limit\nof 4mb but you don't want to be pulling 4mb data down at once, so\nyour limit should take this into consideration)</li>\n<li>You need access to all comments on a post when you load a post</li>\n</ul>\n\n<p>Reasons why you should reference Posts from Comments:</p>\n\n<ul>\n<li>You want to have unlimited comments on a post</li>\n<li>You're ok with loading the post first then going back to the database every time you need comments</li>\n<li>You want to fetch comments without posts</li>\n</ul>\n\n<p>I offer a combined approach. Store comments in their own collection but store a total comments counter and possibly recent comments against the post. This way you can have unlimited comments but still have access to important information when listing posts without having to go back to the database.</p>\n\n<p>I hope this helps</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T08:44:46.050", "Id": "14577", "ParentId": "14576", "Score": "1" } } ]
{ "AcceptedAnswerId": "14577", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T08:17:12.123", "Id": "14576", "Score": "1", "Tags": [ "php", "zend-framework" ], "Title": "Mongodb Post/Comment use case" }
14576
<p>I'm working on my own PHP framework for a long while now. Right now I'm in a refactoring process.</p> <p>I'm came up with the question what a programmer would excpect what happens when he see following code:</p> <pre><code>// working object orientated with a database. $UserGroup = new UserGroupModel(); $UserGroup-&gt;Title = 'Guest'; $UserGroup-&gt;Insert(); // execute sql $User = new UserModel(); $User-&gt;Name = 'Peter'; $User-&gt;UserGroupID = $UserGroup-&gt;UserGroupID; // print all users print_r($UserGroup-&gt;Users); $User-&gt;Insert(); // execute sql // print all users print_r($UserGroup-&gt;Users); </code></pre> <p>Would you expect that <em>$UserGroup->Users</em> imeditaley contains the reference or after the statement <em>$User->Insert();</em>.</p> <p>(Currently it is the second one.)</p> <p>The same with an update statement:</p> <pre><code>// lets pretend we got the $UserGroup1 and $UserGroup2 from the database $User = $UserGroup1-&gt;Users[0]; $User-&gt;UserGroupID = $UserGroup2-&gt;UserGroupID; print_r($UserGroup1-&gt;Users); print_r($UserGroup2-&gt;Users); $User-&gt;Update(); print_r($UserGroup1-&gt;Users); print_r($UserGroup2-&gt;Users); </code></pre> <p>Would you expect that <em>$UserGroup->Users</em> imeditaley contains the changed reference or after the statement <em>$User->Update()</em>. (Currently it is the first one.)</p> <p>Because working with new Objects and already existing ones behave differently I thought it might could be confusing. My suggestion would be that the reference is updated imeditaley.</p> <p>At the moment references for new Objects aren't updated imeditaley because the reference is based on the primary key that doesn't exists yet. It exists after we run <em>Insert()</em>.</p> <p>Maybe I could solve this problem by working internal ids and not database ids.</p> <p><strong>But the real question is, what would you expect what happens (for the references) without reading any documentation?</strong></p> <p><strong>EDIT</strong></p> <p>@showerhead</p> <p>If I got you right, you would consider this as an better way:</p> <pre><code>$UserGroup = new UserGroupModel(); $UserGroup-&gt;Name = "..."; $UserGroup-&gt;Save(); // runs an insert or update sql statement $User = new UserModel(); $User-&gt;Name = "..."; $User-&gt;UserGroupID = $UserGroup-&gt;UserGroupID; $User-&gt;Save(); // runs an insert or update sql statement print_r($UserGroup-&gt;Users); // would be still empty here $UserGroup-&gt;LoadChanges(); // load the changes // now we have the new reference in $UserGroup-&gt;Users print_r($UserGroup-&gt;Users); </code></pre>
[]
[ { "body": "<p>Without reading any documentation, huh? Well let me read you your code as I see it then.</p>\n\n<ol>\n<li>Create new Author</li>\n<li>Give it a name(instead of title? or is that really the book too?)</li>\n<li>Add it to the database.</li>\n<li>Create a new Book</li>\n<li>Give it a title</li>\n<li>Assign it an author using initiated author class</li>\n<li>Print Author's books, which is empty</li>\n<li>Add book to database</li>\n<li>Now, maybe with an update, I would expect Author to have the new book</li>\n</ol>\n\n<p>Your second bit of code is just confusing. Why would you allow your properties to be reassigned? The author isn't going to change. If there are multiple authors, then I would expect you to have a <code>setAuthors()</code> method that accepted an array, or multiple arguments.</p>\n\n<p>Otherwise this looks fine.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Still not sure if I understand, and changing the example didn't help. If anything it confused matters. Don't delete contents or drastically change it. Just add an <strong>Update</strong> or <strong>Edit</strong> section like I've done in my post. Let's see if I can clear up some of these misunderstandings.</p>\n\n<p>Your main question seems to be how I would expect the contents of <code>$UserGroup</code> to be updated. You are right, I originally misunderstood you. So long as I am not misunderstanding you now, this update should help. Anything that caches information, even just temporarily in local scope, I would expect to need to check periodically for updates. Because the content of <code>$UserGroup</code> is \"cached\" (or should be), I would not expect any change to be immediately available to it. That being said, I also would not expect <code>$User</code> to be responsible for this. <code>$User</code> is a completely separate class and should not be concerned with <code>$UserGroup</code> at all. Instead <code>$UserGroup</code> should explicitly request new data from the database when it anticipates that the data may have changed.</p>\n\n<p>Your comment leads me to believe you also would like to know how this update method would look. I think I just explained it, but essentially it will do what you are already doing when you first initialize the object, it should fetch the new data from the database to replace the old. To be efficient, you should have some sort of check to see if any changes were actually made before requesting the new data. In other words, you would reinitialize the object.</p>\n\n<p>Next you ask the same question again, but say you are using a different method from when you first asked the question. I'm assuming this is a typo from when you updated your question, so I'll skip over this.</p>\n\n<p>The problem with updating the <code>$UserGroup</code> immediately, through the <code>$User</code> object, is that the <code>$UserGroup</code> has no control over it. This means that information could change in some other part of the application, and you would never know because you did not expect it. An example of how this might be a problem: Say you have initialized this object and call another method, and, unbeknownst to you, it changes the information in your object. You didn't expect it, so you continue using it and now indices could be messed up and, using the new example you gave, you could be giving out someone's password to a completely different user. This is why I said earlier that <code>$UserGroup</code> should be concerned with its own data, nothing else should touch it. The best way to do this is to just not load the data until after you have already made all the changes you need to make.</p>\n\n<p>The last two statements about referencing the data is just confusing. Of course you should be using internal indices. When you fetch data from a database, it is no longer associated with that database. It will now have its own reference pointers you should use, usually array indices. When its time to update the database with the new data, then you will use references common to both. For instance, in the <code>$UserGroup</code> database, you might use a user's username or ID to reference the proper cell in the database. These are pretty typical primary keys because they are unique.</p>\n\n<p>I hope this better answers your question. I'm sorry I can't help more, but I\"m having difficulties understanding what you are trying to say. I'm assuming because of some language barrier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T17:32:28.533", "Id": "23808", "Score": "0", "body": "It seems like my question wasn't clear enough.\nWhat would you expect what happens to the references.\nThese are the parts I like to know:\n7. Print Author's books, which is empty\n9. Now, maybe with an update, I would expect Author to have the new book\nBut what happends on an update statement?\nI used an Author Book reference to have a simple example.\nYou're right the example isn't very logical." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T17:43:46.997", "Id": "23810", "Score": "0", "body": "I tried to give a better example now. But it is still not the best." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T19:03:08.497", "Id": "23812", "Score": "0", "body": "@roccosportal.com: Updated answer, hope it helps" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T19:36:00.043", "Id": "23814", "Score": "0", "body": "Thank you for this long answer. It's very helpful.\n\nAt the moment in my Framework I'm always working with the same model instance. That means when I'm loading a UserGroup by its ID, the first time the code loads it from the database the second time it gets the reference from the cache.\nSo, yes you're right, the program could change the data from the object instance unbeknownst to me.\nA solution would be that every Model object would be a own instance. On a \"save\" method it would write the object to the database and also the new instance in the cache." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T19:39:49.243", "Id": "23815", "Score": "0", "body": "But what happends when two application parts load same the UserGroup. The first part changes the Title and saves it. The second part (still working with the old instance with the old title) tries to change a different property and tries to save it.\nHow can I prevent that both instances are out of snyc? (Asking theoretically)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T21:08:58.620", "Id": "23819", "Score": "0", "body": "Not an expert, but you will have to perform a time and integrity check. A time check to compare the cached time to the last modified time. If the cache is newer then the data hasn't changed. If its older you will have to perform an integrity check. There are probably better ways to do this all over the internet, but right off the top of my head I would assume you can create a hash of the data before you change it then compare it to the hash of the current contents before you try updating it. If the two hashes aren't the same then its been modified and you should abort." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T21:11:59.007", "Id": "23820", "Score": "0", "body": "@roccosportal.com: Unless two sessions are trying to write to it at the same time, this method should work. In this latter instance you could set it up to use a queue and then compare the times entered into the queue instead of cached. But again, not an expert. I would specifically ask this question on SO for better results. After researching it a bit yourself first though, otherwise they will eat you alive." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T22:01:43.773", "Id": "14637", "ParentId": "14581", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T14:14:32.890", "Id": "14581", "Score": "2", "Tags": [ "php" ], "Title": "Code behaviour: Working object orientated with a database" }
14581
<p>Anonymous functions are one of the best features of C++11. They make everything so beautiful! </p> <p>However, one can get carried away and start overusing them.</p> <p>This code calls a function that reads through a file and invokes a callback everytime that something matches a regex. Since I read two different files but I want callbacks only to differ for a constant, I chose this "lambda-returning-lambda" factory pattern.</p> <pre><code>auto callback_factory = [&amp;] (IPMarkerType start, IPMarkerType stop) -&gt; std::function&lt;void(IPNode&lt;T&gt;&amp;)&gt; { return [&amp;,start,stop](IPNode&lt;T&gt; &amp; node){ markers.push_back(IPMarker&lt;T&gt;(node.ip, start)); markers.push_back(IPMarker&lt;T&gt;(node.ip.network_ones(node.prefix), stop)); }; }; read_regexp&lt;T&gt;("C:\\path\\to\\file1.txt", regex, callback_factory(ipm_a_open,ipm_a_close)); read_regexp&lt;T&gt;("C:\\path\\to\\file2.txt", regex, callback_factory(ipm_b_open,ipm_b_close)); </code></pre> <p>Callbacks are really local just to the calling function, so I think that external functor would not be justified. On the other hand, this code smells a lot to me, so I would like to hear your comments.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T11:50:19.977", "Id": "23693", "Score": "0", "body": "Meh, looks good to me. Just make the `node` argument `const&`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T11:55:12.823", "Id": "23694", "Score": "0", "body": "Any reason you need to declare the return type of the outer lambda?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T17:15:34.100", "Id": "23711", "Score": "0", "body": "@ecatmur Visual Studio 11 wouldn't compile otherwise." } ]
[ { "body": "<p>First of all, I will assume there is something like <code>template &lt;typename T&gt;</code> somewhere in your code. Otherwise, I doubt it would compile.</p>\n\n<p>There is something you could do to improve your program: use <code>emplace_back</code> instead of <code>push_back</code> with an object construction. That way, objects will be created right in the collection (<code>list</code>, <code>vector</code>, etc...). By the way, I'll also assume that <code>markers</code> is a standard collection.</p>\n\n<pre><code>auto callback_factory = \n [&amp;] (IPMarkerType start, IPMarkerType stop) -&gt; std::function&lt;void(IPNode&lt;T&gt;&amp;)&gt;\n{\n return [&amp;,start,stop](IPNode&lt;T&gt; &amp; node){ \n markers.emplace_back(node.ip, start); \n markers.emplace_back(node.ip.network_ones(node.prefix), stop);\n };\n};\n</code></pre>\n\n<p>And, yeah, something still smells: I really wonder how and/or where you declared <code>markers</code>. If it's a global variable, then I think the template parameter may cause some problems.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T12:52:18.793", "Id": "23698", "Score": "0", "body": "I think it’s pretty obvious that this code is just part of a function, which obviates your first and last paragraph." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T12:41:34.797", "Id": "14611", "ParentId": "14588", "Score": "5" } }, { "body": "<p>I suspect I'd hoist the start/stop parameters out, something like this:</p>\n\n<pre><code>template &lt;typename T, typename Markers&gt;\nvoid regex_start_stop_wrapper(char const *path, char const *regex,\n Markers &amp;markers,\n IPMarkerType start, IPMarkerType stop)\n{\n read_regexp&lt;T&gt;(path, regex,\n [&amp;markers,start,stop](IPNode&lt;T&gt; &amp; node)\n { \n markers.push_back(IPMarker&lt;T&gt;(node.ip, start)); \n markers.push_back(IPMarker&lt;T&gt;(node.ip.network_ones(node.prefix), stop));\n }\n );\n}\n\nvoid test()\n{\n // ... original call sites now look like this:\n regex_start_stop_wrapper&lt;T&gt;(\"C:\\\\path\\\\to\\\\file1.txt\", regex,\n markers, ipm_a_open, ipm_a_close);\n regex_start_stop_wrapper&lt;T&gt;(\"C:\\\\path\\\\to\\\\file2.txt\", regex,\n markers, ipm_b_open, ipm_b_close);\n}\n</code></pre>\n\n<p>It just seems like a simpler interaction between the callback, the call site and the <code>read_regexp</code>, somehow. I think it's because this is a straighter call chain, compared to the factory-lambda-returning-a-nested-lambda approach, which is a bit like the world's densest dependency injection.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:05:57.047", "Id": "14624", "ParentId": "14588", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T19:21:48.077", "Id": "14588", "Score": "4", "Tags": [ "c++", "design-patterns", "c++11", "lambda" ], "Title": "C++11 factory pattern with lambdas" }
14588
<p>Is this PDO wrapper structure dynamic? Can using <code>self::</code> rather than <code>$this</code> cause problems?</p> <pre><code>class Database extends PDO { /*@var mixed $stmt Used as a temporary variable to hold queries*/ private $stmt = Null; /*@var $scopeSelectVar Used as a temporary variable to hold queries*/ private $scopeSelectVar = Null; /*@Constructor __construct * * Database __construct ( mixed $db, [ string $serverHost = Null], [ string $dbName = Null], * [ string $dbUser = Null], [ string $password = Null], [ bool $persistent = Null]) * * @access-public */ public function __construct($db, $serverHost = Null, $dbName = Null, $dbUser = Null, $password = Null, $persistent = true) { try { if(is_array($db)) { /* * parent::_construct allows easy instantiation and multiple database connections. * @param mixed $db When array(), var holds all parameters required to connect. * When string, var holds the type of DB to connect to. E.g. mysql * * @param string $serverHost the host of the DB connection * @param string $dbName the name of the database * @param string $dbUser the respective name of the user * @param string $password the password of the user connecting * @param bool $persistent if true, allows connection to persist through the app * */ parent::__construct("{$db['dbType']}:host={$db['Host']}; dbname={$db['dbName']}", $db['dbUser'], $db['dbPassKey'], array( PDO::ATTR_PERSISTENT =&gt; $persistent, )); }//if Var $db == array() then connect using array parameters else { //else connect using all the other function parameters parent::__construct("{$db}:host={$serverHost}; dbname={$dbName}", $dbUser, $password, array( PDO::ATTR_PERSISTENT =&gt; $persistent, )); } /*Uncomment if you have a proper log class*/ Log::write('../AppLogs/databaseConn.log', 'Connection Established at:'); } catch(PDOException $e)/*catching pdo exception and writing it to a file*/ { /*Uncomment if you have a proper log class*/ Log::write('../AppLogs/databaseErrors.log', 'Error:' .$e-&gt;getMessage()); } } /* * @access private * * void defineParamType(string $val) * * */ private function defineParamType($val) { /*@param string $val the update or insert query data passed*/ /*@return const $param the param type constant returned from the function*/ switch($val): case (is_int($val)): $param = PDO::PARAM_INT; break; case (is_string($val)): $param = PDO::PARAM_STR; break; case (is_bool($val)): $param = PDO::PARAM_BOOL; break; case (is_Null($val)): $param = PDO::PARAM_Null; break; default: $param = Null; endswitch; return $param; } /* * @access private * * void insertPrepare(array $bindData) * */ private function insertPrepare($bindData) { /* @param array $bindData Data to be prepared for binding * @return array $insertArray * */ ksort($bindData); $insertArray = array( 'fields' =&gt; implode("`,`", array_keys($bindData)), 'placeholders' =&gt; ':'.implode(',:',array_keys($bindData)), ); return $insertArray; } /* * @access private * * void updatePrepare(array $bindData) * */ private function updatePrepare($bindData) { /* * @param array $bindData Data to be prepared for binding * @return string $placeHolders * */ ksort($bindData); $placeHolders = Null; foreach($bindData as $key =&gt; $val) { $placeHolders .= "`$key`=:$key, "; } $placeHolders = rtrim($placeHolders, ', '); return $placeHolders; } private function where($arguments = array(), $joinKeyword = 'AND') { ksort($arguments); $whereClause = Null; foreach($arguments as $key =&gt; $val) { if(is_int($val)) { $whereClause .= "`$key` = $val {$joinKeyword} "; } else { $whereClause .= "`$key` = '$val' {$joinKeyword} "; } } $whereClause = rtrim($whereClause, ' '.$joinKeyword.' '); $whereClause = "WHERE {$whereClause}"; return $whereClause; } /* * @access public * * void query(string $sql) * */ public function query($sql) { /* * @param string $sql the sql command to execute * */ $this-&gt;scopeSelectVar = NULL; $this-&gt;stmt = parent::query($sql); } /* * @access public * * void insertRow(string $tableName, string $bindData) * * $array = array('field1'=&gt;'field1Value')&lt;-Notice the abscence of ":" * $handler-&gt;insertRow('table', $array) * * */ public function insertRow($tableName, $bindData) { /* * @param string $tableName Name of the table that is inserted into * @param array $bindData array holding the set of column names * respective data to be inserted * */ try { $insertData = self::insertPrepare($bindData); $this-&gt;stmt = parent::prepare("INSERT INTO `{$tableName}` (`{$insertData['fields']}`) VALUES({$insertData['placeholders']})"); foreach($bindData as $key =&gt; $val) { $param = self::defineParamType($val); $this-&gt;stmt-&gt;bindValue(":$key", $val, $param); } $query = $this-&gt;stmt-&gt;execute(); } catch(PDOException $e) { } } /* * @access public * * void updateRow(string $tableName, array $bindData, string $target) * * Way of use: to update * $array = array('field1'=&gt;'field1Value')&lt;-Notice the abscence of ":" * $handler-&gt;updateRow('table', $array, '`field2`='Val'') * */ public function updateRow($tableName, $bindData, $target, $targetClause = 'AND') { /* * @param string $tableName The name of the table you're updating * @param array $bindData array of the values to be inserted. * includes $_POST and $_GET * @param string $target The exact update target. I.e. * WHERE id='?' * */ try { $updateData = self::updatePrepare($bindData); if(isset($target)) { $target = self::where($target, $targetClause); } $this-&gt;stmt = parent::prepare("UPDATE {$tableName} SET {$updateData} {$target}"); foreach($bindData as $key =&gt; $val) { $param = self::defineParamType($val); $this-&gt;stmt-&gt;bindValue(":$key", $val, $param); } $this-&gt;stmt-&gt;execute(); } catch(PDOException $e) { } } /* * @access public * * void deleteRow(string $tableName, string $target) * */ public function deleteRow($tableName, $target) { /* * @param string $tableName table to be deleted from * @param string $target target of the delete query * */ try { return parent::exec("DELETE FROM {$tableName} WHERE {$target}"); } catch(PDOException $e) { } } /* * @access public * * void selectRow(string $fields, string $tableName, string $target) * */ public function selectRow($fields, $tableName, array $target = NULL , $targetClause = 'AND') { /* * @param string $fields the fields of selection. E.g. '`field`,`field2`'... * @param string $tableName The name of the target table * */ if(isset($target)) { $where = self::where($target, $targetClause); }else { $where = Null; } self::query("SELECT {$fields} FROM {$tableName} {$where}"); } /* * @access public * * void fetch([string $singleReturn = false], [constant $fetchMode = PDO::FETCH_OBJ]) * */ public function fetch($singleReturn = false, $fetchMode = PDO::FETCH_OBJ) { /* * @param string $singleReturn the name of the "single" field to be fetching * @param constant $fetchMode The fetch mode in which the data recieved will be stored * @return mixed Null when conditions are not met, stdClass(object) or string when * conditions are met. * */ if(!isset($this-&gt;stmt)){return false;} if($singleReturn == true) { if($this-&gt;scopeSelectVar == false) { $this-&gt;scopeSelectVar = $this-&gt;stmt-&gt;fetch($fetchMode); if(isset($this-&gt;scopeSelectVar-&gt;$singleReturn)) { return $this-&gt;scopeSelectVar-&gt;$singleReturn; }else return false; } }else { $this-&gt;scopeSelectVar = $this-&gt;stmt-&gt;fetch($fetchMode); return (isset($this-&gt;scopeSelectVar)) ? $this-&gt;scopeSelectVar: new StdClass; } } /* * @access public * * void fetchAll([constant $fetchMode = PDO::FETCH_ASSOC]) * */ public function fetchAll($fetchMode = PDO::FETCH_ASSOC) { /* * @param constant $fetchMode Default is PDO::FETCH_ASSOC the mode of fetching data * */ if(!isset($this-&gt;stmt)){return false;} $fetchVar = $this-&gt;stmt-&gt;fetchAll($fetchMode); return (!empty($fetchVar)) ? $fetchVar: new StdClass; } /* * @TODO set a convenient method to quicly setup nested queries * */ public function setSubQuery($target, $subQuery, $mysqlSubQueryHandler) { //mysql nested query handler } /* * @access public * * void rowCount() * */ public function rowCount() { /* * @return numeric $this-&gt;stmt-&gt;rowCount() * */ if(isset($this-&gt;stmt)) { return $this-&gt;stmt-&gt;rowCount(); } } /* * @access public * * void lastId() * * */ public function lastId() { if(isset($this-&gt;stmt)) { return parent::lastInsertId(); } } /* * @access public * * void truncateTable(string $tableName) * */ public function truncateTable($tableName) { /* * @param string $tableName The name of table to be truncated * Notice: truncation will reset the table and delete the data * */ return self::query("TRUNCATE TABLE {$tableName}"); echo "Table {$tableName} Truncated on:".date("d-m-Y h:i:s") ."\n"; } /* * @access public * void debugDumpParams() * * */ public function debugDumpParams() { return $this-&gt;stmt-&gt;debugDumpParams(); } public function rankTable($tableName, $rankableColumn, $orderByColumn, $ascDesc='DESC', $sqlVarName = 'rankNum') { self::query("SET @{$sqlVarName}:= 0"); self::query("UPDATE `{$tableName}` SET {$rankableColumn} =@{$sqlVarName}:=@{$sqlVarName}+1 ORDER BY `{$orderByColumn}` {$ascDesc}"); } public function public function __destruct() { } } </code></pre> <p>I know I probably shouldn't be extending on PDO, but the entire architecture will be redesigned. I just need to make sure the other functions are somewhat nicely coded.</p> <p>This is my first heavy OOP code design. Please criticise.</p>
[]
[ { "body": "<p>When trying to make things like this, it's amazing how quickly it can become complicated and how many OOP ideas and principles can be involved.</p>\n\n<p>Anyway, there's a lot to cover here, so I'm just going to glaze over a few things and may come back and edit more detail in later.</p>\n\n<p>For a \"first heavy OOP code design\" this is pretty good (probably better than the typical first real go at it), but there are a few things that stood out:</p>\n\n<ul>\n<li><code>self::</code> is almost always a bad sign\n<ul>\n<li>It means that a variable is basically a namespaced global</li>\n<li>It means that a method has absolutely nothing to do with the state of an object of the class it belongs to. This can make sense in a few situations, but it is a decision that should be carefully considered unless it's one of the obvious uses.</li>\n<li>Your code is wrong on a technical standpoint because you cannot--well, should not, since PHP is overly lenient--call a non-static method statically. It doesn't make sense. <code>$this</code> and <code>self</code> are <em>not</em> interchangable at all.</li>\n</ul></li>\n<li>Your class is MySQL specific\n<ul>\n<li>Backticks are MySQL specific</li>\n<li>A few other things that I'm too lazy to look back through the code and refind :)</li>\n</ul></li>\n<li>You're mixing concerns with query creation and database connection.\n<ul>\n<li><code>prepare</code>, <code>query</code> etc are fairly low level operations</li>\n<li>creating statements with methods like <code>where</code> is a fairly high level operation\n<ul>\n<li>If you want a DBAL, create a DBAL. A DBAL should have a connection, not be a connection.</li>\n</ul></li>\n<li>People for some reason always want to extend PDO. There are situations where that makes sense, however, 99% of the time, it does not.\n<ul>\n<li>If you want an SQL helper class, then have a class that uses a PDO instance behind the scenes. Don't couple your helper class and your connection class together.</li>\n</ul></li>\n</ul></li>\n<li>You're abusing exceptions\n<ul>\n<li>How does a consumer of your class know that a PDOException occurred? You should almost never eat an exception. If your methods fail, the consuming code probably needs to know.</li>\n</ul></li>\n<li>Your logging is flawed\n<ul>\n<li>If you ever find yourself used a class like <code>C::a();</code> <code>C::b();</code> or if you ever find yourself creating a new object in a method, it's likely a sign that the dependency should be provided by the caller.\n<ul>\n<li>Provides flexibility (what if someone wants to have two instances of your class and use two different loggers?)</li>\n<li>Eases coupling (<code>Database</code> is secretly dependent on <code>PDO</code> -- telling consumers to uncomment the code if they have a logger named <code>Log</code> is not sufficient)</li>\n</ul></li>\n<li>Pass in a logger instead that implements a certain interface\n<ul>\n<li>Allows flexibility like a null logger (a logger that just discards everything) or like having one instance log to a DB table and another to a CSV</li>\n</ul></li>\n<li>Depending how low level your class ends up being, a logger may not belong there.\n<ul>\n<li>What I mean by this is that there's a certain level where logging just doesn't make sense. System calls don't log. Even PDO doesn't log. You should probably handle logging in application-land where the application can have a better feel for how logging should be handled.</li>\n</ul></li>\n</ul></li>\n<li>Your constructor kills flexibility\n<ul>\n<li>SQL Server or Postgres for example, will have much different DSNs than MySQL\n<ul>\n<li>in trying to be overly helpful, your constructor has killed this flexibility -- there's a reason PDO takes a DSN and not the params your constructor takes.</li>\n</ul></li>\n<li>You address persistence, but what about the other attributes?</li>\n</ul></li>\n<li>A few stylist notes (note: these are 100% opinion)\n<ul>\n<li>It's fairly standard to indent to the first level inside of classes</li>\n<li><code>switch:</code> and <code>endswitch;</code> are very rarely used. A lot of people will vehemently argue with me on this one, but I think that the <code>endwhile;</code> <code>endif;</code> and so on constructs are a hideous blotch a on C-esque language.</li>\n<li><code>Null</code> is almost always written either <code>NULL</code> or <code>null</code> in PHP.</li>\n</ul></li>\n</ul>\n\n<p>In short, this is a good start, but you're probably headed down the wrong path with this class. There's a lot of technical and design flaws here that need to be addressed. I would suggest learning the OO syntax a bit more and trying to better familiarise yourself with low level philosophies and ideas of object oriented programming (when I have more time later I'll come back and provide some links).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T05:20:50.467", "Id": "23684", "Score": "0", "body": "Thanks A lot! I really am going to take those remarks and work at improving each and everyone of them. Right now, I am reading a book by Hasin Hayder called \"Publishing Object Oriented Programming with PHP5\".\nI will work on an overhaul of the entire class, and once done, will gladly edit this, or post a new review :)\nThanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T05:11:57.287", "Id": "14600", "ParentId": "14589", "Score": "7" } }, { "body": "<p><strong>On Extending Classes</strong></p>\n\n<p>As Corbin says. It is rarely necessary to extend a predefined class. Think of it like this. You should only \"extend\" a class if you want to add functionality to it. Functionality mean a new feature. This does not mean, usually, redefining the entire class. Using a class is not the same as extending it. In this case you want to \"use\" the class, not \"extend\" it.</p>\n\n<p><strong>Some things about PHPDoc</strong></p>\n\n<p>I don't know how it is treated in other IDE's, but on netbeans (and I'm pretty sure eclipse) your PHPDoc comments do not show up because they are not in the (proper format)[<a href=\"http://www.phpdoc.org/docs/latest/for-users/anatomy-of-a-docblock.html]\" rel=\"nofollow noreferrer\">http://www.phpdoc.org/docs/latest/for-users/anatomy-of-a-docblock.html]</a>. This means the IDE doesn't know what to display when you try to use it, which makes these comments <em>mostly</em> useless. The link should help with any further questions that I don't cover in this section. The way you are currently doing it, it is just treated as a normal comment and therefore ignored. To initiate a PHPDoc comment you MUST use two asterisks <code>/**</code> to open it. A simple search and replace can fix that for you. Also, the \"access\" parameter is unnecessary, that should be documented somewhere on that site I linked you, but they changed it since last I looked and I'm not sure where it is anymore. I also don't think the \"constructor\" parameter is used anymore either, but I can't swear to that one.</p>\n\n<pre><code>/**@var mixed $stmt Used as a temporary variable to hold queries*/\n\n/**allows easy instantiation and multiple database connections.\n *\n * @param mixed $db When array(), var holds all parameters required to connect.\n * When string, var holds the type of DB to connect to. E.g. mysql\n *\n * @param string $serverHost the host of the DB connection\n * @param string $dbName the name of the database\n * @param string $dbUser the respective name of the user\n * @param string $password the password of the user connecting\n * @param bool $persistent if true, allows connection to persist through the app\n *\n * Database __construct ( mixed $db, [ string $serverHost = Null], [ string $dbName = Null],\n * [ string $dbUser = Null], [ string $password = Null], [ bool $persistent = Null])\n *\n */\n</code></pre>\n\n<p>The PHPDoc inside your methods ARE useless. Even if they did have the proper syntax, they would do nothing because they are located in the wrong place and are only making it difficult to read your methods. All of your interior DocBlocks should be combined with their exterior ones. Its also redundant and unnecessary to rewrite parent PHPDoc comments. If the parent class has documentation, the child class inherits that as well as any methods and properties. The only time this becomes an issue is if the child method does something completely different than the parent method, but then you are doing something wrong.</p>\n\n<p>Here's another cool thing about PHP properties/PHPDoc comments. Though this is purely preference, I find it easier to keep my properties together this way :)</p>\n\n<pre><code>private\n /**@var mixed $stmt Used as a temporary variable to hold queries*/\n $stmt = Null,\n\n /**@var mixed $scopeSelectVar Used as a temporary variable to hold queries*/\n $scopeSelectVar = Null\n;\n</code></pre>\n\n<p>Either way, you are definitely better about your documentation than I am. Keep that up and I'll aspire to be more like you :)</p>\n\n<p><strong>Self vs This</strong></p>\n\n<p><a href=\"https://stackoverflow.com/questions/151969/php-self-vs-this\">Here's</a> a link to help illustrate the difference between <code>self::</code> and <code>$this-&gt;</code>. I have a hard time explaining this one, otherwise I would normally translate this for you. The more helpful of the answers, in my opinion, is the second one. But the first answer as well as a few others are pretty good too, they just expect you to already understand some of the more advanced OOP concepts. Corbin had a good explanation, but it seemed somewhat vague. No offense to Corbin, he's a good reviewer, but this is a difficult topic to explain (at least for me).</p>\n\n<p>If you take nothing else from that link, just remember <code>self::</code> is static (as is anything with <code>::</code>) and <code>$this-&gt;</code> is not. You commonly see this syntax in child classes when overriding parent methods where you use the <code>parent::</code> to call the parent's version of that method (or property). So the below snippet, and any others like it, should not use <code>self::</code> because those methods are not static.</p>\n\n<pre><code>$param = self::defineParamType($val);\n</code></pre>\n\n<p><strong>Comments</strong></p>\n\n<p>Endif, endfor, endforeach, etc... All comments along these lines, at least if you have a common IDE, aren't all that helpful. All IDE's, at least all the good ones, have brace matching highlighting, and usually code folding too. Either of these features is usually enough to find the end of a block of code. The comments typically just add noise. So this comment below is unnecessary. In fact, most comments inside methods should be avoided or only used for development.</p>\n\n<pre><code>//if Var $db == array() then connect using array parameters\n</code></pre>\n\n<p><strong>Don't Repeat Yourself (DRY)</strong></p>\n\n<p>Along with many other principles, the DRY principle is a key point of OOP. Another good one is the Single Responsibility Principle, which is something Corbin was driving at. The names usually explain the principle fairly well. In this case, don't have repetitious code. Usually this means creating a function or method or loop. But in this case, it means moving things around and assigning new variables or redefining existing ones. So, for example here is your constructor, rewritten to use this principle.</p>\n\n<pre><code>$persistance = array( PDO::ATTR_PERSISTENT =&gt; $persistent );\n$type = $db;\n\nif( is_array( $db ) ) {\n $type = $db[ 'dbType' ];\n $serverHost = $db[ 'Host' ];\n $dbName = $db[ 'dbName' ];\n\n $dbUser = $db[ 'dbUser' ];\n $password = $db[ 'dbPassKey' ];\n}\n\n$conn = \"$type:host=$serverHost;dbname=$dbName\";\nparent::__construct( $conn, $dbUser, $password, $persistance );\n</code></pre>\n\n<p>Of course, you could use <code>extract()</code> above to an even better effect, but not many people like <code>extract()</code> or its counterpart <code>compact()</code>. The reasoning being that they are difficult to debug for. I believe that so long as the variables expected are being documented and the source is trusted, you should be fine. So the use of these functions are entirely up to you.</p>\n\n<p><strong>Escaping Variables in Strings</strong></p>\n\n<p>You may have noticed in the above section that I did not define <code>$conn</code> the same way you would have. I removed the braces from inside the strings because they are unnecessary. When declaring simple variables inside a string, it is only necessary to use PHP's escape sequence, \"{}\", when the variable name is likely to run into another word. For instance:</p>\n\n<pre><code>\"{$verb}ing\"\n</code></pre>\n\n<p>The only other time it is necessary to use the escape sequence is when using complicated variables. Such as:</p>\n\n<pre><code>\"host={$db[ 'Host' ]}\"\n//OR\n\"host={$this-&gt;host}\"\n</code></pre>\n\n<p>When in doubt, it wont hurt, but it makes it harder to read. Depending on the implementation it is sometimes just better to manually escape these sequences yourself.</p>\n\n<p><strong>Template Language</strong></p>\n\n<p>PHP is sometimes considered a templating language. One of the features that highlights this is the alternative syntax for its statements. For instance <code>if: endif;</code>. The colon and endif are the alternative syntax. Typically this is seen only in templates. So seeing it inside a class is quite odd, especially when not combined with the other alternatives. You should be consistent, and honestly you should only use this format in templates. It's a stylistic choice, but one most of the community agrees with.</p>\n\n<pre><code>switch( $var ) {\n case 1 :\n //contents\n break;\n //etc...\n}\n</code></pre>\n\n<p><strong>Exception Handling</strong></p>\n\n<p>I'm no expert here, but I believe the proper way to do exception handling is merely to throw the exception if one is found then catch it during implementation. So all of these try/catch blocks are unnecessary and redundant.</p>\n\n<p><strong>Conclusion</strong></p>\n\n<p>It was about at this point that I stopped reading. A lot of it appeared to be repeat issues or things Corbin already covered. As Corbin said, this is a good start. Keep up the good work!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T22:58:10.200", "Id": "23743", "Score": "0", "body": "I just need to make clear that the reviewer shouldn't take a look at the entire code and analyze it, just point me to the problems/errors/mistakes standing out :)\n\nI must thank you for the comment advice, I just recently began working with phpdoc for starters and moved in to commenting this code...\nThe \"Don't Repeat Yourself (DRY)\" part is brilliant! I felt stupid there for not thinking of that.\n\nAnd I guess along the lines of OOP I forgot many \"basic\" principals which shouldn't be left out. Many thanks for the awesome review. I am learning so much in here!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T21:43:42.243", "Id": "14636", "ParentId": "14589", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T19:45:27.950", "Id": "14589", "Score": "7", "Tags": [ "php", "object-oriented", "sql", "pdo" ], "Title": "PDO wrapper structure" }
14589
<p>I built my first long running AJAX heavy app and memory leaks are eating me alive. I don't want to post too much code because it should be my job to fix it all, but I need some help.</p> <p>Does this code leak? Where? Why? and if you'd be so kind as to suggest a fix.</p> <pre><code>function list_stuff(data, type, where, order) { var items = []; $.each(data, function (i, item) { items.push( //using jquery $data might make this look more readable '&lt;li data-lat="' + item.lat + '" data-lng="' + item.lng + '" data-type="' + type + '" data-id="' + item.group_id + '" data-privacy="' + item.privacy + '" type = "li"&gt; ' + '&lt;div class ="li_title"&gt;' + item.name + '&lt;/div&gt;' + '&lt;div class ="li_description"&gt;' + item.description + '&lt;/div&gt;' + '&lt;div class ="li_footer"&gt;' + 'Miles: ' + item.distance + ' People: ' + item.people); if (item.privacy != 0) { items.push(' (Private group) '); } if (where == '#thelist') { items.push('&lt;/div&gt;' + '&lt;button data-action ="2" type ="button" class ="join_button" onclick="join_group(this)"&gt;Join&lt;/div&gt;&lt;/li&gt;'); } else if (where == '#thelist2') { items.push('&lt;/div&gt;' + '&lt;button data-action= "4" type ="button" class ="join_button" onclick="join_group(this)"&gt;Leave&lt;/div&gt;&lt;/li&gt;'); } }); if (order === 'append') { $(where).append(items.join('')); } else { $(where).prepend(items.join('')); } scroll.refresh(); } </code></pre> <p>My AJAX looks like this: </p> <pre><code>function ajax(send,where) { $.ajax({ url: where, type: 'POST', dataType: 'json', data: send, success: function(a) { if (a.success===1) { list_stuff(a.data, a.type, '#list1','append'); } else { create_group_problem(a.msg); } if(a.msg.length &gt;1 ) { msg_disp(a.msg); } }, error: function(err){ msg_disp('error'); } }); } </code></pre> <hr> <p>I understand (tenuously) that JavaScript gets garbage collected, but doesn't this form a circular reference that may prevent it from being collected? Please correct me if I'm wrong, but here is my reasoning: </p> <ol> <li><p><code>list_stuff()</code>:</p> <pre><code>'&lt;button data-action ="2" type ="button" class ="join_button" onclick="join_group(this)"&gt;Join&lt;/div&gt;&lt;/li&gt;' </code></pre> <p>JS -> DOM</p></li> <li><p>Generated LI Element:</p> <pre><code>onclick="join_group(this)" </code></pre> <p>DOM ->JS</p></li> </ol> <p>Last question for the sake of learning/understanding: if this is not a circular reference, that will be prevented from being garbage collected, how can I change it to become one? </p> <pre><code>function join_group(block) { var $block = $(block); var pass = 0; var c_id = $block.closest("li").data("id"); var p = $block.closest("li").data("privacy"); var action = $block.data("action"); if(p !== 0 &amp;&amp; action ==3){ pass = prompt("This group requires a password to join."); if (pass === null || pass ==='') { return; } } var send ={ group_id: c_id, group_action: action, privacy:p, password: pass, }; ajax(send, 'group'); } </code></pre>
[]
[ { "body": "<p>javascript is garbage collected, unless you're making huge(tens of MB of XML/JSON) data transfers every couple of seconds and keep references to that data, there should be \"no memory leak\" unless the browser is doing a lousy job.</p>\n\n<p>I would put \"items\" array as global variable so that with each request, you overwrite it, in this way, old data will be discarded, i.e.</p>\n\n<pre><code>// moved globally\nvar items = [];\nfunction list_stuff(data, type, where, order) \n{\n // try to parse data as JSON\n try \n {\n items = jQuery.parseJSON(data);\n var index;\n var item;\n for ( index = 0; index &lt; items.length; index++ )\n {\n item = items[index];\n // do something with \"item\"\n }\n }\n catch(e)\n {\n // handle error here\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T17:42:56.090", "Id": "23716", "Score": "0", "body": "I wouldn't put it global. What if the list_stuff is triggered again while it is still running? Bad idea!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T18:15:21.973", "Id": "23719", "Score": "0", "body": "@ANeves well, javascript is not threaded, so, I fail to see the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T16:19:33.677", "Id": "23807", "Score": "0", "body": "I don't know if execution is interrupted, or if execution of the second call waits for the first to finish, or if they just run concurrently. Either way: if you just want to override it, why not simply setting it to null in the end?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T11:11:10.190", "Id": "14607", "ParentId": "14592", "Score": "1" } }, { "body": "<p>First of all, to answer your questions:</p>\n\n<ol>\n<li>I don't see anything in the code you've posted which would cause a \"memory leak\".</li>\n<li><p>Your reference to <code>join_group</code> inside of your HTML is within a string, and so does not create a reference in the JavaScript code. The browser will create a reference to that function when it is parsed. If you really want to create a reference immediately, you could, after your call to <code>prepend</code> or <code>append</code>, hook up the event handlers using jQuery with something like:</p>\n\n<pre><code>$('.join_button').on('click', join_group);\n</code></pre>\n\n<p>If you do that, you'll need to change the start of <code>join_group</code> to:</p>\n\n<pre><code>function join_group() {\n var $block = $(this);\n</code></pre>\n\n<p>You'll want to remove the <code>onclick=\"join_group(this)\"</code> from the HTML as well.</p></li>\n</ol>\n\n<p>On a different note, you can speed up your code by not concatenating strings you're pushing into an array and joining anyway. In other words, replace all of the <code>+</code>s inside a <code>push()</code> with a <code>,</code>. You won't see much of a speed difference though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T19:32:33.727", "Id": "14716", "ParentId": "14592", "Score": "1" } } ]
{ "AcceptedAnswerId": "14716", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T00:07:03.587", "Id": "14592", "Score": "2", "Tags": [ "javascript", "jquery", "memory-management", "ajax" ], "Title": "Possible leak in heavy app" }
14592
<p>I have followed the TGA specs described <a href="http://local.wasp.uwa.edu.au/~pbourke/Dataformats/tga/" rel="nofollow">here</a> (the info at the end of the page is what this method is based on) and have written a method that takes a TGA file's pixel data section and creates a bitmap out of it.</p> <p>It works, but the code looks sloppy. Particularly, when I'm actually reading the bytes. You'll notice that I do some sort of odd <code>foreach</code> loop in order to repeatly add the same bytes to my array.</p> <p>Here's the method that reads the pixels. It returns an array of bytes representing the pixels.</p> <p>Is there a way for me to re-write the inner loop in the <code>128</code> case to NOT use a foreach in order to set the same sequence of bytes to an array? I imagine I will find myself putting bytes into an array often and it would be nice to know other ways to do it.</p> <pre><code>private byte[] getImageType10() { // header stores total bits per pixel int bytesPerPixel = header.bpp / 8; int total = header.width * header.height * bytesPerPixel; // number of bytes we've read so far int count = 0; int repeat; byte packetHdr; int packetType; // temp storage byte[] bytes; byte[] pixData = new byte[total]; while (count &lt; total) { packetHdr = inFile.ReadByte(); packetType = packetHdr &amp; (1 &lt;&lt; 7); // RLE packet if (packetType == 128) { // packet stores number of times following pixel is repeated repeat = (packetHdr &amp; ~(1 &lt;&lt; 7)) + 1; bytes = inFile.ReadBytes(bytesPerPixel); for (int j = 0; j &lt; repeat; j++) { foreach (byte b in bytes) { pixData[count] = b; count += 1; } } } // raw packet else if (packetType == 0) { // packet stores number of pixels that follow repeat = ((packetHdr &amp; ~(1 &lt;&lt; 7)) + 1) * bytesPerPixel; for (int j = 0; j &lt; repeat; j++) { pixData[count] = inFile.ReadByte(); count += 1; } } } return pixData; } </code></pre>
[]
[ { "body": "<p>The 128 case can be optimized as:</p>\n\n<pre><code> if (packetType == 128) \n { \n // packet stores number of times following pixel is repeated \n repeat = (packetHdr &amp; ~(1 &lt;&lt; 7)) + 1; \n bytes = inFile.ReadBytes(bytesPerPixel);\n for (int j = 0; j &lt; repeat; j++) \n {\n bytes.CopyTo(pixData, count);\n count += bytes.Length;\n }\n } \n</code></pre>\n\n<p>The 0 case can be optimized as:</p>\n\n<pre><code> if (packetType == 0) \n { \n // packet stores number of pixels that follow \n repeat = ((packetHdr &amp; ~(1 &lt;&lt; 7)) + 1) * bytesPerPixel;\n bytes = inFile.ReadBytes(repeat);\n bytes.CopyTo(pixData, count);\n count += bytes.Length;\n } \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T04:01:18.243", "Id": "23676", "Score": "0", "body": "Thanks, I have to look at what Array class provides! Though, guess I should check whether it's actually faster or not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T04:04:35.583", "Id": "23677", "Score": "0", "body": "It really should be faster :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T03:57:38.837", "Id": "14594", "ParentId": "14593", "Score": "4" } }, { "body": "<p>My answer is heavily based on that by @WouterH, so if you upvote me, then you must upvote Wouter twice. What I did is provided a \"full\" code listing, cleaned up some variable names and comments (many comments were removed after the proper variable names were used), added a class for the image header and added the placeholder for the error checking. I am not too happy with the magic constant <code>positiveMask</code> because I do not fully understand what it does. You could replace code contracts with exceptions in order to use fewer assemblies. You can speed the code up a bit by pre-computing some variables in the ImageHeader class once. Other improvements are possible, but we have not seen your entire code, so it is hard to tell. I would also split up this one file into two different ones - one per class.</p>\n\n<pre><code>namespace TGAImageParser\n{\n using System;\n using System.Diagnostics.Contracts;\n using System.IO;\n\n // Using a class like this helps to avoid http://c2.com/cgi/wiki?DataEnvy\n internal class TGAImageHeader\n {\n public const int BitsInByte = 8; // const is ok over readonly here since this will not change in the future, right?\n\n public readonly int BytesPerPixel;\n public readonly int Width;\n public readonly int Height;\n\n public TGAImageHeader(int bytesPerPixel, int width, int height)\n {\n // Check the inputs thoroughly here.\n Contract.Requires(width &gt; 0, \"Image must be at least one pixel wide.\"); // Or is it zero pixels wide?\n // ... and so on.\n\n this.BytesPerPixel = bytesPerPixel;\n this.Width = width;\n this.Height = height;\n }\n\n public int BitsPerPixel\n {\n get\n {\n return this.BytesPerPixel * BitsInByte;\n }\n }\n\n // If this gets called often, then pre-compute it once.\n public int TotalBytes\n {\n get\n {\n return this.BytesPerPixel * this.TotalPixels;\n }\n }\n\n // If this gets called often, then pre-compute it once.\n public int TotalPixels\n {\n get\n {\n return this.Width * this.Height;\n }\n }\n }\n\n public class TGAImageParser\n {\n public const int RLEPacketType = 128;\n public const int RawPacketType = 0;\n\n private const byte positiveMask = 1 &lt;&lt; 7; // TODO: Come up with a better name! What does it do?\n\n public static byte[] GetImageType10Bytes(BinaryReader inFile, TGAImageHeader imageHeader)\n {\n int numBytesReadSoFar = 0;\n int numTimesPixelIsRepeated;\n byte packetHeaderByte;\n int packetType;\n\n byte[] tempStorageBuffer;\n byte[] pixData = new byte[imageHeader.TotalBytes];\n\n while (numBytesReadSoFar &lt; imageHeader.TotalBytes)\n {\n packetHeaderByte = inFile.ReadByte();\n packetType = packetHeaderByte &amp; positiveMask;\n\n if (packetType == RLEPacketType)\n {\n numTimesPixelIsRepeated = (packetHeaderByte &amp; ~positiveMask) + 1;\n tempStorageBuffer = inFile.ReadBytes(imageHeader.BytesPerPixel);\n for (int i = 0; i &lt; numTimesPixelIsRepeated; i++)\n {\n tempStorageBuffer.CopyTo(pixData, numBytesReadSoFar);\n numBytesReadSoFar += tempStorageBuffer.Length;\n }\n\n continue;\n }\n\n if (packetType == RawPacketType)\n {\n numTimesPixelIsRepeated = ((packetHeaderByte &amp; ~positiveMask) + 1) * imageHeader.BytesPerPixel;\n tempStorageBuffer = inFile.ReadBytes(numTimesPixelIsRepeated);\n tempStorageBuffer.CopyTo(pixData, numBytesReadSoFar);\n numBytesReadSoFar += tempStorageBuffer.Length;\n\n continue;\n }\n\n // TODO: report an error here?\n }\n\n return pixData;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T19:29:56.553", "Id": "23915", "Score": "0", "body": "Yes, I defined a separate header class because it seemed like something nice to do, but I wasn't sure how to justify it. The `positiveMask` is just used because the format uses the high-order bit to identify the packet type and the rest of the bits to store a number. I didn't think about setting it as a const though and that would avoid having to compute it again and again when it's always the same value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T19:50:37.213", "Id": "23917", "Score": "0", "body": "I see ... this should execute a bit faster but it is harder to understand. I like using something like: http://stackoverflow.com/questions/2431732/checking-if-a-bit-is-set-or-not\nSince there is only one bit that drives this, you do not need to have two separate if statements. You could do `if(cond) { <doSmthIfYes> return;} <doSmthIfNo>` instead of `if (...) {...} else {...}` but it is just a matter of preference; either one will execute fast enough." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:14:53.370", "Id": "14628", "ParentId": "14593", "Score": "3" } } ]
{ "AcceptedAnswerId": "14594", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T03:37:04.713", "Id": "14593", "Score": "2", "Tags": [ "c#" ], "Title": "Refactoring a TGA image parser" }
14593
<p>I want to get just the first line of a big string. Currently, here's how I do it:</p> <pre><code>def getFirstParagraph(txt: String) = { val newLineIdx = txt.indexOf("\n") match { case i: Int if i &gt; 0 =&gt; i case _ =&gt; txt.length } txt.substring(0, newLineIdx) } </code></pre> <p>But my friend sees some downfall: if <code>txt</code> is <code>null</code>, there will be an exception. His suggestion involved using <code>var</code>:</p> <pre><code>def getFirstParagraph(txt: String) = { var result = txt scala.util.control.Exception.ignoring(classOf[Exception]) { result = result.substring(0, result.indexOf("\n")) } result } </code></pre> <p>Which will handle the <code>null</code> value fine. Thing is, I'm quite uncomfortable using <code>var</code>. How can I handle this case without using <code>var</code> (aka the Scala / functional way)?</p>
[]
[ { "body": "<pre><code>scala&gt; def getFirstParagraph(txt: String) = {\n Option(txt).map(_.takeWhile(c =&gt; c != '\\n')).orNull\n }\ngetFirstParagraph: (txt: String)String\n\nscala&gt; getFirstParagraph(null)\nres2: String = null\n\nscala&gt; getFirstParagraph(\"fsdfasf\")\nres3: String = fsdfasf\n\nscala&gt; getFirstParagraph(\"fsdfasf\\nxxxxxxx\")\nres4: String = fsdfasf\n</code></pre>\n\n<p><code>Option(txt)</code> converts <code>txt</code> into an <code>Option[String]</code> which will be <code>None</code> if <code>txt</code> is null.</p>\n\n<p><code>map</code> will execute the <code>takeWhile</code> only if the <code>Option</code> is <code>Some</code>. </p>\n\n<p>Finally <code>orNull</code> will pull the value out of the <code>Option</code> if it is <code>Some</code> or evaluate to <code>null</code> otherwise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T04:03:22.217", "Id": "23682", "Score": "0", "body": "This gives me a warning: \"<console>:9: warning: comparing values of types Char and java.lang.String using `!=' will always yield true\" on Sacla 2.9.2, also the code didn't work..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T04:08:31.710", "Id": "23683", "Score": "0", "body": "Nevermind, silly mistake. I tested against `\"\\n\"`, not `'\\n'`. Sorry." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T03:03:35.927", "Id": "14598", "ParentId": "14596", "Score": "10" } }, { "body": "<p>Here's my take on it:</p>\n\n<pre><code>def getFirstParagraph(txt: String): String = txt.lines.next\n</code></pre>\n\n<p>As to the <code>null</code> objection: in idiomatic Scala, you don't use <code>null</code>. If there's some API which might return you a <code>null</code> string, then, <em>at that point</em>, you turn it into an <code>Option</code>, and handle the <code>Option</code> elsewhere as needed.</p>\n\n<p>Handling <code>null</code> (or even <code>Option</code>) at the <code>getFirstParagraph</code> method is misplaced.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T23:00:34.270", "Id": "23744", "Score": "0", "body": "I agree on the misplaced responsabilities note." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T03:19:20.193", "Id": "23758", "Score": "0", "body": "Good point, I agree." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T13:52:31.277", "Id": "14614", "ParentId": "14596", "Score": "12" } }, { "body": "<p>ericacm's code may be shortened (removing explicit lambda notation). Also, propagating <code>null</code> is a bad/dangerous thing (unless you are forced to stay close to the metal, but then how about writing in C), so why not return an <code>Option</code>?</p>\n\n<pre><code>def getFirstParagraph(txt: String) = {\n Option(txt).map(_.takeWhile(_ != '\\n'))\n}\n</code></pre>\n\n<p>Or, if you don't use this from Java, testing for <code>null</code> is kinda weird, as in pure world there is no <code>null</code>. So there is:</p>\n\n<pre><code>def getFirstParagraph(txt: String) = {\n txt.takeWhile(_ != '\\n')\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-17T15:12:33.487", "Id": "29860", "Score": "1", "body": "In the second case map call is excess." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-22T20:26:02.423", "Id": "15837", "ParentId": "14596", "Score": "5" } } ]
{ "AcceptedAnswerId": "14598", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T01:52:15.360", "Id": "14596", "Score": "6", "Tags": [ "strings", "functional-programming", "scala", "exception-handling" ], "Title": "A safer way to cut a string" }
14596
<p>Trying to come up with a way to have a fixed space (eg <code>20px</code>) between two blocks on a single line which dynamically resize to fit that line (<code>50%</code> each minus the fixed space between).</p> <p>I ended up with the <a href="http://jsfiddle.net/XfStv/" rel="nofollow">following code (demo)</a>:</p> <p>HTML:</p> <pre><code>&lt;div class="cont"&gt; &lt;div class="left"&gt;foo&lt;/div&gt; &lt;div class="right"&gt;bar&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.cont{ outline: 3px solid #ddd; position: relative; height: 50px; } .cont div{ border: 1px solid #f0f; background: #fef; height: 40px; position: absolute; top: 0; } .left{ left: 0; right: 50%; margin-right: 10px; } .right{ left: 50%; right: 0; margin-left: 10px; } </code></pre> <p>Is this a common or a good way to do it? Are there other or better ways (which work in <code>IE &gt;= 7</code>).</p> <p>Tested successfully in IE8 &amp; IE9, and latest versions of Chrome, Firefox, and Opera.</p>
[]
[ { "body": "<p>I guess this is the proper way to have fixed space between to half-fitted blocks, but maybe later you'll have small issuer with container DIV, because child elements are absolute position and parent - relative, so it will not follow heights of child elements. </p>\n\n<p>for example: <a href=\"http://jsfiddle.net/XfStv/3/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/XfStv/3/</a> </p>\n\n<p>.</p>\n\n<p><strong>------UPDATE------</strong></p>\n\n<p>You can also use table property for objects, but it's not supported by IE 7:\n<img src=\"https://i.stack.imgur.com/RxKg9.png\" alt=\"Browser Support Table\"></p>\n\n<p>here is example of tabled version code: <a href=\"http://jsfiddle.net/zur4ik/ehGRk/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/zur4ik/ehGRk/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T11:42:44.323", "Id": "23692", "Score": "0", "body": "Yea, but thankfully height is fixed in this case. Otherwise it would be more difficult. (Can't see an obvious solution to that. Tables?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T07:19:49.130", "Id": "23839", "Score": "0", "body": "you can use also tables version if you want: _see updated answer_." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T09:47:09.763", "Id": "14605", "ParentId": "14602", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T07:14:31.913", "Id": "14602", "Score": "1", "Tags": [ "html", "css" ], "Title": "Fixed space between two dynamically sized blocks" }
14602
<p>I have written some code for finding a level in a binary tree, having a maximum number of elements. I have a few questions:</p> <ol> <li>Is it a good design? I have used 2 queues but the total sum of elements both queues store will be less than n. So I think it should be OK.</li> <li>Can there be a better design?</li> </ol> <hr> <pre><code> public class MaxSumLevel { public static int findLevel(BinaryTreeNode root) { Queue mainQ = new Queue(); Queue tempQ = new Queue(); int maxlevel = 0; int maxVal = 0; int tempSum = 0; int tempLevel = 0; if (root != null) { mainQ.enqueue(root); maxlevel = 1; tempLevel = 1; maxVal = root.getData(); } while ( !mainQ.isEmpty()) { BinaryTreeNode head = (BinaryTreeNode) mainQ.dequeue(); BinaryTreeNode left = head.getLeft(); BinaryTreeNode right = head.getRight(); if (left != null) { tempQ.enqueue(left); tempSum = tempSum + left.getData(); } if (right != null) { tempQ.enqueue(right); tempSum = tempSum + right.getData(); } if (mainQ.isEmpty()) { mainQ = tempQ; tempQ = new Queue(); tempLevel ++; if (tempSum &gt; maxVal) { maxVal = tempSum; maxlevel = tempLevel; tempSum = 0; } } } return maxlevel; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T10:57:54.223", "Id": "23688", "Score": "1", "body": "This looks pretty complex. What’s the “level” (since you are obviously not using the usual definition by returning an `int`)? Does it correspond to the depth of a node? If so, there’s a much simpler solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T17:05:53.363", "Id": "23710", "Score": "0", "body": "@Konrad, yes level means depth. Thanku" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T23:52:57.197", "Id": "23746", "Score": "2", "body": "You definitely over-complicated things. Simpler solutions do exist.\n\nhttp://www.leetcode.com/2010/04/maximum-height-of-binary-tree.html http://stackoverflow.com/questions/9323036/tail-recursive-function-to-find-depth-of-a-tree-in-ocaml \n\nNote that you could change the data structure such that it keeps the depth of every node as well as the max depth (or better yet, a reference to the deepest node) at all times. This will result in a bit more space, a bit more time, but will make your problem very easy - a simple `O(1)` function call." } ]
[ { "body": "<p>My initial criticism is that your method doesn't have javadoc comments that state <em>clearly and unambiguously</em> what the method is supposed to do. </p>\n\n<p>Why am I saying that?</p>\n\n<p>Well, mainly because your Question has exactly the same problem! You say:</p>\n\n<blockquote>\n <p>I have written some code for finding a level in a binary tree, having a maximum number of elements.</p>\n</blockquote>\n\n<p>This is bad description of what you are (apparently) trying to do:</p>\n\n<ul>\n<li>The word \"level\" usually refers to the distance of a node from (say) the root of a tree. But you apparently mean the \"height\" of the entire tree.</li>\n<li>The phrase \"having a maximum number of elements\" is unclear. What are you talking about? How does this affect the problem? (I don't see a maximum number of elements parameter ... or any reference to this in your code.)</li>\n</ul>\n\n<p>So why does this matter?</p>\n\n<p>Because I (the reader) should not have to read through your code to try to figure out the problem you are trying to solve. Especially if your implementation is non-obvious ... which it is ... and possibly contains mistakes that might lead me to think it is solving a different problem than you are actually trying to solve.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T04:33:30.237", "Id": "17516", "ParentId": "14603", "Score": "2" } }, { "body": "<p>First, I notice that you are not using generics; I would prefer <code>Queue&lt;BinaryTreeNode&gt;</code> over simply <code>Queue</code>.<br>\nYou could use the standard Java <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Queue.html\" rel=\"nofollow\">Queue interface</a>. The <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html\" rel=\"nofollow\">LinkedList implementation</a> should provide all you need for this snippet. </p>\n\n<p>Second, I'm a little surprised that you use iteration; a recursive solution would be a lot more intuitive, and is almost exactly the same as what you would get if you were to use a <code>Stack</code> instead of a <code>Queue</code>. And it looks like changing from <code>Queue</code> to <code>Stack</code> would not change the result of the computation.</p>\n\n<p>It looks like you are both calculating <code>maxLevel</code> and <code>maxVal</code>, but only returning <code>maxLevel</code>. Trying to calculate both smells like premature optimization; I would prefer to write separate methods for these calculations.<br>\nDrifting somewhat off-topic, but Java 8 is scheduled to have lambda expressions, so you might then be able to have one tree traversal method and pass it appropriate lambda expressions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T18:03:57.233", "Id": "17528", "ParentId": "14603", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T07:55:39.310", "Id": "14603", "Score": "4", "Tags": [ "java", "algorithm", "queue" ], "Title": "Binary tree max sum level - better design?" }
14603
<p>I need to create an image on the fly where one large image covers a small image. The large image is a mask which makes the underlying image visible. Here is a quick sketch of what I'm trying to accomplish: </p> <p><a href="https://i.stack.imgur.com/TTf4P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TTf4P.png" alt="enter image description here"></a><br /> It's important that Y lies beneath X.</p> <p>I have created to code for this and it works, but I was wondering how I can make the code more efficient. This is what I have:</p> <pre><code> // Create a blank image with the underlying image correctly positioned $blank = imagecreatetruecolor(403, 403); $profile = imagecreatefromjpeg('img.jpg'); $w = imagesx($profile); $h = imagesy($profile); imagecopy($blank, $profile, 0, 140, 0, 0, $w, $h); imagejpeg($blank, 'tmp.jpg', 100); // Frame overlay $frame = imagecreatefrompng('frame.png'); $photo = imagecreatefromjpeg('tmp.jpg'); imagecopy($photo, $frame, 0, 0, 0, 0, 403, 403); imagejpeg($photo, 'output.jpg', 100); // Garbage collection unlink('tmp.jpg'); imagedestroy($blank); imagedestroy($profile); imagedestroy($frame); imagedestroy($photo); </code></pre> <p>I just think that creating 2 different images is just overkill, but I just can't find a better solution. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T13:04:46.827", "Id": "23700", "Score": "0", "body": "How long does your code take to run? Would there be any benefit in finding another method? (In other words, are you trying to over-optimise?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T13:15:13.187", "Id": "23701", "Score": "0", "body": "Well, the code runs pretty fast. It's just that I'd like to know if the final image could be created with only 1 imagecopy call (or with something else). I'll post this question on the codereview page you gave me Aleks, thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:11:19.677", "Id": "23722", "Score": "0", "body": "First off, a disclaimer: I've never used any of these functions before. But it seems to me that instead of recreating the same base image every time, it might be better to create a permanent one in a \"template\" directory, then load it whenever you need it. Then you can make what ever changes you need and save it to the permanent directory. But this is all speculation." } ]
[ { "body": "<p>First of all don't save your temporary file as tmp.jpg, think about what happends if there are 2 requests for an image at the same time, the first tmp.jpg will be overwritten by the second one (very unlikely, but still possible and very hard to debug / reproduce bug)..</p>\n\n<p>Second saving to the disk is expensive and useless, avoid it whenever possible.</p>\n\n<p>Third why do you need the blank image? I think you should have the frame image and overlay the profile image on top of it.</p>\n\n<p>Given this, I think the code should look like this:</p>\n\n<pre><code>// Create a blank image with the underlying image correctly positioned\n$base = imagecreatefrompng('frame.png');\n$profile = imagecreatefromjpeg('img.jpg');\n$w = imagesx($profile);\n$h = imagesy($profile);\nimagecopy($base, $profile, 0, 140, 0, 0, $w, $h);\n\nimagejpeg($base, 'output.jpg', 100);\n\n// Garbage collection\nimagedestroy($base);\nimagedestroy($profile);\n</code></pre>\n\n<p>Unless I miss something this code should do exactly the same thing, but faster and safer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T08:08:56.833", "Id": "14824", "ParentId": "14612", "Score": "2" } } ]
{ "AcceptedAnswerId": "14824", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-08-13T13:00:08.513", "Id": "14612", "Score": "3", "Tags": [ "php" ], "Title": "Dynamic image using PHP" }
14612
<p>I watched <a href="http://www.youtube.com/watch?v=mtvoOIsN-GU" rel="nofollow">this live coding of Sokoban</a> in Haskell and thought I'd take a crack at writing it using State and lenses, since I've never tried that before. My problem is that the control flow seems to be complicated by <code>isWall</code> and friends now being monadic values that I need to unwrap, so I can't use the otherwise obvious approach of guards etc. Any suggestions? I did not focus very much on not making partial functions or handling IO properly, what interests me is how to manage the data and control flow cleanly. Note that I should have also not set default values for <code>_wWorker</code> and <code>_wMax</code>.</p> <p>The worst culprits are <code>move</code>, <code>toChar</code> and <code>setMaxCoords</code>.</p> <p>EDIT: Because of the way values are in State, I have a series of functions:</p> <pre><code>isWall :: MonadState World m =&gt; Coord -&gt; m Bool isWall c = use $ wWalls.contains c isCrate :: MonadState World m =&gt; Coord -&gt; m Bool isCrate c = use $ wCrates.contains c isStorage :: MonadState World m =&gt; Coord -&gt; m Bool isStorage c = use $ wStorage.contains c isWorker :: MonadState World m =&gt; Coord -&gt; m Bool isWorker c = uses wWorker (==c) </code></pre> <p>These, I feel, are all fine, but they end up being less than useful in practice, because of the fact that the Bool is wrapped. The unwrapping process becomes very tedious in several functions:</p> <pre><code>move :: MonadState World m =&gt; Direction -&gt; m () move dir = do newCoord &lt;- uses wWorker (moveCoord dir) let newCoord' = moveCoord dir newCoord wall &lt;- isWall newCoord wall' &lt;- isWall newCoord' crate &lt;- isCrate newCoord case () of () | wall -&gt; return () | crate -&gt; if wall' then return () else do wWorker ^= newCoord wCrates %= delete newCoord wCrates %= insert newCoord' | otherwise -&gt; wWorker ^= newCoord toChar :: MonadState World m =&gt; Coord -&gt; m Char toChar c = do wall &lt;- isWall c crate &lt;- isCrate c storage &lt;- isStorage c worker &lt;- isWorker c return $ case () of () | wall -&gt; '#' | worker -&gt; '@' | crate -&gt; 'o' | storage -&gt; '.' | otherwise -&gt; ' ' </code></pre> <p>The lenses themself also come with a certain cost</p> <pre><code>setMaxCoords :: StateT World IO () setMaxCoords = do xMaxWall &lt;- uses wWalls $ fold (max . fst) 0 yMaxWall &lt;- uses wWalls $ fold (max . snd) 0 xMaxCrate &lt;- uses wCrates $ fold (max . fst) 0 yMaxCrate &lt;- uses wCrates $ fold (max . snd) 0 xMaxStorage &lt;- uses wStorage $ fold (max . fst) 0 yMaxStorage &lt;- uses wStorage $ fold (max . snd) 0 (xWorker, yWorker) &lt;- use wWorker wMax ^= ( maximum [xMaxWall, xMaxCrate, xMaxStorage, xWorker], maximum [yMaxWall, yMaxCrate, yMaxStorage, yWorker] ) </code></pre> <p>I feel like I must be missing some obvious abstractions, because all these operations seem trivial and necessary, but the wrapping adds a lot of boilerplate.</p> <p>The full code is here: <a href="http://hpaste.org/73124" rel="nofollow">http://hpaste.org/73124</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T18:09:40.423", "Id": "23718", "Score": "1", "body": "I found it very hard to give a good example of exactly what I \"feel\" is bad code, but I've tried to give the ones I think are most obvious now. Thank you for the feedback. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T03:52:09.507", "Id": "23834", "Score": "0", "body": "hi, what was the version of ghc that this was compiled with?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T16:55:08.690", "Id": "23895", "Score": "0", "body": "7.4.1 :) But apparently Edward Kmett has released a few new versions of lens (like.. eight) since I got it last week, which means all occurences of `^=` should be substituted with `.=`." } ]
[ { "body": "<p>I think the <code>is*</code> functions are a bad idea - Haskell has pattern matching for this.</p>\n\n<p>Also you can 'unwrap' your <code>World</code> when necessary and get unwrapped data from it.</p>\n\n<pre><code>data Cell = Wall | Crate | Storage | Worker | Empty\n\ncellContents coords world = bar where\n f x = S.member coords (x ^$ world)\n bar | f wCrates = Crate\n | f wWalls = Wall\n | f wStorage = Storage\n | coords == (wWorker ^$ world) = Worker\n | otherwise = Empty\n</code></pre>\n\n<p>With this approach <code>toChar</code> can be just </p>\n\n<p>toChar :: World -> Coord -> Char</p>\n\n<pre><code>toChar2 coords world = case cellContents coords world of\n Wall -&gt; '#'\n Worker -&gt; '@'\n Crate -&gt; 'o'\n Storage -&gt; '.'\n _ -&gt; ' '\n</code></pre>\n\n<p>If you have already unpacked current <code>world</code>, you can use </p>\n\n<pre><code>let char = toChar2 coords world\n</code></pre>\n\n<p>If you don't have <code>world</code> you can just do</p>\n\n<pre><code>char &lt;- toChar2 coord &lt;$&gt; get\n</code></pre>\n\n<p>The only place where you use <code>toChar</code> is <code>printWorld</code>, so it becomes simpler (no need for <code>evalState</code>):</p>\n\n<pre><code>let out = [[ toChar2 (x,y) w | x &lt;- [0 .. maxX]] | y &lt;- [0 .. maxY]]\n</code></pre>\n\n<p><code>setMaxCoords</code> can be rewritten as:</p>\n\n<pre><code>setMaxCoords :: StateT World IO ()\nsetMaxCoords = do\n w &lt;- get\n wMax .= maxCoords w\n\nmaxCoords = foldr (app2 max) (0, 0) . allCoords where\n allCoords w = (wWorker ^$ w) : concatMap (\\x -&gt; S.toList $ x ^$ w) [ wWalls, wCrates, wStorage ] where\n app2 f (x1, y1) (x2, y2) = (f x1 x2, f y1 y2)\n</code></pre>\n\n<p><code>move</code> can be rewritten the same way as <code>toChar2</code>: </p>\n\n<pre><code>move dir w = move2 (cellContents newCoord w) (cellContents newCoord' w) where\n oldCoord = wWorker ^$ w\n newCoord = moveCoord dir oldCoord\n newCoord' = moveCoord dir newCoord\n\n move2 Wall _ = return ()\n move2 Crate Wall = return ()\n move2 Crate _ = do\n wWorker .= newCoord\n wCrates %= delete newCoord\n wCrates %= insert newCoord'\n move2 _ _ = wWorker .= newCoord\n</code></pre>\n\n<p>It should be used in the <code>loop</code> as <code>get &gt;&gt;= move dir</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T01:51:58.273", "Id": "15312", "ParentId": "14616", "Score": "3" } } ]
{ "AcceptedAnswerId": "15312", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:20:43.370", "Id": "14616", "Score": "5", "Tags": [ "haskell" ], "Title": "Rewrite of Sokoban using State" }
14616
<p><a href="https://codereview.stackexchange.com/questions/14674/referential-mysql-design">A modified review request has been made here.</a></p> <p>Can I please have someone review this simple database design below and tell me if this is the correct way to achieve what I want to do? </p> <p><strong>What I am trying to do:</strong></p> <ol> <li>When a <code>cardID</code> is deleted this cascades and deletes the <code>surveyID</code> associated row.</li> <li>When a <code>trackID</code> is deleted this cascades and deletes the <code>cardID</code> associated row and its associated <code>surveyID</code> row.</li> </ol> <p><strong><a href="http://themindspot.com/junk/images/trackerDB.png" rel="nofollow noreferrer">ENTITY RELATIONSHIP DIAGRAM</a></strong></p> <p><strong>MYSQL CODE</strong></p> <pre><code>CREATE TABLE `Card` ( `cardID` int(11) NOT NULL AUTO_INCREMENT, `trackID` int(11) NOT NULL, `fName` varchar(21) NOT NULL, `mName` varchar(1) DEFAULT NULL, `lName` varchar(21) DEFAULT NULL, `email` varchar(40) NOT NULL, `isMember` int(1) NOT NULL, PRIMARY KEY (`cardID`), FOREIGN KEY (`trackID`) REFERENCES `Tracker`(`trackID`) ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; CREATE TABLE `Survey` ( `surveyID` int(11) NOT NULL AUTO_INCREMENT, `cardID` int(11) NOT NULL, `trackID` int(11) NOT NULL, `q0` int(1) NOT NULL, `q1` int(1) DEFAULT NULL, `q2` int(1) DEFAULT NULL, `q3` int(1) DEFAULT NULL, `q4` int(1) DEFAULT NULL, `q5` int(1) DEFAULT NULL, PRIMARY KEY (`surveyID`), FOREIGN KEY (`trackID`) REFERENCES `Tracker`(`trackID`) ON UPDATE CASCADE, FOREIGN KEY (`cardID`) REFERENCES `Card`(`cardID`)ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; CREATE TABLE `Tracker` ( `trackID` int(11) NOT NULL AUTO_INCREMENT, `tName` varchar(21) DEFAULT NULL, `tDesc` varchar(50) DEFAULT NULL, PRIMARY KEY (`trackID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:15:24.867", "Id": "23724", "Score": "0", "body": "Could you write something about the specification? Some sample data also could help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T23:11:49.893", "Id": "23745", "Score": "0", "body": "Should you not be using InnoDB if you want Foreign Key restraints?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T00:31:11.507", "Id": "23748", "Score": "0", "body": "@DavidBarker I am pretty sure you are correct. I tried to switch the engine type but I need to figure out what I need to do different when creating the tables because switching the engine type doesn't work. Find it kind of funny that MyISAM accepts it but converts the foreign keys to keys." } ]
[ { "body": "<ol>\n<li><p>I'd use longer attribute names (<code>firstName</code> instead of <code>fName</code>, <code>middleName</code>, <code>lastName</code>). \nIt's easier to read and maintain.</p></li>\n<li><p>Are you sure that <code>latin1</code> is enough for every data? Consider using <code>UTF-8</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T20:57:36.627", "Id": "23740", "Score": "1", "body": "I have made the change to `utf8`. That was a very good suggestion. For now I will leave the names as is because this is my prototype or proof of concept for a application that is establishing a remote connection to the database. I will definitely take you advice when I get going on the working beta. What about the Engine? I know InnoDB has foreign key support But I am having an issue with my MySql if I try and switch engines, not sure why since key support is on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T06:43:12.710", "Id": "23838", "Score": "0", "body": "@BrandonClark: Sorry, I don't know MySQL so deep. It may be worth a question on http://dba.stackexchange.com/" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:16:07.283", "Id": "14629", "ParentId": "14619", "Score": "2" } } ]
{ "AcceptedAnswerId": "14629", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T17:33:49.637", "Id": "14619", "Score": "1", "Tags": [ "mysql", "sql" ], "Title": "MySQL database with foreign key support" }
14619
<p>I am currently working on an unfinished project about Chess, it will (at some point) be able to help me to make some chess variations just by pasting the FEN position while I play online.</p> <p>But before continuing, my code must have good structure or it will become a nightmare to fix it later. So now that I have some basics, it would be great to have it reviewed:</p> <pre><code>//Note: the code uses jQuery function writeBoard() { var i, j, str, bol; str = "&lt;table id=\"chessboard\" cellpadding=\"0\" cellspacing=\"0\"&gt;&lt;tbody&gt;"; for (i = 9; --i;) { str += "&lt;tr&gt;"; for (j = 0; j &lt; 8; j++) { bol = !bol; str += "&lt;td class=\"" + (bol ? "ws" : "bs") + "\" id=\"" + (AbcLabels[j] + "" + i) + "\"&gt;&lt;/td&gt;"; } bol = !bol; str += "&lt;/tr&gt;"; } str += "&lt;/tbody&gt;&lt;/table&gt;"; $("body").append(str); } function setFEN(fen) { var i, j, len, arr, tmp, tmp2, tmp3; arr = (fen ? fen : DefaultFen).split(" ")[0].split("/"); for (i = 0; i &lt; 8; i++) { tmp = i * 8; for (j = 0, len = arr[i].length; j &lt; len; j++) { tmp2 = arr[i].charAt(j); if (tmp2 * 1) { tmp += tmp2 * 1; } else { tmp3 = tmp2.toLowerCase(); ChessBoard[i][tmp % 8] = PiecesNames.indexOf(tmp3) * (tmp2 != tmp3 ? 1 : -1); tmp++; } } } refreshBoard(); } function refreshBoard() { var i, j, emt, fen, tmp, tmp2, tmp3, tmp4; fen = ""; for (i = 9; --i;) { emt = 0; for (j = 0; j &lt; 8; j++) { tmp = Math.abs(i - 8); tmp2 = ChessBoard[tmp][j] || 0; if (tmp2) { if (emt) { fen += "" + emt; emt = 0; } tmp3 = $("#" + AbcLabels[j] + "" + i); if (tmp2 &lt; 0) { tmp4 = PiecesNames.charAt(tmp2 * -1); tmp3.addClass("b" + tmp4); fen += tmp4; } else { tmp4 = PiecesNames.charAt(tmp2); tmp3.addClass("w" + tmp4); fen += tmp4.toUpperCase(); } } else { emt++; } } if (emt) { fen += "" + emt; } fen += "/"; } console.log(fen); //remove the last "/" //fen+= can enPass, to move, castle Avility, clock, etc... //Fen=fen } var I, J, Len; var AbcLabels = ["a", "b", "c", "d", "e", "f", "g", "h"]; var PiecesNames = "*pnbrqk"; //[wp:1][wn:2][wb:3][wr:4][wq:5][wk:6]***[bp:-1][bn:-2][bb:-3][br:-4][bq:-5][bk:-6] var DefaultFen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -"; var ChessBoard = new Array(8); for (I = 8; I--;) { ChessBoard[I] = new Array(8); } var Fen; var ToMove; //[0:white][1:black] var WCastling, BCastling; //[0:none][1:short][2:long][3:both] //var IsCheck,EnPassant; $(function() { writeBoard(); setFEN("5Rk1/1b2p2p/p2pP1p1/2rP4/2BQ2P1/6qP/PP6/1K6 b - -"); }); </code></pre> <p>If you don't have a good text editor, you will find <code>tmpX</code> variables very hard to recognize one over the another... In my case, I just double click and they all get highlighted (using Notepad++).</p>
[]
[ { "body": "<p>The first thing I noticed are the escaping orgies. Both HTML and JavaScript allow you to use either <code>'</code> or <code>\"</code> to quote strings. Don't use the same for both and you can get rid of all those ugly backslashes.</p>\n\n<p>You can also get rid of the (badly-named) <code>bol</code> variable. You already have a loop variable so you can use <code>j % 2 == 0</code> or even simpler <code>j &amp; 1</code> to determine if the number is even or odd.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T18:20:52.560", "Id": "14622", "ParentId": "14620", "Score": "4" } }, { "body": "<p>Not a big java person, but I'd say rename all your variables, especially the tmp ones. When you come back in 6 months, are you really going to know what tmp2, or fen is representing? Try coming up with more descriptive names, even if the name is longer, in the long run you'll thank yourself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:13:36.190", "Id": "23723", "Score": "0", "body": "every single `tmpX` is unimportant, they are just vars that hold a cache of something to don't write or call them twice. But renaming the others (arr,bol,str,etc) is also a possibility, 3 letter names are not very descriptive" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:24:15.737", "Id": "23725", "Score": "0", "body": "I agree with Jeff. `tmp` is fine but if you have three different temp variables a more meaningful name is usually appropriate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:06:06.073", "Id": "23783", "Score": "1", "body": "@Jeff This is JavaScript not Java. Completely unrelated concepts." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T15:28:32.333", "Id": "23805", "Score": "0", "body": "Why is having descriptive variable names unrelated? Descriptive variable names are good for cleanliness in any language." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:11:15.943", "Id": "14627", "ParentId": "14620", "Score": "1" } }, { "body": "<p>First obvious point: In JavaScript it's custom to give variables names starting with lower case letters.</p>\n\n<p>One thing I would do is remove the \"writing\" of the board from the JavaScript and use a static HTML table instead. </p>\n\n<p>You could remove both the class and the id from the table cells. The checkered color can easily be created with CSS, e.g.</p>\n\n<pre><code>#chessboard tr:nth-child(2n) &gt; td:nth-child(2n+1), #chessboard tr:nth-child(2n+1) &gt; td:nth-child(2n) {\n background-color: black;\n}​\n</code></pre>\n\n<p>and the cells can be accessed using the <code>rows</code> and <code>cells</code> properties of the table DOM.</p>\n\n<p>Prefilling the variable <code>tmp</code> (the file) with <code>i * 8</code> doesn't mnake much sense, considering you do <code>tmp % 8</code> anyway.</p>\n\n<p>I'm not a big fan of displaying the pieces with CSS alone leaving the table practically empty. You should consider filling the cells with the <a href=\"http://en.wikipedia.org/wiki/Chess_symbols_in_Unicode\" rel=\"nofollow\">appropriate Unicode characters</a> and use the usual CSS text replacement techniques, if you want to display nicer images.</p>\n\n<p>Is there a any special reason you are writing the setup to a global variable (<code>ChessBoard</code>) before filling the table? Global variables is something one always should avoid when programming. And splitting up both steps just requires you to run though the loops twice. The only advantage I see in spitting the two steps up is the separation of concerns (model, view), which doesn't seem to be a priority here.</p>\n\n<p>Speaking of which, the \"encoding\" of the pieces in the <code>ChessBoard</code> as positive and negative numbers is quite cryptic. If you want to reuse that information, you may want to use something more readable, such as an object. Or at least document in a comment what you are doing.</p>\n\n<p>The identification of digits by multiplication with one isn't very common, and should also be commented. Using the unitary plus operator is more common, and explicitly testing with <code>ìsNaN</code> would make it more readable:</p>\n\n<pre><code>if ( !isNaN(+tmp2) ) {\n</code></pre>\n\n<p>Finally <code>fen ? fen : DefaultFen</code> can be shorted to <code>fen || DefaultFen</code></p>\n\n<p>Here's how I would do it: <a href=\"http://jsfiddle.net/xL9B8/4/\" rel=\"nofollow\">http://jsfiddle.net/xL9B8/4/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T15:25:12.703", "Id": "23804", "Score": "0", "body": "+1, you have some good points there. I will post the ones I disagree: _vars should start with lower case_ Globals should not. _reason to have everything in ChessBoard_ because I am planning to check legal moves, and getting values from the DOM is expensive and slow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T14:03:59.620", "Id": "23876", "Score": "0", "body": "Well, you shouldn't use globals in the first place :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-19T05:34:02.227", "Id": "502842", "Score": "0", "body": "8+ years and I cringe looking back at my code haha, true, I don't expose globals anymore, my \"library\" only exposes one global, like jQuery. Had no idea on any design patterns lol." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:37:38.467", "Id": "14660", "ParentId": "14620", "Score": "1" } } ]
{ "AcceptedAnswerId": "14622", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T18:07:00.273", "Id": "14620", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Can someone have a look to my Chess Project?" }
14620
<p>How can I format this code so it's more readable?</p> <pre><code>$(".card").click(function(){ $(this).stop().animate({ width:'0px', marginLeft: margin+'px', opacity: 0.5}, 500, function(){ $(this).siblings('.card').animate({ width: width + 'px', marginLeft:'0px', opacity:'1'},500); }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:07:53.580", "Id": "23721", "Score": "1", "body": "I just read it...." } ]
[ { "body": "<p>This is a very subjective question </p>\n\n<p>I am a fan of separating things so each is identifiable and easily maintained in the future. However some will argue this does lead to more code, but more readable code in my opinion. </p>\n\n<pre><code>var animateCallback = function() {\n var props = {\n width: width + 'px',\n marginLeft: '0px',\n opacity: '1'\n };\n $(this).siblings('.card').animate(props, 500);\n};\nvar clickHandler = function() {\n var props = {\n width: '0px',\n marginLeft: margin + 'px',\n opacity: 0.5\n };\n $(this).stop().animate(props, 500, animateCallback);\n};\n$(\".card\").click(clickHandler);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:36:52.420", "Id": "23726", "Score": "1", "body": "Robert C. Martin and Martin Fowler are on your side (*Clean Code* by *Robert C. Martin*, *G19: Use Explanatory Variables*; *Refactoring: Improving the Design of Existing Code by Martin Fowler*, *Introduce Explaining Variable*)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T20:32:24.973", "Id": "23739", "Score": "0", "body": "I would assume your audience knows JQ and name your handler something more descriptive of the behavior initiated than 'clickHandler.' The faster you get at the general purpose of a thing the less people have to look when they don't need more details. (just making that point here since mine's TLDR as always : P)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:07:59.010", "Id": "14625", "ParentId": "14621", "Score": "4" } }, { "body": "<p>This would be my preference:</p>\n\n<pre><code>$(\".card\")\n .click(function(){\n $(this)\n .stop()\n .animate({\n width:'0px', \n marginLeft: margin+'px', \n opacity: 0.5\n }, \n 500, \n function(){\n $(this)\n .siblings('.card')\n .animate({\n width: width + 'px',\n marginLeft:'0px',\n opacity:'1'\n }, 500);\n });\n });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:41:31.900", "Id": "23728", "Score": "1", "body": "ahhhh, after reading that my legs hurt. *staircase code is not fun to read*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:44:04.747", "Id": "23729", "Score": "0", "body": "I think it's the best you can do if the only thing you changed was the styling (white-spaces) of the code provided originally. Unless, you have something better, but in the end isn't it a matter of preference?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:55:14.740", "Id": "23732", "Score": "0", "body": "yes, and my preference is to not have my code looking like a water slide :P no offence, I think you will find a lot of developers agree here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T20:00:14.117", "Id": "23733", "Score": "1", "body": "Water slides! Sounds like fun. :D" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:10:35.693", "Id": "14626", "ParentId": "14621", "Score": "0" } }, { "body": "<p>This is really very open ended and is open to many forms of interpretation. The code format below is strictly the way I like to make my code legible.</p>\n\n<pre><code>$( \".card\" ).click( function()\n{\n $( this ).stop()\n .animate(\n { \n width:'0px', \n marginLeft: margin+'px', \n opacity: 0.5\n }, 500,\n\n function()\n {\n $(this).siblings('.card')\n .animate(\n {\n width: width + 'px',\n marginLeft:'0px',\n opacity:'1'\n },500);\n }); \n});\n</code></pre>\n\n<p>Only functions parenthesis start on the same vertical. Objects and arrays are always indented 4 spaces beyond the function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:18:54.400", "Id": "14631", "ParentId": "14621", "Score": "0" } }, { "body": "<p>My principle is to start general and get more specific. A good label on something is the fastest way to provide information. Name your functions for what they do and your properties/vars for what they store.</p>\n\n<p>I like my function/object-constructor internals to answer three questions in order:</p>\n\n<ol>\n<li>What's local to this scope? (vars and a list of funcs defined later)</li>\n<li>What's the general action of this thing (basic method calls that lead to output/changes)</li>\n<li>How does the internally defined stuff work (hoisted function definitions last)</li>\n</ol>\n\n<p>The merits of function hoisting for legibility are of course debatable but I prefer general stuff first, details later to trying to learn the general action of a thing while swimming in a sea of internal function definitions. Note: function hoisting only works with <code>function &lt;label&gt;()</code> definitions, not when you assign anonymous functions to vars as in <code>var someFunc = function(){}</code>.</p>\n\n<p>On the jquery front, I would use the <code>.animate(options, settings)</code> object arguments approach since object literal labels can add a lot more clarity (for instance to what 500 means) but I'm sticking with what you have here in case there's a JQ version issue. Also it's easy to miss methods in chaining. It's okay to use line-breaks between '.' operators and we often do where I work to make all method calls clear.</p>\n\n<pre><code>$('.card').click(animateCards); // name well and intent is clear sooner\n\nfunction animateCards(){\n\n //locals(1)\n var optionsObject = {\n //&lt;everything in the first animate arg object&gt;\n }\n\n //actual comment I would put in my code typically follows:\n //functions defined at bottom:\n //animateCallback - list so we can see the local funcs\n\n\n //main (2)\n\n $(this) //breaking chaining into lines like this can be helpful\n .stop()\n .animate(optionsObject,500,animateCallBack);\n\n\n //internal functions (3)\n\n function animateCallback(){\n //&lt;everything in animate's callback arg&gt;\n }\n\n}//end animateCards - always indicate ending brackets of longer functions\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:35:33.587", "Id": "14633", "ParentId": "14621", "Score": "0" } } ]
{ "AcceptedAnswerId": "14625", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T18:13:21.430", "Id": "14621", "Score": "4", "Tags": [ "javascript", "formatting" ], "Title": "How would I format this JavaScript code so it's more readable" }
14621
<p>I have a jQuery function using a series of <code>if</code> and <code>else</code> statements. I am wondering if there is a more elegant way I can code this. I am thinking I could create an array with my "hashtag names" and then loop it through a function. However, I am not quite sure how to go about doing that.</p> <pre><code>setTimeout(function() { var i = 0; if(window.location.hash == "#" + "somename"){ var i = 0; return scroll(i); } else if(window.location.hash == "#" + "somethingelse"){ var i = 1; return scroll(i); } else if(window.location.hash == "#" + "someotherword"){ var i = 2; return scroll(i); } else if (window.location.hash == "#" + "sometext"){ var i = 3; return scroll(i); } }, 500 ); function scroll(i){ var title = $('.title').eq(i); var top = $(title).offset().top - 50 ; $('html,body').animate({ scrollTop: top }, 'slow'); } </code></pre> <p>I'm checking to see what hashtag is in the URL, and then scrolling to the part of the page that is related to that hashtag. This method works, but I would like to optimize the <code>if</code>/<code>else</code> part of my code if possible. An array with a loop may not be the best approach. I am open to any ideas.</p>
[]
[ { "body": "<p>You can just parse the number right out of the location like this:</p>\n\n<pre><code>setTimeout(function() {\n var matches = window.location.hash.match(/^#page(\\d+)$/);\n if (matches) {\n scroll(+matches[1] - 1);\n }\n}, 500);\n</code></pre>\n\n<hr>\n\n<p>OK, now that you've changed to random strings, you could use a table lookup like this:</p>\n\n<pre><code>setTimeout(function() {\n var values = {\n \"#somename\": 1,\n \"#somethingelse\": 2,\n \"#someotherword\": 3,\n \"#sometext\": 4\n };\n var val = values[window.location.hash];\n if (val) {\n scroll(val - 1);\n }\n}, 500 );\n</code></pre>\n\n<p>P.S. Note, there is no reason to return anything from the <code>setTimeout()</code> callback as the return value is not processed by anything which is why I removed the return statement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:37:53.337", "Id": "23727", "Score": "0", "body": "Sorry, I am actually not using numbers... I just updated my question to reflect that. I put that them there as an example I didn't intend for it be like that, my mistake. For my scenario I am actually using different names for each page." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:46:08.257", "Id": "23730", "Score": "0", "body": "@KrisHollenbeck - OK, I've now provided a lookup table option for random strings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:54:14.797", "Id": "23731", "Score": "0", "body": "Thanks, I will see if I can get it to work with my code and get back to you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T20:04:41.370", "Id": "23734", "Score": "0", "body": "Hmm.. I am thinking I need to post some more code. That doesn't seem to work with what I have... I will update my question" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T20:08:10.633", "Id": "23735", "Score": "0", "body": "FYI.. I get this error when trying to implement the \"table lookup\" .. Uncaught TypeError: Cannot read property 'top' of null" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T20:11:34.857", "Id": "23736", "Score": "0", "body": "@KrisHollenbeck - I fixed an off by one error in my suggested code, but other than that, it does exactly what your previous code did. It passes a number from 0 to 3 to the function `scroll()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T20:15:18.473", "Id": "23737", "Score": "0", "body": "Okay, yeah that seemed to fix it. I am assuming this is because .eq() starts at 0? Is that correct." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:32:50.550", "Id": "14632", "ParentId": "14630", "Score": "1" } }, { "body": "<p>The book <a href=\"http://shop.oreilly.com/product/9780596802806.do\" rel=\"nofollow\">High Performance JavaScript</a> provides some good advice on looping in JavaScript. To quote it: </p>\n\n<blockquote>\n <p>Generally speaking, if-else is best used when there are two discrete values or a few different ranges of values for which to test. When there are more than two discrete values for which to test, the switch statement is the most optimal choice. ... When there are a large number of discrete values for which to test, both if-else and switch are significantly slower than using a lookup table. (Ch. 4 Algorithms and Flow Control)</p>\n</blockquote>\n\n<p>Also, instead of calling <code>window.location.hash</code> with each evaluation, copy that value to a local variable and evaluate that. It will improve performance since you won't keep going back to the DOM to look-up the value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T21:20:55.273", "Id": "14635", "ParentId": "14630", "Score": "0" } } ]
{ "AcceptedAnswerId": "14632", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T19:16:11.880", "Id": "14630", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Loop function using an array" }
14630
<p>This is just a simple login form with a very vanilla HTML markup, but I just wanted to get some professional feedback. I know about jslint and try to adhere to there principals where possible.</p> <pre><code>&lt;script&gt; //event listeners $('#sign_in_button').on('click', sign_in); $('#create_new_account').on('click', create); $('#create_signup_form').on('click', modal); function modal() { $('#error_box2').text('').hide(); } function login_success() { linkLocation = 'home.html'; $("body").fadeOut(3000, redirect_page); } function redirect_page() { window.location = linkLocation; } function login_error() { var msg = 'Error logging in'; error(msg); } function get_form_input(id,validator) { var check ='', type =$(id).attr('type'); if(type != 'checkbox' ) { check = $(id).val(); } else if (type == 'checkbox') { check = $(id).attr('checked'); } if(validator(check)){ return check; } else { return false; } return false; } ///validation functions function validate_username(id) { var username_regex = /^[A-Za-z](?=[A-Za-z0-9_.]{3,20}$)[a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*$/; var msg; if (!username_regex.test(id)) { if ((id.length) &gt; 21){ msg = "under 20 characters."; } else if((id.length) &lt; 4) { msg = " more than 4 characters."; }else { msg = "You can use 4-20 characters, including underscores and one dot."; } return error(msg); } return username_regex.test(id); } function validate_password(pass) { var msg; var password_regex = /^.{8,20}$/; if (password_regex.test(pass)) { return true; } else if (pass.length &lt;8) { msg = "Passwords should be 8 characters or more."; return error(msg); } else if (pass.length &gt;21) { msg= "twenty character max"; return error(msg); } else if (!password_regex.test(password)) { msg= "Passwords can be 8-20 characters"; return error(msg); } } function validate_email(email) { var email_regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; var msg; if (!email_regex.test(email)) { msg = "Not a valid email."; return error(msg); } return email; } function error(msg) { $('#error_box1').slideDown(); $('#error_box1').text(msg); return false; } function create_success() { login_success(); } function create_error() { var msg = 'Error logging in'; error(msg); } function sign_in() { var send = { 'password' : get_form_input('#password', validate_password), 'username' : get_form_input('#username', validate_username), }; var url = "http://"; if (send.username &amp;&amp; send.password) { console.log(send); $.when($.post(url,send)).then(login_success, login_error); } else { return; } } function create() { var send = { 'password' : get_form_input('#new_password', validate_password), 'username' : get_form_input('#new_username', validate_username), 'email' : get_form_input('#new_email', validate_email) }; var url = "http://"; if (send.username &amp;&amp; send.password &amp;&amp; send.email) { console.log(send); $.when($.post(url,send)).then(create_success, create_error); } else { //return error('Error logging in. Try again soon.'); } } &lt;/script&gt; </code></pre> <ol> <li>What is the non-quick fix for the name space issue? </li> <li>Why couldn't a heavy, more complicated application not function effectively with procedural code?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T12:53:06.270", "Id": "23853", "Score": "0", "body": "\"As professionals, is there anything clearly amateurishness about this code that I could improve?\" - the over-use of $()" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T13:06:31.857", "Id": "23854", "Score": "0", "body": "To clarify, you shouldn't just reach into the DOM every time to select stuff. cache it (store it as a local variable) ... `var el = $('#error_box1'); el.slideDown().text(msg);` *due to chaining this is a bad example*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:49:08.723", "Id": "23909", "Score": "0", "body": "Not worthy of \"answer\" status: generally, JavaScript code is camelCased rather than using underscores. Obviously styles differ, but you asked ;). Also, `$(id).attr('checked')` should be `$(id).prop('checked')`, as `attr()` only looks for the HTML attribute, not whether the checkbox is actually checked." } ]
[ { "body": "<ul>\n<li><p>It's in the HTML (script tag). Link it. Keep 'em separated whenever possible.</p></li>\n<li><p>Not a big deal but when declaring vars you can do them with one var statement, e.g. <code>var a = 0, b = 3;</code></p></li>\n<li><p>Add 'use strict;' to look super cool (but I've seen at least one thing that will break)</p></li>\n<li><p>Fix stuff like <code>linkLocation = 'home.html';</code> (no var statement - would be global - illegal in strict mode)</p></li>\n<li><p>window is global in browsers. <code>window.location</code> can just be called as <code>location</code></p></li>\n<li><p>If this is to be seen by interviewers, be consistent with your style. For instance, you mix ' and \" for strings. Most prefer ' to differentiate from HTML attribute quotes which are typically double. Mixing both looks like it's not all your code or you're a little sloppy.</p></li>\n<li><p>When it's just a JavaScript object and not JSON, it doesn't need quotes on the property names. e.g. <code>send = { 'password':...</code></p></li>\n<li><p>If it's an interview situation, don't pretend any of the regEx is yours unless you can explain it.</p></li>\n<li><p>You're pooping all over the global namespace - quick fix would be:</p>\n\n<p>(function(){</p>\n\n<p>//wrap your code here</p>\n\n<p>})()</p></li>\n</ul>\n\n<p>Don't know what's wrong with code formatting but that puts your functions in scope with anonymous function that automatically fires so it should keep your stuff from being overwritten or overwriting other stuff in the global namespace.</p>\n\n<p>Otherwise it looks like good, clean, straightforward, procedural code. Nothing wrong with that when it's all that's called for. If this were a heavy, complicated, application, I'd be wondering where the objects were at.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T02:44:38.340", "Id": "23754", "Score": "0", "body": "Thank you for you're response. 2 questions: \n1) The name space issue, vis-a-vis pooping all over it, what is the non-quick fix?\n2) Why couldn't a heavy, more complicated application not function effectively with procedural code?\n\nThanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T02:09:11.157", "Id": "14640", "ParentId": "14639", "Score": "3" } }, { "body": "<p>Polluting the global scope with variables is not a wise idea. Instead, lets pass in <code>linkLocation</code> as a parameter:</p>\n\n<pre><code>function login_success() {\n $(\"body\").fadeOut(3000, function(){\n redirect_page('home.html');\n }); \n}\n\nfunction redirect_page(linkLocation) {\n window.location = linkLocation;\n}\n</code></pre>\n\n<p>If looks like you may have a bug with <code>get_form_input</code>. If the form input is a checkbox and is unchecked it will return <code>false</code> even if it passes the validator function. Since this will cause the <code>sign_in</code> function to fail, lets return <code>null</code> as an invalid state.</p>\n\n<pre><code>function get_form_input(id,validator) {\n var check,\n type =$(id).attr('type');\n\n if(type != 'checkbox' ) {\n check = $(id).val();\n } else if (type == 'checkbox') {\n check = $(id).attr('checked');\n }\n\n return validator(check) ? check : null;\n}\n</code></pre>\n\n<p>To guard agains the previously mentioned bug, we need to check if not null. I'm including only the <code>create</code> function.</p>\n\n<pre><code>function create() {\n var send = {\n 'password' : get_form_input('#new_password', validate_password),\n 'username' : get_form_input('#new_username', validate_username),\n 'email' : get_form_input('#new_email', validate_email)\n };\n\n var url = \"http://\";\n\n if (send.username != null &amp;&amp; send.password != null &amp;&amp; send.email != null) {\n console.log(send); \n $.when($.post(url,send)).then(create_success, create_error);\n } else {\n //return error('Error logging in. Try again soon.');\n }\n}\n</code></pre>\n\n<p>Regular expressions are tough to read (human wise). As such, if you have a gnarly reg-ex in your code (<code>username_regex</code>), you should comment what it does. Furthermore, using regular expressions to check the total length of the string is inefficient and not necessary here, since you already have to check the length to report an accurate error message. As such, consider validating the username and password like this:</p>\n\n<pre><code>function validate_username(id) {\n /* Starts with an alpha character and contains at most one '.' */\n var username_regex = /^[A-Za-z]\\w*\\.?\\w*$/;\n var msg;\n if (id.length &gt; 21){\n msg = \"under 20 characters.\";\n } else if (id.length &lt; 4){\n msg = \" more than 4 characters.\";\n } else if(!username_regex.text(id)){\n msg = \"You can use 4-20 characters, including underscores and one dot.\"\n } else {\n return true;\n }\n\n return error(msg);\n}\n\nfunction validate_password(pass) {\n var msg;\n\n if (pass.length &lt; 8) {\n msg = \"Passwords should be 8 characters or more.\";\n } else if (pass.length &gt; 21) {\n msg = \"Passwors may be twenty character max.\";\n } else {\n return true;\n } \n\n return error(msg);\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T02:21:42.377", "Id": "14641", "ParentId": "14639", "Score": "2" } } ]
{ "AcceptedAnswerId": "14640", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T01:20:57.773", "Id": "14639", "Score": "1", "Tags": [ "javascript", "jquery", "form" ], "Title": "Simple login form with vanilla HTML markup" }
14639
<p>It seems it could be written shorter. It's especially annoying when I have to do this in multiple languages, so the button labels will be different.</p> <pre><code>&lt;button id="egyes" class="btn btn-danger"&gt;Hide&lt;/button&gt;&amp;nbsp;some text &lt;button id="kettes" class="btn btn-warning"&gt;Hide&lt;/button&gt;&amp;nbsp;other text &lt;button id="harmas" class="btn btn-info"&gt;Hide&lt;/button&gt;&amp;nbsp;some more text &lt;button id="otos" class="btn btn-success"&gt;Hide&lt;/button&gt;&amp;nbsp;last button &lt;button id="showall" class="btn"&gt;Show all&lt;/button&gt; &lt;script&gt; $(document).ready(function() { $("#egyes").click( function() { $("div.progress-danger").parent().fadeToggle(); if ($(this).html() == "Show") { $(this).html("Hide"); } else { $(this).html("Show"); } }); $("#kettes").click( function() { $("div.progress-warning").parent().fadeToggle(); if ($(this).html() == "Show") { $(this).html("Hide"); } else { $(this).html("Show"); } }); $("#harmas").click( function() { $("div.progress-info").parent().fadeToggle(); if ($(this).html() == "Show") { $(this).html("Hide"); } else { $(this).html("Show"); } }); $("#otos").click( function() { $("div.progress-success").parent().fadeToggle(); if ($(this).html() == "Show") { $(this).html("Hide"); } else { $(this).html("Show"); } }); $("#showall").click( function() { $("div.container &gt; div &gt; div.progress").parent().fadeIn(); }); }); &lt;/script&gt; </code></pre>
[]
[ { "body": "<p>if you add the parent div class into the data attributes:</p>\n\n<pre><code>&lt;button id=\"egyes\" class=\"btn btn-danger\" data-parentclass=\"progress-danger\"&gt;Hide&lt;/button&gt;&amp;nbsp;some text \n&lt;button id=\"kettes\" class=\"btn btn-warning\" data-parentclass=\"progress-warning\"&gt;Hide&lt;/button&gt;&amp;nbsp;other text\n&lt;button id=\"harmas\" class=\"btn btn-info\" data-parentclass=\"progress-info\"&gt;Hide&lt;/button&gt;&amp;nbsp;some more text\n&lt;button id=\"otos\" class=\"btn btn-success\" data-parentclass=\"progress-success\"&gt;Hide&lt;/button&gt;&amp;nbsp;last button\n&lt;button id=\"showall\" class=\"btn\"&gt;Show all&lt;/button&gt;\n</code></pre>\n\n<p>or add it in via javascript:</p>\n\n<pre><code>$(\"#egyes\").data(\"parentclass\", \"progress-danger\");\n// etc\n</code></pre>\n\n<p>then the javascript can work it out itself.\n ​</p>\n\n<pre><code>$(document).ready(function() {\n $(\"#egyes, #kettes, #harmas, #otos\").click( function() {\n var $parent = $(\"div.\" $(this).data(\"parentclass\")).parent();\n\n if ($parent.is(\":visible\")) {\n $(this).html(\"Hide\");\n } else {\n $(this).html(\"Show\");\n }\n\n parent.fadeToggle();\n });\n\n\n $(\"#showall\").click( function() {\n $(\"div.container &gt; div &gt; div.progress\").parent().fadeIn();\n });\n });\n</code></pre>\n\n<p>​</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T07:38:14.440", "Id": "23767", "Score": "0", "body": "definately looks better !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T08:05:07.450", "Id": "23769", "Score": "0", "body": "however `parent.is(\":visible\")` will be always true, because when the script reach the `if(...)` the divs will be already visible !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T09:30:46.140", "Id": "23773", "Score": "0", "body": "@Walkman whoops! ... wasn't able to test it. Just move the `.fadeToggle` after it? ... I can't actually test it without some more markup. (or maybe a jsfiddle.net?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T09:37:13.543", "Id": "23774", "Score": "1", "body": "I tested it and worked after the modification." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T06:51:13.547", "Id": "14645", "ParentId": "14644", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T05:44:10.713", "Id": "14644", "Score": "2", "Tags": [ "javascript", "performance", "jquery" ], "Title": "jQuery button text changer script" }
14644
<p>I'm just getting into SQL injection and data sanitization and seeking some advice on my script to get started. I have made this simple program which allows the user to enter their name into a form and the information gets saved into the database. There is also a button that lists all the current names in the database.</p> <pre><code>&lt;?php require 'db.php'; //If the "name" form was submitted, enter it into the database. if (isset($_POST['submit'])) { $name = $_POST['name']; echo $name . ', you submitted it!'; $con-&gt;query("INSERT INTO name (name) VALUES ('$name')"); } //Delete name from database. if (isset($_POST['del_submit'])) { $con-&gt;query("DELETE FROM name WHERE name='$del'"); echo $del . ' deleted successfully!'; } ?&gt; &lt;form id="devvo" method="post"&gt; &lt;h2&gt;Enter your name:&lt;/h2&gt; &lt;p&gt;&lt;input type="text" name="name" /&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Submit" /&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="hidden" name="submit" /&gt;&lt;/p&gt; &lt;/form&gt; &lt;br /&gt; &lt;br /&gt; &lt;form id="list" method="post"&gt; &lt;input type="submit" value="List Everyone..."&gt; &lt;input type="hidden" name="list" /&gt;&lt;/p&gt; &lt;/form&gt; &lt;?php //If the "list" form was submitted, get all names from database and display them to the user. if (isset($_POST['list'])) { $result = $con-&gt;query("SELECT * FROM name"); while ($row = $result-&gt;fetch_assoc()) { $del = $row['name']; echo '&lt;strong&gt;Name:&lt;/strong&gt; &lt;br /&gt;'; echo $row['name']; echo '&lt;form id="del" method="post"&gt;&lt;input type="submit" name="del_submit" value="X" /&gt;&lt;input type="hidden" name="del" value="'.$del.'" /&gt;&lt;/form&gt;'; echo '&lt;br /&gt;'; } } ?&gt; </code></pre> <p>My knowledge of PHP is very limited (as you can tell from the program) but I'm definitely seeking some best practices and simple ways to improve the security of a simple program such as this. Feel free to tell me all the different ways this program could be exploited!</p>
[]
[ { "body": "<p>Can't help you much here, not much of a SQL person. However, right off the bat you are going to want to validate and sanitize your data. You never want to use raw user data. That's always bad. You are doing an ok job in validating using the <code>isset()</code> function. But there's more to it. You should make sure you are getting the proper data type (alphanumeric, alpha only, numeric only, etc...). You should also make sure there is no sort of injection going on by sanitizing any unwanted data. If you have PHP version >= 5.2 I would recommend using the <code>filter_input()</code> function here as it can do both. For instance:</p>\n\n<pre><code>$name = filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING );\n</code></pre>\n\n<p>I'll let everyone else help you with the SQL specific stuff :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T17:38:08.953", "Id": "23809", "Score": "0", "body": "Here I've revised the code. Let me know what you think now. Thank you for your input!\n\n[PASTIE HERE](http://pastie.org/pastes/4471333/edit)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T13:11:38.620", "Id": "14662", "ParentId": "14646", "Score": "0" } }, { "body": "<p>A few quick things:</p>\n\n<ul>\n<li><code>$del</code> is never defined when you delete based on it</li>\n<li>Use prepared statements\n<ul>\n<li>Not technically necessary here in your script (depending on <code>$del</code>)\n<ul>\n<li>a good habit to have even when data is safe</li>\n<li>If you remove the filter later, then the escaping will already be there</li>\n</ul></li>\n</ul></li>\n<li>Don't silently change user's input\n<ul>\n<li>If the user provides invalid input, tell him; don't silently change it.</li>\n<li>Not a hard rule by any means, but if a user provides a name and you change it for him, that might be a bit confusing.</li>\n</ul></li>\n<li>Strive for valid HTML\n<ul>\n<li>Probably just meant to be a toy-esque script, but it's CodeReview, so might as well be pedantic :-).</li>\n<li>You do have a stray <code>&lt;/p&gt;</code> though after the <code>list</code> input</li>\n</ul></li>\n<li>It's a good habit to separate business logic and presentation\n<ul>\n<li>MVC is basically what I'm hinting at, but there's no need to go all the way</li>\n<li>New data should never be fetched or generated inside of HTML</li>\n<li>The best description of what I'm getting at that I've ever heard is probably (summarized):\n<ul>\n<li>If you can't reskin your site without repeating PHP code other than simple output, something is wrong.</li>\n</ul></li>\n<li>A bit hard to explain if you've never seen it, so if you want, I can do a little example.</li>\n</ul></li>\n<li>Escape HTML\n<ul>\n<li>Any time you put a variable into html, it should be escaped with htmlspecialchars or htmlentities.</li>\n<li><code>echo '&lt;tr&gt;&lt;td&gt;' . htmlspecialchars($row['name']) . '&lt;/td&gt;';</code></li>\n</ul></li>\n<li>Just because one input is set does not mean that another is\n<ul>\n<li><code>$_POST['submit']</code> and <code>$_POST['name']</code> are not magically linked</li>\n<li>A user could exploit this to cause a notice</li>\n<li><strong>Never</strong> directly access anything a user can control the existence or content of\n<ul>\n<li>Use <code>filter_input</code> like showerhead suggested</li>\n<li>Or, if you want to do it more directly:\n<ul>\n<li><code>$name = (isset($_POST['name']) &amp;&amp; is_string($_POST['name'])) ? $_POST['name'] : null;</code></li>\n<li>Note: everything comes in as either a string or an array even if it's an integer.</li>\n<li><code>$id = (isset($_POST['id']) &amp;&amp; is_string($_POST['id'])) ? (int) $_POST['id'] : null</code>;'</li>\n</ul></li>\n<li>(Yes, I am 100% crazy-level paranoid)</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p><strong>Edit: This is a response to the comment below</strong></p>\n\n<blockquote>\n <p>if you could elaborate on a couple of your points that would be great. \n Particularly: \"Just because one input is set does not mean that another is $_POST['submit'] and $_POST['name'] are not magically linked A user could exploit this to cause a notice\" </p>\n</blockquote>\n\n<p>Consider this code:</p>\n\n<pre><code>if (isset($_POST['submit'])) {\n $name = $_POST['name'];\n ...\n}\n</code></pre>\n\n<p>As discussed above, you should never access a key that your not sure exists. I'm assuming the logic here is, \"well if the form was submitted, then the name field must exist.\"</p>\n\n<p>That's not the case though. Consider this HTML:</p>\n\n<pre><code>&lt;form action=\"http://yoursite.tld/yourpage.php\" method=\"POST\"&gt;\n &lt;input type=\"submit\" name=\"submit\" value=\"Submit\"&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Now imagine that someone submits this form.</p>\n\n<p>Reading <code>$_POST['name']</code> will trigger an \"undefined index\" notice.</p>\n\n<p>So, in short, what I was getting at is that there is no link between the <code>submit</code> and <code>name</code> indexes. It's completely possible for one to be set and not the other.</p>\n\n<p>Would this actually ever matter? Probably not. But still, it can have bad effects like a malicious user seeing file path or trying to fill up a log file.</p>\n\n<p>The code should look like this:</p>\n\n<pre><code>if (isset($_POST['submit'])) {\n $name = (isset($_POST['name']) &amp;&amp; is_string($_POST['name'])) ? $_POST['name'] : null;\n ...\n}\n</code></pre>\n\n<p>(Or you could use <code>filter_input</code>.)</p>\n\n<blockquote>\n <p>And: The $del issue. The script works great even though you say it isn't defined? </p>\n</blockquote>\n\n<p>The first time <code>$del</code> appears is on line 15 (<code>$db-&gt;query(\"DELETE FROM name WHERE name='$del'\");</code>). This means that it is either defined in db.php, or it's not defined.</p>\n\n<p>If it's defined in db.php, it shouldn't be.</p>\n\n<p>If it's not defined, that means that it's issuing a notice and being treated as <code>null</code>.</p>\n\n<p>(There's a third, very unlikely possibility that register globals is enabled. If that abomination is enabled, immediately disable it, or if your hosting company has enabled it without you requesting it, promptly switch companies.)</p>\n\n<p>When <code>null</code> is casted to a string, it becomes an empty string, so the query is probably running like:</p>\n\n<pre><code>$db-&gt;query(\"DELETE FROM name WHERE name=''\");\n</code></pre>\n\n<p>Also, this query falls under my \"Use prepared statements\" point above.</p>\n\n<p>Imagine if someone submits the following form:</p>\n\n<pre><code>&lt;form action=\"http://yoursite.tld/page.php\" method=\"POST\"&gt;\n &lt;input type=\"submit\" name=\"del_submit\" value=\"Delete\"&gt;\n &lt;input type=\"hidden\" name=\"del\" value=\"' OR 1\"&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>That means that this query would be executed:</p>\n\n<pre><code>DELETE FROM name WHERE name='' OR 1\n</code></pre>\n\n<p><code>1</code> is always true, thus the entire table would be cleared.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T16:53:58.433", "Id": "23894", "Score": "0", "body": "Corbin, this is exactly the response I was looking for. I can't believe I forgot that stray </p> tag! Also, if you could elaborate on a couple of your points that would be great. Particularly: \n\"Just because one input is set does not mean that another is\n$_POST['submit'] and $_POST['name'] are not magically linked\nA user could exploit this to cause a notice\"\nAnd:\nThe $del issue. The script works great even though you say it isn't defined?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T08:42:26.743", "Id": "24010", "Score": "0", "body": "@Brandon Have edited in a response to both of your points." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T05:07:15.147", "Id": "24080", "Score": "0", "body": "Corbin, that clears things up, thank you. Also, I thought I had $del registered like this: `$del = $row['name'];`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T05:09:43.493", "Id": "24081", "Score": "0", "body": "@Brandon that doesn't happen until later in execution. (And, it's used for N-different items -- how would it magically bind only one of those to `$del`?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-16T19:09:53.277", "Id": "47336", "Score": "0", "body": "I strongly promote prepared statements over ad-hoc sanitizing filters. First, sanitizing filters are often too restrictive or corrupt data unnecessarily. For example, many people's names contain essential spaces, hyphens, or apostrophes. Why should they suffer just because you used the DB library improperly? Also, constructing SQL queries by string interpolation or concatenation is a filthy habit, as the `DELETE` vulnerability shows. Use parameterized queries as standard operating procedure and solve both problems. Then you never have to keep track of which strings have been sanitized." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T10:01:03.093", "Id": "14684", "ParentId": "14646", "Score": "3" } } ]
{ "AcceptedAnswerId": "14684", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T06:57:56.767", "Id": "14646", "Score": "3", "Tags": [ "php", "security", "mysqli" ], "Title": "Protecting a database from bad data" }
14646
<p>For a website I'm working on, I had to get all the unique entries in an array and count their occurrence. It is possible a certain entry is only found once, but it can also be found 20 times. So I designed the following bit of code:</p> <pre><code>for ($i = 0; $i &lt; count($nodes); $i++) { for ($j = 0; $j &lt; count($nodes[$i]); $j++) { if (!array_key_exists($nodes[$i][$j], $uniekenodes)) { $uniekenodes[$nodes[$i][$j]] = 1; } else { $uniekenodes[$nodes[$i][$j]] += 1; } } } </code></pre> <p>The <code>$nodes</code> array contains the the entries returned from the database. And the <code>$uniekenodes</code> array contains the unique entries and how many times they occured in the <code>$nodes</code> array.</p> <p>This is my first php script (on a drupal webpage by the way) and as such I don't know that much about php. I'm pretty confident there is probably a more a efficient way to do this, using php-specific functions. Any and all tips are welcome!</p> <p>EDIT: I might have to clarify the structure of the arrays:</p> <p><code>$nodes</code> has two dimensions. The first dimension is just a key for the second dimension. This one contains an array of drupal nodes for each key.</p> <p><code>$uniekenodes</code> uses the nodes from <code>$nodes</code> as a key and the value is how many times the node occured in <code>$nodes</code></p> <p>EDIT 2:</p> <p>I printed the arrays, as requested by Boris Guéry:</p> <pre><code>Array ( [0] =&gt; Array //Each of these contains node id's returned by a query ( [0] =&gt; 12 [1] =&gt; 11 [2] =&gt; 10 [3] =&gt; 9 [4] =&gt; 8 [5] =&gt; 7 ) [1] =&gt; Array ( [0] =&gt; 10 [1] =&gt; 9 [2] =&gt; 8 [3] =&gt; 7 ) [2] =&gt; Array ( ) [3] =&gt; Array ( [0] =&gt; 11 [1] =&gt; 10 [2] =&gt; 9 [3] =&gt; 8 [4] =&gt; 7 ) ) Array //This one uses the node ids from the previous array as keys, the values are the number of occurences. ( [12] =&gt; 1 [11] =&gt; 2 [10] =&gt; 3 [9] =&gt; 3 [8] =&gt; 3 [7] =&gt; 3 ) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T09:06:20.120", "Id": "23772", "Score": "0", "body": "Post an example of your array structure" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T09:52:00.617", "Id": "23775", "Score": "0", "body": "@BorisGuéry Added an example." } ]
[ { "body": "<p>I think the associative array approach is good. You could probably get away with:</p>\n\n<pre><code>for ($i = 0; $i &lt; count($nodes); $i++)\n for ($j = 0; $j &lt; count($nodes[$i]); $j++)\n $uniekenodes[$nodes[$i][$j]]++;\n</code></pre>\n\n<p>As incrementing NULL values results in 1.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T11:17:05.643", "Id": "23779", "Score": "0", "body": "It doesn't seem to work properly. `$uniekenodes[$nodes[$i][$j]]++;` gives me this error: `Notice: Undefined index: 12 in include()`. If I leave my loop in place, before executing yours it doesn't give the error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T14:45:05.620", "Id": "23800", "Score": "0", "body": "This may work if you use error suppressants. As the OP points out, there are undefined index errors because these keys have not been declared yet. However you should definitely NOT use error suppressants. It is a pretty unique solution though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T09:55:05.467", "Id": "14655", "ParentId": "14647", "Score": "1" } }, { "body": "<p>First off, foreach loops would make this look much nicer. Also, its always better to use the \"not operator\" <code>!</code> only if you have to. For instance, in your situation you do something either way, so switch it around.</p>\n\n<pre><code>foreach( $nodes AS $node ) {\n foreach( $node AS $value ) {\n if( array_key_exists( $value, $uniekenodes ) ) {\n $uniekenodes[ $value ] += 1;\n } else {//the not is now the else\n $uniekenodes[ $value ] = 1;\n }\n }\n}\n</code></pre>\n\n<p>I had the initial idea that you could just use <code>array_count_values()</code> on each interior array then combine them. You can still do this, but combining them wasn't as easy as I thought it would be. Maybe I'm missing something... Anyways, I found another solution. It SHOULD work, but I've not tested it, so no promises. I'm not really sure how I feel about the closure, but it seems to be picking up common use. In the end, both the above method and this one below are fine, its up to you to decide which to use. I'm not even sure where I stand on this one. The bottom one is cleaner, but the top one I'm more familiar with. Its fun to play around with stuff like this and experiment. I'll have to see how this works out in some of my projects. Its always good when you walk away having learned something yourself. Thanks for giving me an excuse to play around with something new :)</p>\n\n<pre><code>array_walk_recursive( $nodes, function( $value, $key ) use( &amp;$uniekenodes ) {\n if( array_key_exists( $value, $uniekenodes ) ) {\n $uniekenodes[ $value ] += 1;\n } else {\n $uniekenodes[ $value ] = 0;\n }\n} );\n</code></pre>\n\n<p>On a final note, I would consider renaming the <code>$uniekenodes</code> array. It is just awkward and I wouldn't have known what was in it if you hadn't told me. <code>$uniqueNodes</code> is good, or <code>$nodeFrequency</code>, or anything else that better describes it. Unless, of course, this is in another language and that is a good description (I don't know, looks like it could be). Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T14:52:18.043", "Id": "23803", "Score": "0", "body": "The first one does the trick! The foreach loop looks more elegant than a for loop. I'm just so used to using for loops, I forgot about foreach loops. `Unieke nodes` is indeed another language, it's dutch. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T14:40:00.960", "Id": "14663", "ParentId": "14647", "Score": "1" } } ]
{ "AcceptedAnswerId": "14663", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T07:09:38.493", "Id": "14647", "Score": "1", "Tags": [ "php", "drupal" ], "Title": "Get unique entries from array" }
14647
<p>Based on a python name generator grammar I found <a href="http://jerith.za.net/code/cfnamegencode.html" rel="nofollow">here</a> I've decided to write my own in objective-C. The idea is I can load the grammar from a plist file and generate random names from it.</p> <p>I'm looking for a general code review and any comments and or suggestions.</p> <p>NameGenerator.h:</p> <pre><code>@interface NameGenerator : NSObject - (id)initWithGrammar:(NSString *)plistName; - (NSString*)name; @end </code></pre> <p>NameGenerator.m:</p> <pre><code>@interface NameGenerator() @property (nonatomic,strong) NSDictionary *grammar; -(NSString*)replaceKey:(NSString*)input; @end @implementation NameGenerator @synthesize grammar = _grammar; - (id)init { @throw [NSException exceptionWithName: @"NameGeneratorInit" reason: @"-init is not allowed, use -initWithGrammar: instead" userInfo: nil]; } - (id)initWithGrammar:(NSString *)plistName { self = [super init]; if (self) { NSString* plistPath = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"]; self.grammar = [NSDictionary dictionaryWithContentsOfFile:plistPath]; id object = [self.grammar objectForKey:@"grammar"]; if (![object isKindOfClass:[NSString class]]) { NSLog(@"initWithGrammar: Not a grammar plist"); self = nil; } NSString *ver = object; if (![ver isEqualToString:@"NG.CF.1"]) { NSLog(@"initWithGrammar: plist version is wrong"); self = nil; } } return self; } - (NSString*)name { return [self replaceKey:@"name"]; } -(NSString*)replaceKey:(NSString*)input { NSString *output = @""; NSArray *parts = [input componentsSeparatedByString:@","]; if ([parts count] &gt; 1) { for(NSString *part in parts) { output = [output stringByAppendingString:[self replaceKey:part]]; } } else { id object = [self.grammar objectForKey:input]; if ([object isKindOfClass:[NSString class]]) { output = [self replaceKey:object]; } else if ([object isKindOfClass:[NSArray class]]) { NSUInteger randomIndex = arc4random() % [object count]; output = [self replaceKey:[object objectAtIndex:randomIndex]]; } else { output = input; } } return output; } </code></pre> <p>ork.plist:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;grammar&lt;/key&gt; &lt;string&gt;NG.CF.1&lt;/string&gt; &lt;key&gt;name&lt;/key&gt; &lt;string&gt;nameStart,nameMiddle0to3,nameEnd&lt;/string&gt; &lt;key&gt;nameMiddle0to3&lt;/key&gt; &lt;array&gt; &lt;string&gt;&lt;/string&gt; &lt;string&gt;nameMiddle&lt;/string&gt; &lt;string&gt;nameMiddle,nameMiddle&lt;/string&gt; &lt;string&gt;nameMiddle,nameMiddle,nameMiddle&lt;/string&gt; &lt;/array&gt; &lt;key&gt;nameStart&lt;/key&gt; &lt;array&gt; &lt;string&gt;nsCons,tick,nsCons,nmVowel&lt;/string&gt; &lt;string&gt;nsCons,nmVowel&lt;/string&gt; &lt;string&gt;nsCons,nmVowel&lt;/string&gt; &lt;string&gt;nsCons,nmVowel&lt;/string&gt; &lt;string&gt;nsVowel&lt;/string&gt; &lt;/array&gt; &lt;key&gt;nameMiddle&lt;/key&gt; &lt;string&gt;nmCons,nmVowel&lt;/string&gt; &lt;key&gt;nameEnd&lt;/key&gt; &lt;array&gt; &lt;string&gt;neCons,neVowel&lt;/string&gt; &lt;string&gt;neCons&lt;/string&gt; &lt;string&gt;neCons&lt;/string&gt; &lt;/array&gt; &lt;key&gt;nsCons&lt;/key&gt; &lt;array&gt; &lt;string&gt;d&lt;/string&gt; &lt;string&gt;g&lt;/string&gt; &lt;string&gt;k&lt;/string&gt; &lt;string&gt;t&lt;/string&gt; &lt;string&gt;gr&lt;/string&gt; &lt;/array&gt; &lt;key&gt;nmCons&lt;/key&gt; &lt;array&gt; &lt;string&gt;d&lt;/string&gt; &lt;string&gt;g&lt;/string&gt; &lt;string&gt;k&lt;/string&gt; &lt;string&gt;t&lt;/string&gt; &lt;string&gt;r&lt;/string&gt; &lt;string&gt;s&lt;/string&gt; &lt;string&gt;z&lt;/string&gt; &lt;string&gt;kt&lt;/string&gt; &lt;string&gt;rs&lt;/string&gt; &lt;string&gt;gr&lt;/string&gt; &lt;/array&gt; &lt;key&gt;neCons&lt;/key&gt; &lt;array&gt; &lt;string&gt;r&lt;/string&gt; &lt;string&gt;s&lt;/string&gt; &lt;string&gt;z&lt;/string&gt; &lt;/array&gt; &lt;key&gt;nsVowel&lt;/key&gt; &lt;array&gt; &lt;string&gt;e&lt;/string&gt; &lt;string&gt;u&lt;/string&gt; &lt;/array&gt; &lt;key&gt;nmVowel&lt;/key&gt; &lt;array&gt; &lt;string&gt;a&lt;/string&gt; &lt;string&gt;e&lt;/string&gt; &lt;string&gt;i&lt;/string&gt; &lt;string&gt;o&lt;/string&gt; &lt;string&gt;u&lt;/string&gt; &lt;/array&gt; &lt;key&gt;neVowel&lt;/key&gt; &lt;array&gt; &lt;string&gt;a&lt;/string&gt; &lt;string&gt;u&lt;/string&gt; &lt;/array&gt; &lt;key&gt;tick&lt;/key&gt; &lt;array&gt; &lt;string&gt;&amp;apos;&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/plist&gt; </code></pre>
[]
[ { "body": "<p>It generally looks like good code to me, so these come under \"nits\":</p>\n\n<ul>\n<li><p>In <code>-initWithGrammar:</code> you're actually passing the <em>name</em> of the grammar, not the grammar itself. Perhaps <code>-initWithGrammarName:</code> would be better.</p></li>\n<li><p>It's conventional not to use accessors in initialisers or destructors, because the object isn't in a consistent state during these methods. This means replacing <code>self.grammar =</code> with <code>_grammar =</code> in the initialiser.</p></li>\n<li><p>Given the change made above, why does the <code>grammar</code> property need to be readwrite? Customers of your class pass a filename into the initialiser and then, presumably, never change the constructed dictionary so it can be <code>readonly</code>.</p></li>\n<li><p>in <code>replaceKey:</code>, if the plist happens to contain a number or a dictionary value for the key then you'll return that instead of an <code>NSString</code>. I realise the grammar format isn't supposed to do that but it's good form to assert this so that when it does happen, people find out the easy way.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:11:07.737", "Id": "14659", "ParentId": "14649", "Score": "2" } } ]
{ "AcceptedAnswerId": "14659", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T07:59:28.567", "Id": "14649", "Score": "2", "Tags": [ "objective-c", "random", "generator" ], "Title": "Objective-C CF Random Name Generator" }
14649
<p>I'm very new to C++, but I really want to write good code and increase my development skill, so I ask you for some review.</p> <p><a href="http://www.gliffy.com/go/publish/3797990/" rel="nofollow noreferrer" title="scheme">Scheme of socket server</a></p> <p>This is the scheme of how my socket server works. It creates a socket, binds it, sets to listen state, creates a new thread (in order not to block the execution of the program), which accepts new connections, creates new threads for each client, reads data from them and dispatches data to observers (server is a child of <code>Observable</code> class, which allows to dispatch events to <code>Observers</code>.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string.h&gt; #include &lt;stdio.h&gt; #include &lt;vector&gt; #include &lt;arpa/inet.h&gt; #include &lt;sys/socket.h&gt; #include &lt;pthread.h&gt; #include "Observer.h" using namespace std; class SocketServer : public Observable { private: string serverIp; int serverPort; int masterSocket; void SocketCreate ( ); void SocketBind ( ); void SocketListen ( ); static void* SocketAccept ( void* ); static void* SocketRead ( void* ); void RequestDispatch ( int , string ); public: SocketServer ( string , int ); static void Send ( int , string ); static void Log ( int , string ); }; struct ClientRequest { int socketFD; string request; }; struct ServerAndSocket { SocketServer* socketServer; int socketFD; }; SocketServer::SocketServer ( string serverIp , int serverPort ) { this-&gt;serverIp = serverIp; this-&gt;serverPort = serverPort; this-&gt;SocketCreate(); this-&gt;SocketBind(); this-&gt;SocketListen(); pthread_create ( new pthread_t() , NULL , SocketServer::SocketAccept, this ); }; void SocketServer::SocketCreate ( ) { this-&gt;masterSocket = socket ( AF_INET , SOCK_STREAM , 0 ); if ( this-&gt;masterSocket &lt; 0 ) { perror ( "socket" ); _exit(0); } else { int opt = 1; setsockopt (this-&gt;masterSocket, SOL_SOCKET, SO_REUSEADDR, &amp;opt, sizeof (opt)); cout &lt;&lt; "Socket created successfully with file descriptor " &lt;&lt; this-&gt;masterSocket &lt;&lt; "\n"; }; }; void SocketServer::SocketBind ( ) { struct sockaddr_in serverAddress; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons ( this-&gt;serverPort ); serverAddress.sin_addr.s_addr = inet_addr ( this-&gt;serverIp.data()); if ( bind ( this-&gt;masterSocket , (sockaddr*)&amp;serverAddress , sizeof ( serverAddress ) ) &lt; 0 ) { perror ( "bind" ); _exit(0); } else { cout &lt;&lt; "Socket bound successfully to the " &lt;&lt; this-&gt;serverIp &lt;&lt; ":" &lt;&lt; this-&gt;serverPort &lt;&lt; " address\n"; }; }; void SocketServer::SocketListen ( ) { listen ( this-&gt;masterSocket , 5 ); cout &lt;&lt; "Socket is beeing listened now\n"; }; void* SocketServer::SocketAccept ( void* serverPointer ) { int socketFD; pthread_t* clientThread; ClientRequest clientRequest; SocketServer* this_; ServerAndSocket serverAndSocketPtr; this_ = (SocketServer*)serverPointer; while ( 1 ) { socketFD = accept ( this_-&gt;masterSocket , NULL , NULL ); if ( socketFD &lt; 0 ) { perror ( "accept" ); } else { this_-&gt;RequestDispatch ( socketFD , "CLIENT_CONNECTED" ); serverAndSocketPtr.socketServer = this_; serverAndSocketPtr.socketFD = socketFD; pthread_create ( new pthread_t() , NULL , SocketServer::SocketRead, &amp;serverAndSocketPtr ); }; }; }; void* SocketServer::SocketRead ( void* serverAndSocketPointer ) { char input[256]; int inputLength; SocketServer* socketServerPtr; int socketFD; ServerAndSocket* serverAndSocketPtr; serverAndSocketPtr = (ServerAndSocket*)serverAndSocketPointer; socketServerPtr = serverAndSocketPtr-&gt;socketServer; socketFD = serverAndSocketPtr-&gt;socketFD; while ( 1 ) { memset ( (void*)&amp;input , '\0' , sizeof ( input ) ); inputLength = read ( socketFD , (void*)&amp;input , 255 ); if ( inputLength &lt; 0 ) { perror ( "read" ); } else if ( inputLength == 0 || input[0] == '\0' ) { socketServerPtr-&gt;RequestDispatch ( socketFD , "CLIENT_DISCONNECTED" ); pthread_exit( NULL ); } else { socketServerPtr-&gt;RequestDispatch ( socketFD , input ); }; }; }; void SocketServer::RequestDispatch ( int socketFD , string request ) { struct ClientRequest clientRequest; SocketServer::Log ( socketFD , "---&gt; " + request ); clientRequest.socketFD = socketFD; clientRequest.request = request; this-&gt;DispatchEvent ( (void*)&amp;clientRequest ); }; void SocketServer::Send ( int socketFD , string message ) { int bytesWritten; bytesWritten = write ( socketFD , message.c_str() , message.size() + 1 ); if ( bytesWritten &lt; 0 ) { perror ( "write" ); } else { SocketServer::Log ( socketFD , "&lt;--- " + message ); }; }; void SocketServer::Log ( int socketFD , string message ) { sockaddr address; socklen_t addressLength; sockaddr_in* addressInternet; string ip; int port; getpeername ( socketFD , &amp;address , &amp;addressLength ); addressInternet = (struct sockaddr_in*)&amp;address; ip = inet_ntoa ( addressInternet-&gt;sin_addr ); port = addressInternet-&gt;sin_port; cout &lt;&lt; ip &lt;&lt; ":" &lt;&lt; port &lt;&lt; " " &lt;&lt; message &lt;&lt; "\n"; }; </code></pre> <p>A year after this code grew to a <a href="https://codereview.stackexchange.com/questions/30761/object-oriented-linux-networking-library">Object-oriented Linux networking library</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T18:43:44.100", "Id": "23811", "Score": "1", "body": "Using a thread per connection is not very scalable. Its OK if your expect your connection count to be in the low teens but after that not so much. Have a look at `select()` as a starting point epoll() is a natural extension to select() but takes a bit more work. It allows you to have one thread service all connections simultaneously." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:22:37.760", "Id": "23901", "Score": "0", "body": "you forgot that ports in `sockaddr` structs are network byte-order, so use `ntohs()` in the `Log()` method" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-01T20:30:21.053", "Id": "105713", "Score": "0", "body": "@LokiAstari could I ask for a reference where using a thread per connection fails to scale past the teens? afaik performance will stop scaling once you go beyond your CPU core count and memory may become an issue going past 2k (2gb), but I don't see why such a relatively low number would cause issues" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-01T22:59:50.317", "Id": "105730", "Score": "1", "body": "@user2813274: The apache blog would be a good place to start. Then do some research into the `C10k problem`. That should find you enough references on the issue." } ]
[ { "body": "<pre><code>#include &lt;iostream&gt;\n#include &lt;string.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;vector&gt;\n#include &lt;arpa/inet.h&gt;\n#include &lt;sys/socket.h&gt;\n#include &lt;pthread.h&gt;\n#include \"Observer.h\"\n\nusing namespace std;\n</code></pre>\n\n<p>This is fine for trivial demo code and such, but more often a mistake for anything larger or more serious.</p>\n\n<pre><code>class SocketServer : public Observable {\n</code></pre>\n\n<p>Personally, I think I'd prefer this as something like:</p>\n\n<pre><code>namespace Socket {\n class Server {\n // ...\n };\n}\n</code></pre>\n\n<hr>\n\n<pre><code> void SocketCreate();\n void SocketBind();\n void SocketListen();\n static void* SocketAccept(void*);\n static void* SocketRead(void*);\n</code></pre>\n\n<p>...then these would become just : <code>Create</code>, <code>Bind</code>, <code>Listen</code>, <code>Accept</code>, and <code>Read</code> (but the full names would be, for example, <code>Socket::Server::Create</code>, remaining quite self-explanatory).</p>\n\n<pre><code>SocketServer::SocketServer(string serverIp, int serverPort)\n{\n this-&gt;serverIp = serverIp;\n this-&gt;serverPort = serverPort;\n</code></pre>\n\n<p>A member initializer list is generally preferable:</p>\n\n<pre><code>Server::Server(string serverIp, int serverPort) : serverIp(ServerIp), serverPort(serverPort) {\n</code></pre>\n\n<hr>\n\n<pre><code> this-&gt;SocketCreate();\n this-&gt;SocketBind();\n this-&gt;SocketListen();\n</code></pre>\n\n<p><code>this-&gt;</code> is ugly noise. Avoid it.</p>\n\n<pre><code> pthread_create(new pthread_t(), NULL, SocketServer::SocketAccept, this);\n</code></pre>\n\n<p>If at all possible, you almost certainly want to use C++11's built-in thread support instead of using pthreads directly. The result is not only much more portable, but nearly always quite a bit cleaner as well.</p>\n\n<pre><code>void SocketServer::SocketCreate()\n{\n this-&gt;masterSocket = socket(AF_INET, SOCK_STREAM, 0);\n if (this-&gt;masterSocket &lt; 0)\n</code></pre>\n\n<p>One more time: <code>this-&gt;</code> is ugly noise that should be avoided whenever possible (and at least in C++, that's nearly always).</p>\n\n<pre><code> {\n perror(\"socket\");\n _exit(0);\n }\n</code></pre>\n\n<p>In my opinion, this is a <em>terrible</em> idea. Code at this level shouldn't set policy about how errors are handled this way. It should (probably) retrieve the error message string using <code>strerror</code>, then throw an exception.</p>\n\n<pre><code> else\n {\n int opt = 1;\n setsockopt(this-&gt;masterSocket, SOL_SOCKET, SO_REUSEADDR, &amp;opt, sizeof (opt));\n cout &lt;&lt; \"Socket created successfully with file descriptor \" &lt;&lt; this-&gt;masterSocket &lt;&lt; \"\\n\";\n</code></pre>\n\n<p>Again, using <code>cout</code> for something on the order of logging seems a rather poor idea.</p>\n\n<pre><code> if (bind(this-&gt;masterSocket, (sockaddr*) &amp;serverAddress, sizeof (serverAddress)) &lt; 0)\n {\n perror(\"bind\");\n _exit(0);\n }\n else\n {\n cout &lt;&lt; \"Socket bound successfully to the \" &lt;&lt; this-&gt;serverIp &lt;&lt; \":\" &lt;&lt; this-&gt;serverPort &lt;&lt; \" address\\n\";\n };\n</code></pre>\n\n<p>I'll note what a poor idea this is one last time, and leave it at that.</p>\n\n<pre><code> char input[256];\n</code></pre>\n\n<p>This size should probably be set with a named constant instead of a magic number.</p>\n\n<pre><code>memset((void*) &amp;input, '\\0', sizeof (input));\n</code></pre>\n\n<p>This seems to be pointless.You gain nothing from setting this memory to 0's immediately before <code>read</code> puts its data into the</p>\n\n<pre><code> inputLength = read(socketFD, (void*) &amp;input, 255);\n</code></pre>\n\n<p>This should almost certainly use something like <code>sizeof(input)-1</code> instead of <code>255</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T04:45:19.493", "Id": "43901", "ParentId": "14650", "Score": "4" } }, { "body": "<p>I think you should probably add a few destructors (think <a href=\"http://www.stroustrup.com/bs_faq2.html#finally\" rel=\"nofollow\">RAII</a>) so both the open socket and the listening sockets always get properly closed.</p>\n\n<p>Oh, and while Jerry's comments are pretty good, ignore the one about using </p>\n\n<pre><code>this-&gt;\n</code></pre>\n\n<p>Its not 'noise', its actually a good practice according to several coding guidelines I've worked with. Your compiler doesn't need it, but it does make your code more readable to other project members.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-08T23:21:17.910", "Id": "233586", "Score": "0", "body": "Using `this->` is not idiomatic C++. Also if you need to use it because you have shadowed variables your code is actually more brittle (because if you forget to use it then you are not doing what you expect). It is better to not use and turn on warnings and the compiler will tell when you are code is breaking." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T07:06:01.913", "Id": "43908", "ParentId": "14650", "Score": "-2" } }, { "body": "<p>Something I hadn't seen anyone else pick up on which I think deserves mention is in regards to your <code>Send</code> method implementation <strong>not handling incomplete writes</strong>. According to a <a href=\"http://man7.org/linux/man-pages/man2/write.2.html\" rel=\"nofollow noreferrer\">manual page for the write system call</a> (and experience) you are not guaranteed that <code>bytesWritten</code> will be all of the bytes that you've requested: \"It is not an error if this number is smaller than the number of bytes requested\".</p>\n\n<p>This can be remedied by adding code in your <code>Send</code> method to loop over the writing of the data. Something in C++11 or newer that might look like:</p>\n\n<pre><code>void SocketServer::Send(int socketFD, string message)\n{\n auto bytesToSend = message.length();\n auto messagePtr = message.c_str();\n while (bytesToSend &gt; 0)\n {\n const auto bytesWritten = write(socketFD, messagePtr, bytesToSend);\n if (bytesWritten == -1)\n {\n // do your error handling and possibly return depending on errno.\n }\n else\n {\n bytesToSend -= bytesWritten;\n messagePtr += bytesWritten;\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-17T18:26:34.537", "Id": "155624", "ParentId": "14650", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T08:38:01.927", "Id": "14650", "Score": "6", "Tags": [ "c++", "beginner", "linux", "tcp" ], "Title": "TCP socket server for UNIX" }
14650
<p>This is a buy and sell game. I've revised it, though it's still unfinished. I would appreciate it if someone could review it again for me. </p> <pre><code>#include&lt;stdio.h&gt; #include&lt;conio.h&gt; #include&lt;time.h&gt; #include&lt;stdlib.h&gt; void end() { system("cls"); int P, L, choice; printf(" *********** \n"); printf(" END OF GAME \n"); printf(" *********** \n"); if(choice == P) main(); else if(choice == L) exit(0); } int PhoenixDown(int *phoenixdown) { srand(time(NULL)); *phoenixdown=rand()%(1200-500+1)%650; return *phoenixdown; } int ElixirEssence(int *elixiressence) { srand(time(NULL)); *elixiressence=rand()%(2100-1500+1)%910;\ return *elixiressence; } int PlatinumIngot(int *platinumingot) { srand(time(NULL)); *platinumingot=rand()%(7000-5000+1)%1950; return *platinumingot; } int GoldenMateria(int *goldenmateria) { srand(time(NULL)); *goldenmateria=rand()%(5500-3500+1)%2600; return *goldenmateria; } int Scarletite(int *scarletite) { srand(time(NULL)); *scarletite=rand()%(12000-8000+1)%6500; return *scarletite; } int Adamantite(int *adamantite) { srand(time(NULL)); *adamantite=rand()%(30000-15000+1)%13500; return *adamantite; } int DarkMatter(int *darkmatter) { srand(time(NULL)); *darkmatter=rand()%(70000-40000+1)%36400; return *darkmatter; } int Trapezohedron(int *trapezohedron) { srand(time(NULL)); *trapezohedron=rand()%(90000-60000+1)%39000; return *trapezohedron; } int buyitem(int x, int y)//* function used to buy an item at any store*// { int bought; bought=x-y; return bought; //*returns the value of the difference between x and y*// } void Tycoons(int *gil,int *onhand,int *day,int *debt, int *phoenixdown, int *elixiressence, int *platinumingot,int *goldenmateria, int *scarletite,int *adamantite, int *darkmatter, int *trapezohedron )//*function used as a shop, it does not return anything*// { int i, j, g, on, d, de, count, N, option,p, e,pl,gm,s,a,dm,t; d=*day; g=*gil; de=*debt; on=*onhand; system("cls"); printf("************************\n"); printf("Tycoon Meteor's Minerals\n"); printf("************************\n"); printf("\n"); printf("Shopkeeper: Welcome! How may I be of service?\n"); printf("\n"); printf("Item On hand Price\n"); printf("\n"); printf("Phoenix Down %d %dG\n", on, PhoenixDown(&amp;p)); printf("Elixir Essence %d %dG Day #%d\n",on,ElixirEssence(&amp;e), d); printf("Platinum Ingot %d %dG Gil:%d\n", on,PlatinumIngot(&amp;p), g); printf("Golden Materia %d %dG Debt:%d\n", on,GoldenMateria(&amp;gm), de); printf("Scarlette %d %dG\n",on,Scarletite(&amp;s)); printf("Adamintite %d %dG\n",on,Adamantite(&amp;a)); printf("Dark Matter %d %dG\n",on,DarkMatter(&amp;dm)); printf("Trapezohedron %d %dG\n",on,Trapezohedron(&amp;t)); printf("\n"); printf("[1]Buy [2]Sell [3]leave\n"); printf("\n"); printf("Option: ", option); scanf("%d", &amp;option); if(option == 1) { system("cls"); printf("************************\n"); printf("Tycoon Meteor's Minerals\n"); printf("************************\n"); printf("\n"); printf("Shopkeeper: Buying an item? Which one?\n"); printf("\n"); printf("Item On hand Price\n"); printf("\n"); printf("[1]Phoenix Down %d %dG\n", on, PhoenixDown(&amp;p)); printf("[2]Elixir Essence %d %dG Day #%d\n",on,ElixirEssence(&amp;e), d); printf("[3]Platinum Ingot %d %dG Gil:%d\n", on,PlatinumIngot(&amp;p), g); printf("[4]Golden Materia %d %dG Debt:%d\n", on,GoldenMateria(&amp;gm), de); printf("[5]Scarlette %d %dG\n",on,Scarletite(&amp;s)); printf("[6]Adamintite %d %dG\n",on,Adamantite(&amp;a)); printf("[7]Dark Matter %d %dG\n",on,DarkMatter(&amp;dm)); printf("[8]Trapezohedron %d %dG\n",on,Trapezohedron(&amp;t)); printf("\n"); printf("Option: ", option); scanf("%d", &amp;option); if(option == 1 || option == 2 || option == 3 || option == 4|| option == 5 || option == 6 || option == 7 || option ==8) { if(option == 1 &amp;&amp; g&gt;PhoenixDown(&amp;p)) {buyitem(g,PhoenixDown(&amp;p)); on++; Tycoons(gil,onhand,day,debt,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron);} else if(option == 2 &amp;&amp; g&gt;ElixirEssence(&amp;e)) {buyitem(g,ElixirEssence(&amp;e)); on++; Tycoons(gil,onhand,day,debt,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron);} else if(option == 3 &amp;&amp; g&gt;PlatinumIngot(&amp;p)) {buyitem(g,PlatinumIngot(&amp;p)); on++; Tycoons(gil,onhand,day,debt,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron);} else if(option == 4 &amp;&amp; g&gt;GoldenMateria(&amp;gm)) {buyitem(g,GoldenMateria(&amp;gm)); on++; Tycoons(gil,onhand,day,debt,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron);} else if(option == 5 &amp;&amp; g&gt;Scarletite(&amp;s)) {buyitem(g,Scarletite(&amp;s)); on++; Tycoons(gil,onhand,day,debt,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron);} else if(option == 6 &amp;&amp; g&gt;Adamantite(&amp;a)) {buyitem(g,Adamantite(&amp;a)); on++; Tycoons(gil,onhand,day,debt,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron);} else if(option == 7 &amp;&amp; g&gt;DarkMatter(&amp;dm)) {buyitem(g,DarkMatter(&amp;dm)); on++; Tycoons(gil,onhand,day,debt,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron);} else if(option == 8 &amp;&amp; g&gt;Trapezohedron(&amp;t)) {buyitem(g,Trapezohedron(&amp;t)); on++; Tycoons(gil,onhand,day,debt,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron);} } } else if(option == 3) { main(gil,onhand,day,debt,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron); d++; de *= (0.15); } else { printf("wrong option"); Tycoons(gil,onhand,day,debt,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron); } } void mainrift(int *gil,int *onhand,int *day,int *debt, int *phoenixdown, int *elixiressence, int *platinumingot,int *goldenmateria, int *scarletite,int *adamantite, int *darkmatter, int *trapezohedron) { int d, g, de, Choice, on; char quit; d = 1; g=20000; de=50000; char option; on= 0; system("cls"); printf("\n"); printf("Gilgamesh: Where should my travels take me to?\n"); printf("\n"); printf("[1]Tycoon Meteor's Minerals Day #%d\n", d); printf("[2]Pulsian Restoratives Gil: %d\n", g); printf("[3]Archadian Luxuries Debt: %d\n", de); printf("[4]Cid's Magical Escapades\n"); printf("[5]Gaian Gratitudes\n"); printf("[6]Riches and Minerals of Spira [Q]uit\n", quit); printf("[7]Go see the Merchant of The Rift\n"); printf("\n"); printf("Your Choice: ", Choice); scanf("%d", &amp;Choice); switch(Choice) { case 1: Tycoons(&amp;g,&amp;on,&amp;d,&amp;de,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron); break; case 'Q': end(); exit(0); break; } } int main(int *gil,int *onhand,int *day,int *debt, int *phoenixdown, int *elixiressence, int *platinumingot,int *goldenmateria, int *scarletite,int *adamantite, int *darkmatter, int *trapezohedron) { int d, g, de, on; system("cls"); int choice, S, L; printf(" ***************************** \n"); printf(" GILGAMESH MEGA GIL ADVENTURES \n"); printf(" ***************************** \n"); printf("\n\n\n\n\n\n\n\n"); printf("[S]tart\n\n"); printf("[L]eave\n\n"); printf("Choice: ", choice); scanf("%d", &amp;choice); switch(choice) { case 'S': mainrift(&amp;g,&amp;on,&amp;d,&amp;de,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron); break; case 'L': exit(0); break; } getch(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T10:41:52.087", "Id": "23776", "Score": "0", "body": "It is just a minor suggestion, but try not to put actual values in numbers in code. For example: *phoenixdown=rand()%(1200-500+1)%650 . Define what 1200, 500 or 650 mean. Use proper named constants and enums (for the option part for example)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T11:15:20.043", "Id": "23778", "Score": "0", "body": "hmm, i see, but i actually need to make it random." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T11:43:36.727", "Id": "23780", "Score": "0", "body": "It would still be random, but it would be rand()%(some_meaningful_name1 - some_meaningful_name2 + 1) % some_meaningful_name3 . It would be easiser to understand, easier to modify and it respects the C language guidelines http://www.lrdev.com/lr/c/ccgl.html#numbers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:03:19.223", "Id": "23781", "Score": "0", "body": "okay, also, my functions didn't work after i revised it, any suggestions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:11:09.697", "Id": "23785", "Score": "0", "body": "You should only post *working* code here, so that it can be *improved*. If some parts aren't working, ask on stackoverflow if they can help you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T14:39:24.227", "Id": "23798", "Score": "0", "body": "See also [CR14580](http://codereview.stackexchange.com/questions/14580/how-can-i-improve-reduce-this-code/14591#14591)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T14:48:53.123", "Id": "23801", "Score": "1", "body": "Welcome to Code Review. Please note that the preferred way of saying 'thanks' around here is by up-voting good questions and helpful answers (once you have enough reputation to do so), and by accepting the most helpful answer to any question you ask (which also gives you a small boost to your reputation). Please see the [FAQ](http://codereview.stackexchange.com/faq) and especially [How do I ask questions here?](http://codereview.stackexchange.com/faq#howtoask)" } ]
[ { "body": "<p>I don't know any C, so I can't comment on the actual code. But it seems to me like you could move the text to txt files or xml files, instead of literally placing it in your code. You could probably walk through the txt file and print the text in a loop, rather than each line on its own. </p>\n\n<p>If you really want to keep the text in the code, you could move the print lines to separate functions to clean it up. As an example, let's clean this part:</p>\n\n<pre><code>void mainrift(int *gil,int *onhand,int *day,int *debt, int *phoenixdown, int *elixiressence, int *platinumingot,int *goldenmateria, int *scarletite,int *adamantite, int *darkmatter, int *trapezohedron)\n{\n //your code\n }\n</code></pre>\n\n<p>I would create a new function <code>printMainRift()</code>:</p>\n\n<pre><code>void printMainRift(int *gil,int *day,int *debt)\n{\n printf(\"\\n\");\n printf(\"Gilgamesh: Where should my travels take me to?\\n\");\n printf(\"\\n\");\n printf(\"[1]Tycoon Meteor's Minerals Day #%d\\n\", d);\n printf(\"[2]Pulsian Restoratives Gil: %d\\n\", g);\n printf(\"[3]Archadian Luxuries Debt: %d\\n\", de);\n printf(\"[4]Cid's Magical Escapades\\n\");\n printf(\"[5]Gaian Gratitudes\\n\");\n printf(\"[6]Riches and Minerals of Spira [Q]uit\\n\", quit);\n printf(\"[7]Go see the Merchant of The Rift\\n\");\n printf(\"\\n\");\n}\n</code></pre>\n\n<p>The original function would become:</p>\n\n<pre><code>void mainrift(int *gil,int *onhand,int *day,int *debt, int *phoenixdown, int *elixiressence, int *platinumingot,int *goldenmateria, int *scarletite,int *adamantite, int *darkmatter, int *trapezohedron)\n{\n int d, g, de, Choice, on;\n char quit;\n d = 1;\n g=20000;\n de=50000;\n char option;\n on= 0;\n system(\"cls\");\n printMainRift(g, on, d, de);\n printf(\"Your Choice: \", Choice);\n scanf(\"%d\", &amp;Choice);\n switch(Choice)\n {\n case 1:\n Tycoons(&amp;g,&amp;on,&amp;d,&amp;de,phoenixdown,elixiressence,platinumingot,goldenmateria,scarletite,adamantite,darkmatter,trapezohedron);\n break;\n case 'Q':\n end();\n exit(0);\n break;\n }\n }\n</code></pre>\n\n<p>This seems a bit better already :) But I think it would still be better to move the text to .txt files</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T11:59:38.227", "Id": "14658", "ParentId": "14652", "Score": "2" } }, { "body": "<p>Are you familiar with structures and arrays in C?</p>\n\n<p>Detailed critique of a minor part of your system:</p>\n\n<pre><code>void end()\n{\n system(\"cls\");\n int P, L, choice;\n printf(\" *********** \\n\");\n printf(\" END OF GAME \\n\");\n printf(\" *********** \\n\");\n if (choice == P)\n main();\n else if (choice == L)\n exit(0);\n}\n</code></pre>\n\n<p>I'm not keen on <code>system(\"cls\")</code> as a way of clearing the screen, but on Windows, it works.</p>\n\n<p>You don't need the trailing blanks at the end of each line of the 'end of game' message.</p>\n\n<p>You don't initialize any of <code>P</code>, <code>L</code> or <code>Choice</code> (so they contain indeterminate garbage), but you compare <code>Choice</code> with <code>P</code> and if they're equal, you call <code>main()</code> once more; if <code>Choice</code> is equal to <code>L</code>, you exit with success (which is good), and otherwise you return. You should think hard about this. Presumably, you needed a prompt such as '<code>Play again (P) or Leave (L):</code>' and then you need to get input for which <code>'P'</code> and <code>'L'</code> are possible inputs. You'd probably want to upshift what the user typed, too.</p>\n\n<p>While it is possible in C (but not C++) to call <code>main()</code> again, it is aconventional to do so. On the whole, you'd be better off not doing so. Your main program should have a loop which invokes the game (a function call), and then calls the <code>end()</code> function to get the choice from the user. If the choice is <code>'P'</code>, then you loop and play the game again; otherwise, you exit the loop and then the whole program.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T15:52:50.523", "Id": "14665", "ParentId": "14652", "Score": "3" } }, { "body": "<p>A quick glance:</p>\n\n<pre><code>srand(time(NULL));\n</code></pre>\n\n<p>Should <strong>ONLY</strong> be called once.</p>\n\n<pre><code>int main()\n{\n #if !defined(TESTING)\n srand(time(NULL));\n #endif\n\n // Your code\n}\n</code></pre>\n\n<p>Calling srand() resets the random number sequence and thus makes the next number not so random.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T08:04:19.950", "Id": "23842", "Score": "0", "body": "yes but it's reinitialised with the current timestamp" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T08:06:51.840", "Id": "23843", "Score": "0", "body": "@hroptatyr: Yes. That is wrong. **Never** do that. Initialize it once. Otherwise you will not get a random (to the human eye) sequence." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T18:46:31.210", "Id": "14667", "ParentId": "14652", "Score": "2" } }, { "body": "<p>I have a few points, some of which duplicate what others have said but are\nincluded for completeness:</p>\n\n<ul>\n<li><p>What are you trying to achieve? Give some more detail as a header to the\nprogram.</p></li>\n<li><p>Turn on more warnings (lots more) on your compiler.</p></li>\n<li><p>All functions except main() should be static</p></li>\n<li><p>Be consistent with naming. Some functions are lowercase, some are camel-case etc.</p></li>\n<li><p>end() is using uninitialised variables. Better to exit by returning from\nmain() if possible. Also <code>end()</code> should be <code>end(void)</code>. And why are you\ncalling main ???</p></li>\n<li><p>Functions <code>PheonixDown</code> etc: </p>\n\n<ul>\n<li><p>why do you need the output parameters in all of these functions; </p></li>\n<li><p>don't call srand in each function; </p></li>\n<li><p>numbers produced by <code>rand() % x</code> will not be truely random; </p></li>\n<li><p>use constants for numerics.</p></li>\n</ul></li>\n<li><p><code>buyitem()</code> is verbose and terminating comment is just noise: </p>\n\n<pre><code>int buyitem(int x, int y) \n{\n return x - y;\n}\n</code></pre></li>\n<li><p><code>Tycoons()</code> has too many parameters - pass a\nstructure, perhaps.</p>\n\n<ul>\n<li><p>you have 8 lines of duplicated printing from <code>printf(\"Phoenix Down ...</code></p></li>\n<li><p>yikes! it's recursive here too! What are you doing??? In C, it is best\nto avoid recursion unless you really know what you are doing...</p></li>\n</ul></li>\n</ul>\n\n<p>I'm bailing out there - you really need to start again. First write down what\nyou want to achive. Then write it as a sequence or flow chart. Then code it\nstarting with a <code>main</code>, which has the prototype <code>int main(int argc, char **\nargv);</code> and use a loop in main, calling a function that does the guts of your\nprogram.</p>\n\n<p>Sorry to be negative, but you are on the wrong tracks completely and are\nbetter off realising it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T02:49:19.143", "Id": "14677", "ParentId": "14652", "Score": "3" } }, { "body": "<p>Here is feedback on C programming and style only. I haven't looked at algorithms or performance:</p>\n<p><strong>Style</strong></p>\n<ul>\n<li>In general, your source code would benefit from adding empty lines here and there, to separate sections of the code that aren't related to each other. Especially between different functions. This is de facto standard coding style, everyone adds empty lines between different functions.</li>\n<li>You really need to fix your indention . If you use tab key for intention, then setup your editor so that it inserts spaces and not tab characters. Never write code on the same line as the opening <code>{</code> nor at the same line as the closing <code>}</code>.</li>\n<li>Avoid &quot;magic numbers&quot;, ie strange numeric constants in the meaning of the code. Define these numbers as constants, at a central location of your program (either as #defines or as const variables).</li>\n<li>Use meaningful variable names, not &quot;i, j, k, l, a, b, c&quot;.</li>\n<li>Parameters that are passed by pointer by a function, but not modified by that function, should be declared as <code>const</code>. Search the web for &quot;<a href=\"http://en.wikipedia.org/wiki/Const-correctness\" rel=\"nofollow noreferrer\">const correctness</a>&quot;.</li>\n<li>Try to keep each row short. Out of tradition, programmers strive to keep lines less than 80 characters (for historical reasons: this was the screen width on ancient operative systems). Instead of <code>func(param1, param2, param3, param4, param5);</code> you can write each parameter on a separate source code row. Example below.</li>\n</ul>\n<hr />\n<pre><code>func (param1, // comment explaining param1\n param2, // comment explaining param2 ...and so on\n param3,\n param4,\n param5);\n</code></pre>\n<p><strong>Bugs</strong></p>\n<ul>\n<li><p>srand() must only be called one single time in your program, before any call to rand(). Otherwise you will keep seeding the random generator, in this case with the same number, meaning you could keep getting the same sequence of numbers that are not random at all.</p>\n</li>\n<li><p>There is absolutely no reason for your program to use recursive functions, they will only slow down, and possibly crash your program. Especially don't do this if you don't know what a recursive function is :) (It is a function calling itself from inside its own body). The uses of recursive functions are few, they are limited to various searching and sorting algorithms that aren't really suitable beginner topics.</p>\n</li>\n<li><p>Please note that all your floating point arithmetic has no use on variables declared as <code>int</code> and your program therefore won't behave as you expect. If you need floating point accuracy, you need to use <code>float</code> variables.</p>\n</li>\n<li><p>Note that scanf() leaves an empty line feed character ('\\n') in the input buffer each time the user presses enter. These line feed characters need to be discarded or you might get them as user input instead of what you expected. (Every single C beginner encounters this bug) Easiest way to dodge it is to always keep an empty space at the beginning of scanf: <code>scanf(&quot; %d, x);</code>. This initial space in the scanf format string tells it to get rid of all whitespace characters, including the pesky line feed one.</p>\n</li>\n</ul>\n<p><strong>Dangerous practice</strong></p>\n<ul>\n<li><p>In C, avoid empty parameter lists such as <code>void end()</code>. It means &quot;accept any parameter&quot; and can lead to bugs. (In C++ however, and empty () is considered proper style.)</p>\n</li>\n<li><p>Never call main() from your program. Not only does it suggest an obscure program design, it may also cause severe, stack-related bugs if the compiler assumes that main() won't be called from anywhere but the &quot;invisible&quot; startup routines executed before your program.</p>\n</li>\n<li><p>Don't invent your own parameters to main(). Either use <code>int main (void)</code> or <code>int main(int argc, char *argv[])</code>. Don't use any other form of main.</p>\n</li>\n<li><p>Never use the exit() function. Reasons why can be found <a href=\"http://www.flounder.com/badprogram.htm#ExitProcess\" rel=\"nofollow noreferrer\">here</a>.</p>\n</li>\n</ul>\n<p><strong>General advise</strong></p>\n<p>Never write the whole big program at once. Write a litte bit at a time, compile it, test it, if there is anything wrong with it, fix it. Develop the program a tiny bit at a time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T15:38:27.670", "Id": "14702", "ParentId": "14652", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T09:39:07.617", "Id": "14652", "Score": "4", "Tags": [ "c", "game" ], "Title": "\"Buy and Sell\" game project" }
14652
<p>The following code is pretty ugly. I suspect that there is a more functional and elegant way of achieving this result.</p> <pre><code>var lines = new[]{ new{Head="A",Value="1"}, new{Head="",Value="2"}, new{Head="",Value="3"}, new{Head="",Value="4"}, new{Head="B",Value="5"}, new{Head="B",Value="6"}, new{Head="C",Value="7"}, new{Head="",Value="8"}, new{Head="D",Value="9"}, new{Head="",Value="10"}}; string currentHead=""; string currentValue=""; lines.Select(line=&gt;{ string newHead; string newValue; if (String.IsNullOrEmpty(line.Head)) { newHead = currentHead; } else { newHead = line.Head; currentHead = line.Head; } if (String.IsNullOrEmpty(line.Value)) { newValue = currentValue; } else { newValue = line.Value; currentValue = line.Value; } return new{Head=newHead,Value=newValue};}).ToList(); </code></pre> <p>The desired output is to produce </p> <p>A,1</p> <p>A,2</p> <p>A,3</p> <p>A,4</p> <p>B,5</p> <p>B,6</p> <p>C,7</p> <p>C,8</p> <p>D,9</p> <p>D,10</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:03:31.037", "Id": "23782", "Score": "2", "body": "I don't see a hierarchical list here — I see a bunch of empty keys (and your code depends on the ordering of the array). Do you have any control over the creation of the array, and can you show the code for that? Or is this *really* how the array is filled?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:07:19.877", "Id": "23784", "Score": "0", "body": "Yup, it is deterministically ordered. It is directly transformed from an excel sheet. The excel list is grouped and I need to \"pad\" the empty entries with the last value on that column. Granted that the list type is not hierarchical, but the data is grouped." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:29:29.580", "Id": "23786", "Score": "0", "body": "Do you need that `Value`s there? Can't you compute them? They seem to be 1,2,3,…,10." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:33:47.317", "Id": "23787", "Score": "0", "body": "The live data are not like that. I just created test data in sequence so that it would be easier to see errors in the algorithm. Otherwise, sure, I would use the overload of Select() that provides a running counter." } ]
[ { "body": "<p>You need to look through your code with an analytical eye and discover the pattern that you are implementing. I call it <strong>default if</strong> (null or) <strong>empty</strong>.</p>\n\n<p>So I created an extension method to implement that pattern.</p>\n\n<pre><code>public static string DefaultIfEmpty(this string source, string defaultValue)\n{\n return string.IsNullOrEmpty(source) ? defaultValue : source;\n}\n</code></pre>\n\n<p><em>(Note of caution: you may want to choose a different name for it since this method already exists in LINQ; technically, this is an overload, which could create problems if a future version of C# adds this signature.)</em> </p>\n\n<p>This makes it possible to adapt the LINQ expression:</p>\n\n<pre><code>var currentHead = string.Empty;\nvar currentValue = string.Empty;\nvar result = lines.Select(\n line =&gt;\n {\n currentHead = line.Head.DefaultIfEmpty(currentHead);\n currentValue = line.Value.DefaultIfEmpty(currentValue);\n return new { Head = currentHead, Value = currentValue };\n }).ToList();\n</code></pre>\n\n<p>Sweet, isn't it?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T12:42:10.537", "Id": "14661", "ParentId": "14657", "Score": "3" } }, { "body": "<p>Another options would be to use Aggregate():</p>\n\n<pre><code>var result = lines.Aggregate(\n seed: lines.Take(0).ToList(), // get an empty list of the anonymous type\n func: (list, line) =&gt; {\n list.Add(new {\n // you can implement a fast Last() method for lists or use list[list.Count - 1] if list is long/you're worried about efficiency\n Head = string.IsNullOrEmpty(line.Head) ? list.Last().Head : line.Head,\n Value = string.IsNullOrEmpty(line.Value) ? list.Last().Value : line.Value\n });\n return list;\n }\n);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-03T12:51:03.787", "Id": "24800", "Score": "0", "body": "Very nice trick in generating an empty list of an anonymous type (the seed). More efficient with captured variable in the object initializer: \"Head = (String.IsNullOrEmpty(line.Head))?currentHead : (currentHead=line.Head),\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-01T20:41:24.077", "Id": "15270", "ParentId": "14657", "Score": "1" } } ]
{ "AcceptedAnswerId": "14661", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T11:48:11.463", "Id": "14657", "Score": "2", "Tags": [ "c#", "linq" ], "Title": "LINQ transforming hierachical data to flat list" }
14657
<p>JavaScript is the language everyone uses without bothering to learn it first, and I'm no exception. I'm trying to set up autorefresh with longpolling. What I have on the client side is the following:</p> <pre><code>var getAjaxer = function(element) { return function() { $.ajax({ url: "/path/to/resource", success: function(response) { element.html(response); }, dataType: "html", timeout: 10000, type: "POST", complete: arguments.callee }); }; } var startAjaxing = function() { myajaxer = getAjaxer($("#myid")); myajaxer(); } $(startAjaxing);​ </code></pre> <p>This works, but I'm worried I might be doing it all wrong. Could I get some pointers on how I could use the language more effectively?</p>
[]
[ { "body": "<p>I can't say whether yours is right or wrong but there were a couple of things that seemed odd to me.</p>\n\n<p>I wouldn't add functions to variables unless you intend to use them more than once. (or it adds to the readability)</p>\n\n<pre><code>var startAjaxing = function() {\n myajaxer = getAjaxer($(\"#myid\"));\n myajaxer();\n}\n\n$(startAjaxing);\n</code></pre>\n\n<p>then becomes:</p>\n\n<pre><code>$(function() {\n getAjaxer($(\"#myid\"))();\n}); // Start ajaxing\n</code></pre>\n\n<p>Also I would get rid of <code>arguments.callee</code> and get the element every time:</p>\n\n<pre><code>var getAjaxer = null;\ngetAjaxer = function(elementid) {\n return function() {\n $.ajax({\n url: \"/path/to/resource\",\n success: function(response) {\n $(\"#\" + elementid).html(response);\n },\n dataType: \"html\",\n timeout: 10000,\n type: \"POST\",\n complete: getAjaxer(elementid);\n });\n };\n}\n</code></pre>\n\n<p>To <strong>ME</strong> this seems easier to read butt it may be only a matter of taste. <em>(PS. I didn't check this for syntax errors etc.)</em></p>\n\n<p>If you don't want to create functions every time?</p>\n\n<pre><code>getAjaxer = function(elementid) {\n var elementAjaxer = $(\"#\" + elementid).data(\"ajaxer\");\n if(elementAjaxer == null){\n elementAjaxer = function() {\n $.ajax({\n // etc etc\n });\n };\n $(\"#\" + elementid).data(\"ajaxer\", elementAjaxer);\n }\n return elementAjaxer;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T06:56:19.767", "Id": "14680", "ParentId": "14664", "Score": "1" } } ]
{ "AcceptedAnswerId": "14680", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T15:05:39.233", "Id": "14664", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Setting up longpolling" }
14664
<p>I've got the following code, which works, but seems repetitive. Under DRY principle, how can I clean this up?</p> <pre><code>puts "Blurt out a word" word = gets.chomp word_list = [] word_list.push word until word == "" word = gets.chomp word_list.push word end puts word_list.sort </code></pre>
[]
[ { "body": "<pre><code>puts \"Blurt out a word\"\nword_list = []\nwhile word_list.last != \"\"\n word_list &lt;&lt; gets.chomp\nend\nputs word_list.sort\n</code></pre>\n\n<p>If you prefer the <code>until</code>:</p>\n\n<pre><code>puts \"Blurt out a word\"\nword_list = []\nuntil word_list.last == \"\"\n word_list &lt;&lt; gets.chomp\nend\nputs word_list.sort\n</code></pre>\n\n<p>You can also do it shorter:</p>\n\n<pre><code>puts \"Blurt out a word\"\nword_list = []\nword_list &lt;&lt; gets.chomp until word_list.last == \"\" \nputs word_list.sort\n</code></pre>\n\n<p>Remark: The last (empty) line is also returned. To skip the empty line you may use:</p>\n\n<pre><code>puts word_list[0..-2].sort\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T19:02:11.463", "Id": "14669", "ParentId": "14666", "Score": "6" } }, { "body": "<p>Perhaps </p>\n\n<pre><code>puts 'Blurt..'\nputs STDIN.take_while{|line| line !~ /^$/}.map(&amp;:chomp).sort\n</code></pre>\n\n<p>Edit: <b>Why is this better?</b> Because unlike other approaches it never modifies a variable that is assigned once. Thus it preserves the referential integrity. That is this is a functional programming approach in comparison with others which (as of now) follow an imperative model. The succinctness that results from it is just a bonus.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T19:24:41.317", "Id": "23914", "Score": "0", "body": "you code solo, don't you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T02:51:15.063", "Id": "23950", "Score": "0", "body": "too hard to read?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T13:55:27.900", "Id": "23970", "Score": "0", "body": "i can read it just fine, understanding what it is doing is taking a lot longer than it should." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T19:26:44.743", "Id": "24454", "Score": "0", "body": "+1. @Ryan: This is simple functional programming style, IMO we should expect a competent team to have no problems with it. @rahul: If you have the abstraction `String#present?` you can even write a slightly more declarative `STDIN.take_while(&:present?).map(&:chomp).sort`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T23:16:37.510", "Id": "14675", "ParentId": "14666", "Score": "2" } }, { "body": "<p>Keeping as much of your style as possible, the simple way to avoid repetition is to pull the repetitive phrases inside your loop.</p>\n\n<p>Now I'm assuming that what prevented you from doing this was the fact that Ruby's 'until' loop evaluates the exit condition at the top of the loop, which will therefore throw an error unless you've initialised 'word'. </p>\n\n<p>This inconvenience can be avoided by moving from an 'until' loop to an infinite loop with an <em>internal</em> test / decision / exit condition, like so:</p>\n\n<pre><code>puts \"Blurt out a word\"\nword_list = []\nloop do\nword= gets.chomp\n if word == \"\" \n break\n else \n word_list.push word\n end \nend\nputs word_list.sort\n</code></pre>\n\n<p>Now 'word' is defined before the exit condition is evaluated. And as a useful aside, a blank entry is not inserted into 'word_list'.</p>\n\n<p>There are of course many other ways of doing this -- <strong><em>Ruby allows for cleverness over clarity.</em></strong> The above simply refactors your code and removes the repetition.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T19:20:56.237", "Id": "14714", "ParentId": "14666", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T18:13:51.860", "Id": "14666", "Score": "1", "Tags": [ "ruby" ], "Title": "Clean up this Ruby code under DRY principle" }
14666
<p>I would like to convert ($<code>data</code>):</p> <pre><code>Array ( [login] =&gt; Log in [logout] =&gt; Log out [label] =&gt; Array ( [email] =&gt; test@test.com [name] =&gt; Some name ) [controllers] =&gt; Array ( [page] =&gt; Array ( [title_new] =&gt; New page [title_edit] =&gt; Edit page [submit_button] =&gt; Submit page ) ) ) </code></pre> <p>To (<code>$result</code>):</p> <pre><code>Array ( [login] =&gt; Log in [logout] =&gt; Log out [label[email]] =&gt; test@test.com [label[name]] =&gt; Some name [controllers[page][title_new]] =&gt; New page [controllers[page][title_edit]] =&gt; Edit page [controllers[page][submit_button]] =&gt; Submit page ) </code></pre> <p>The following code works "fine":</p> <pre><code>$data = some_data; $result = array(); foreach ($data as $k =&gt; $v) { if (is_array($v)) foreach ($v as $_k =&gt; $_v) if (is_array($_v)) foreach ($_v as $__k =&gt; $__v) if (is_array($__v)) foreach ($__v as $___k =&gt; $___v) $result[$k.'['.$_k.']['.$__k.']['.$___k.']'] = $___v; else $result[$k.'['.$_k.']['.$__k.']'] = $__v; else $result[$k.'['.$_k.']'] = $_v; else $result[$k] = $v; } </code></pre> <p>The code work nicely for four levels, and after that it returns "Array" as the value. I think I need recursion, but I would like for you to review my current code, and optionally present me with a solution to go even deeper.</p>
[]
[ { "body": "<blockquote>\n <p>So I probably need some kind of recursion, but I have no clue how to get around that with PHP</p>\n</blockquote>\n\n<p>Recursion in PHP is the same as basically any language (well... at a very high level).</p>\n\n<p>I'm very torn on if I think your question is on topic or not, but it's been a long time since I've written anything recursive, and I'm a shameless rep-whore, so here's my go:</p>\n\n<pre><code>function flatten(array $arr, $prefix = '')\n{\n $out = array();\n foreach ($arr as $k =&gt; $v) {\n $key = (!strlen($prefix)) ? $k : \"{$prefix}[{$k}]\";\n if (is_array($v)) {\n $out += flatten($v, $key);\n } else {\n $out[$key] = $v;\n }\n }\n return $out;\n}\n</code></pre>\n\n<p>Or, if you don't like the magical second param:</p>\n\n<pre><code>function _flatten(array &amp;$out, array $arr, $prefix)\n{\n foreach ($arr as $k =&gt; $v) {\n $key = (!strlen($prefix)) ? $k : \"{$prefix}[{$k}]\";\n if (is_array($v)) {\n _flatten($out, $v, $key);\n } else {\n $out[$key] = $v;\n }\n }\n}\n\nfunction flatten(array $arr)\n{\n\n $flat = array();\n _flatten($flat, $arr, '');\n return $flat;\n\n}\n</code></pre>\n\n<p>You could also optimize a bit and make a lot of the things in there references (the for loop values and function params). I tend to avoid references in PHP though unless I have an extremely strong reason for them. (If you plan on using this function on arrays larger than a few hundred elements, that may begin to enter into strong reason land.)</p>\n\n<p>(And <code>flatten</code> is a horrible name, but... yeah.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T10:46:32.880", "Id": "23849", "Score": "0", "body": "Hey, that works pretty great. Usually the arrays are indeed bigger than a few hundred elements, but not like thousands. I will try to get some benchmarks on them. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T11:00:23.847", "Id": "23850", "Score": "0", "body": "Well very simple tests do show that $key = $prefix ? $k : \"{$prefix}[{$k}]\"; is a lot faster then the !strlen() check. Why do you use that? Other than that it looks fast enough to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T11:02:18.347", "Id": "23851", "Score": "1", "body": "@Tessmore Because `0` is a valid key and considered false. I suppose a faster version than strlen could be `((string) $prefix) !== '')`. Or, the fastest would probably actually be to have $prefix default to null and just check `$prefix === null`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T11:03:16.010", "Id": "23852", "Score": "0", "body": "Ye I did the last one" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T10:32:41.913", "Id": "14685", "ParentId": "14671", "Score": "3" } } ]
{ "AcceptedAnswerId": "14685", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T20:58:03.310", "Id": "14671", "Score": "2", "Tags": [ "php", "array" ], "Title": "Flaten array to 1D and assigning 'associative' keynames recursively" }
14671
<p>How does this look? It has been over a year since my database concepts class and I have never worked with MySQL. I have chosen InnoDB as my engine because of foreign key support using UTF-8 based on advice from an <a href="https://codereview.stackexchange.com/questions/14619/mysql-database-design-review">earlier review</a>. Everything works as it should when deleting and updating, but I am worried I am doing something that may be considered bad practice.</p> <p>The main table <code>Tracker</code> manages different survey name and descriptions. The table <code>Card</code> holds information on each person who has been surveyed. <code>Survey</code> holds the results of each <code>Card</code> response for the survey being tracked by <code>Tracker</code> and has a unique composite key. </p> <p>If a <code>cardID</code> is deleted or updated the corresponding composite key of <code>Survey</code> will be deleted or updated. If a <code>trackID</code> is deleted or updated this will delete or update the corresponding <code>cardID</code> fields in <code>Card</code>.</p> <p><strong>ERD design image:</strong> </p> <p><img src="https://i.stack.imgur.com/ascS4.png" alt="enter image description here"></p> <p>Is this the right way to apply a composite key in this way? Are there any changes that should be made? Are there any suggestions for changes?</p> <pre><code>CREATE TABLE `Tracker` ( `trackID` int(11) NOT NULL AUTO_INCREMENT, `tName` varchar(40) DEFAULT NULL, `tDesc` varchar(200) DEFAULT NULL, PRIMARY KEY (`trackID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; CREATE TABLE `Card` ( `cardID` int(11) NOT NULL AUTO_INCREMENT, `trackID` int(11) NOT NULL, `fName` varchar(21) NOT NULL, `mName` varchar(1) DEFAULT NULL, `lName` varchar(21) DEFAULT NULL, `email` varchar(50) NOT NULL, `isMember` int(1) NOT NULL, PRIMARY KEY (`cardID`), FOREIGN KEY (`trackID`) REFERENCES `Tracker`(`trackID`) ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; CREATE TABLE `Survey` ( `cardID` int(11) NOT NULL, `trackID` int(11) NOT NULL, `q0` int(1) NOT NULL, `q1` int(1) DEFAULT NULL, `q2` int(1) DEFAULT NULL, `q3` int(1) DEFAULT NULL, `q4` int(1) DEFAULT NULL, `q5` int(1) DEFAULT NULL, PRIMARY KEY (`cardID`, `trackID`), FOREIGN KEY (`trackID`) REFERENCES `Tracker`(`trackID`) ON UPDATE CASCADE, FOREIGN KEY (`cardID`) REFERENCES `Card`(`cardID`) ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ; </code></pre>
[]
[ { "body": "<p>You should consider normalizing <code>Survey</code> further, in that having many fields with only a differing numeric suffix indicates that it should be a single field with another key.</p>\n\n<pre><code>CREATE TABLE `Survey` (\n `cardID` int(11) NOT NULL,\n `trackID` int(11) NOT NULL,\n `questionID` int(11) NOT NULL,\n `response` int(1) NOT NULL,\n PRIMARY KEY (`cardID`, `trackID`, `questionID`),\n FOREIGN KEY (`trackID`) REFERENCES `Tracker`(`trackID`) ON UPDATE CASCADE,\n FOREIGN KEY (`cardID`) REFERENCES `Card`(`cardID`) ON UPDATE CASCADE ON DELETE CASCADE,\n FOREIGN KEY (`questionID`) REFERENCES `Question`(`questionID`) ON UPDATE CASCADE ON DELETE CASCADE\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T06:45:12.690", "Id": "14679", "ParentId": "14674", "Score": "3" } }, { "body": "<p>Just a quick thing: <code>int(1)</code> probably does not mean what you think it means.</p>\n\n<pre><code>mysql&gt; create table int_length (x int(1));\nQuery OK, 0 rows affected (0.04 sec)\n\nmysql&gt; INSERT INTO int_length VALUES (1234);\nQuery OK, 1 row affected (0.05 sec)\n\nmysql&gt; SHOW WARNINGS;\nEmpty set (0.00 sec)\n\nmysql&gt; SELECT x FROM int_length;\n+------+\n| x |\n+------+\n| 1234 |\n+------+\n1 row in set (0.00 sec)\n</code></pre>\n\n<p><code>int(x)</code> is basically used for zerofill and nothing else. If you want a smaller data type, you'll need to use a small data type (<code>tinyint</code>, etc). (Note that this doesn't apply to <code>var</code> types. <code>varchar(5)</code> is <code>&lt;= 5</code> characters, and varchar(10) is <code>&lt;= 10</code> characters.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T10:43:09.063", "Id": "14686", "ParentId": "14674", "Score": "4" } }, { "body": "<p>I agree with <em>Corbin</em> and <em>Ignacio Vazquez-Abrams</em>, and here are some other notes:</p>\n\n<blockquote>\n <p>The main table <code>Tracker</code> manages different survey name and descriptions. </p>\n</blockquote>\n\n<p>Then, I'd call it <code>Survey</code> with attributes <code>surveyId</code>, <code>name</code> and <code>description</code>.</p>\n\n<blockquote>\n <p>The table <code>Card</code> holds information on each person who has been surveyed. </p>\n</blockquote>\n\n<p>Then, I'd call it <code>SurveyedPerson</code> with attributes <code>surveryPersonId</code> etc.</p>\n\n<blockquote>\n <p><code>Survey</code> holds the results of each <code>Card</code> response for the survey being tracked by <code>Tracker</code> and has a unique composite key.</p>\n</blockquote>\n\n<p>Then, <code>SurveyResult</code> (or <code>Answer</code>) holds the results of each <code>SurveyPerson</code> response for the <code>Survey</code> (being tracked by <code>Survey.surveyId</code>) and has a unique composite key.</p>\n\n<p>In your first question I did not understand the purpose of these tables (see my comment on your first question). I don't know whether your original names are special terms in the field of the survey science or anything but the names above seem easier to understand, read and therefore maintain (for me, at least). </p>\n\n<hr>\n\n<ol>\n<li><p>Are you sure that you need the <code>Card.trackId</code> attribute? It seems duplication of <code>Survey.trackId</code> (so it's redundant).</p></li>\n<li><p>Are you sure that you don't need to store multiple <code>Survey</code>s (answers) for the same <code>Card</code> (person)? What happens when the same person answers to multiple surveys? Do you duplicate their name?</p></li>\n<li><p>Attribute lengths in the <code>Card</code> table seems too short. You might have problems with <a href=\"http://news.bbc.co.uk/2/hi/uk_news/england/somerset/7707098.stm\" rel=\"nofollow noreferrer\">the new name of this guy</a>. AFAIK <a href=\"https://stackoverflow.com/questions/386294/maximum-length-of-a-valid-email-address\">email addresses also could be 254 characters long</a>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T21:31:48.863", "Id": "14720", "ParentId": "14674", "Score": "4" } } ]
{ "AcceptedAnswerId": "14720", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T22:56:25.423", "Id": "14674", "Score": "3", "Tags": [ "sql", "mysql" ], "Title": "Database of survey information" }
14674
<p>I have a class called <code>Foo</code> </p> <pre><code>public class Foo { private String optionalProperty; private String name; private long uniqueId; // getters/setters for above properties } </code></pre> <p>For some business reason I need to create an Identifier which I can use to 'identify' Foo instances (having some <code>name</code>/<code>uniqueId</code>) in some business flow. I want to create some <code>FooIdentifier</code> class which will be used to identify <code>Foo</code> instances (this <code>FooIdentifier</code> has other business use cases as well and this is one of the use cases). </p> <p>Since this <code>FooIdentifier</code> will be either based on <code>name</code> or <code>uniqueId</code> we need to distinguish between those two scenarios, <code>optionalProperty</code> is common in both the scenarios.<br> I'm considering two designs as follows -<br> Subclassing - </p> <pre><code>public abstract class FooIdentifier { private String optionalProperty; public enum Type { NAME_BASED, ID_BASED } protected FooIdentifier(String optionalProperty) { this.optionalProperty = optionalProperty; } public String getOptionalProperty() { return optionalProperty; } public abstract Type getType(); } public class NameBasedIdentifier extends FooIdentifier { private String name; public NameBasedIdentifier(String optionalProperty, String name) { super(optionalProperty); this.name = name; } public NameBasedIdentifier(String name) { this(null, name); } public String getName() { return name; } @Override public Type getType() { return Type.NAME_BASED; } } public class IdBasedIdentifier extends FooIdentifier { private long uniqueId; public IdBasedIdentifier(String optionalProperty, long uniqueId) { super(optionalProperty); this.uniqueId = uniqueId; } public IdBasedIdentifier(long uniqueId) { this(null, uniqueId); } public long getUniqueId() { return uniqueId; } @Override public Type getType() { return Type.ID_BASED; } } </code></pre> <p>Or plain old class - <br/></p> <pre><code>public class FooIdentifier { private String optionalProperty; private String name; private long uniqueId; public enum Type { NAME_BASED, ID_BASED } public FooIdentifier(String optionalProperty, String name) { this.optionalProperty = optionalProperty; this.name = name; // will have null check } public FooIdentifier(String optionalProperty, long uniqueId) { this.optionalProperty = optionalProperty; this.uniqueId = uniqueId; // will have null check } public FooIdentifier(String name) { this(null, name); } public FooIdentifier(long uniqueId) { this(null, uniqueId); } public String getOptionalProperty() { return optionalProperty; } public Type getType() { return name == null ? Type.ID_BASED : Type.NAME_BASED; } public String getName() { return name; } public long getUniqueId() { return uniqueId; } } </code></pre> <p>Which one will be better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T19:53:10.587", "Id": "25408", "Score": "0", "body": "Did you ever decide on an approach for this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T20:31:47.623", "Id": "25417", "Score": "0", "body": "yes, I went with One public class and private inner classes for all the special implementations." } ]
[ { "body": "<p>Assuming you need to retrieve the string or long values (I don't see getters for them in the single class) I prefer the three classes, with the getter methods also in the base class to avoid a cast. Each derived class would unconditionally throw an exception if the inappropriate getter method is called, whereas a single class needs an if statement in both getters. Same goes for if you added a toString() method, equals(long), equals(string) or other methods to the base class - no if statements for \"which type of class am I\" that are necessary with a single class. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:01:51.390", "Id": "23900", "Score": "1", "body": "So basically you're saying I should have three classes but subclasses should not be visible to the clients and all clients will deal with main `FooIdentifier` class.. right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T20:47:01.997", "Id": "23923", "Score": "1", "body": "Yes. Ideally there would be some way to use them without ever having to call getType(). Like a toString() method that converted the long to a string if necessary for accessing the data and an equals( FooIdentifer in) method for comparing them. But maybe getType() is unavoidable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T13:58:59.930", "Id": "14697", "ParentId": "14687", "Score": "2" } }, { "body": "<p>The <em>old class</em> is interesting : <br>\nyou can have a double identification, with <em>name</em> and <em>long</em> (<code>long</code> is never <code>null</code> but <code>0L</code>) for the same 'user', so you will be able to know it.<br>\nHowever if a same 'user' may have two entries, two identities it does not matter, and <em>three class</em> is loosely coupled, if those classes engage opposite traitements, why not.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T08:40:00.827", "Id": "17548", "ParentId": "14687", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T11:19:17.440", "Id": "14687", "Score": "3", "Tags": [ "java", "object-oriented", "classes" ], "Title": "Subclassing or not?" }
14687
<p>I was looking at this website:</p> <p><a href="http://www.devshed.com/c/a/MySQL/Creating-User-Models-in-PHP-and-MySQL/1/" rel="nofollow">http://www.devshed.com/c/a/MySQL/Creating-User-Models-in-PHP-and-MySQL/1/</a> and <a href="http://www.devshed.com/c/a/MySQL/Creating-User-Models-in-PHP-and-MySQL/2/" rel="nofollow">http://www.devshed.com/c/a/MySQL/Creating-User-Models-in-PHP-and-MySQL/2/</a></p> <p>In the first one they have methods such as:</p> <pre><code>/** * Perform a SELECT statement */ public function select($table, $where = '', $fields = '*', $order = '', $limit = null, $offset = null) { $query = 'SELECT ' . $fields . ' FROM ' . $table . (($where) ? ' WHERE ' . $where : '') . (($limit) ? ' LIMIT ' . $limit : '') . (($offset &amp;&amp; $limit) ? ' OFFSET ' . $offset : '') . (($order) ? ' ORDER BY ' . $order : ''); $this-&gt;query($query); return $this-&gt;countRows(); } /** * Perform an INSERT statement */ public function insert($table, array $data) { $fields = implode(',', array_keys($data)); $values = implode(',', array_map(array($this, 'quoteValue'), array_values($data))); $query = 'INSERT INTO ' . $table . '(' . $fields . ')' . ' VALUES (' . $values . ')'; $this-&gt;query($query); return $this-&gt;getInsertId(); } </code></pre> <p>then in the second page:</p> <pre><code>/** * Fetch all users */ public function fetchAll() { // try to fetch users data from the cache system if ($users = $this-&gt;_cache-&gt;get('all')) { return $users; } // otherwise fecth users data from the database $this-&gt;_adapter-&gt;select('users'); $users = array(); while ($user = $this-&gt;_adapter-&gt;fetch()) { $users[] = $user; } if (count($users) !== 0) { $this-&gt;_cache-&gt;set('all', $users); } return $users; } /** * Insert new user data (the cache is cleared also) */ public function insert(array $data) { if ($insertId = $this-&gt;_adapter-&gt;insert('users', $data)) { $this-&gt;_cache-&gt;clear(); return $insertId; } return false; } /** * Delete the table row corresponding to the specified user (the cache is cleared also) */ public function delete($id) { if ($affectedRow = $this-&gt;_adapter-&gt;delete('users', "id = $id")) { $this-&gt;_cache-&gt;clear(); return $affectedRow; } return false; } </code></pre> <p>Is this a bad way of doing things? Is this opening me up to sql injection just like anything else where I construct the sql on the fly would? I want to build my models "right." Does that mean I need to have all stored procedures or prepared statements?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T20:23:23.847", "Id": "23855", "Score": "0", "body": "possible duplicate of [Best way to prevent SQL Injection in PHP](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T20:24:31.933", "Id": "23856", "Score": "0", "body": "That's not a duplicate. I'll edit the title of this one to clarify." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T20:25:29.757", "Id": "23857", "Score": "0", "body": "I can't see where your parameters are coming from, but *theoretically* as long as you are escaping them properly you should be ok." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T20:26:24.267", "Id": "23858", "Score": "4", "body": "Don't do it this way, better to use [PDO](http://www.php.net/pdo) and parameterise your queries. There is a good tutorial here http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers. Also take a look at the information in the link in my previous comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T20:27:32.130", "Id": "23859", "Score": "0", "body": "@RobertHarvey You may be right, but there's still some good information there for the OP. In fact, I think the accepted answer there could answer this question. Don't you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T20:33:29.533", "Id": "23860", "Score": "0", "body": "Also take a look at this answer here http://stackoverflow.com/a/5887401/212940" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T20:46:50.480", "Id": "23861", "Score": "0", "body": "Get yourself some redbean, then use prepared statements. http://redbeanphp.com/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T21:30:42.877", "Id": "23926", "Score": "0", "body": "I don't know why SO keeps sending these kinds of things over this way. This isn't a code review, this is a legitimate question about implementation. Also, I'm not sure where the authors of those articles over at DevShed stand on the matter, but blatantly copying their work is considered copyright infringement. I think the policy on including code from linked websites only extends to your own code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T13:50:15.037", "Id": "23969", "Score": "0", "body": "@showerhead I don't know about devshed, but I know that when I posted just a link on SO, I was thrashed and given a -6. I was told by one commenter they \"frankly did not care\" but if I wanted an answer to post code. So, here I did and gave a link." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T16:42:54.790", "Id": "23982", "Score": "0", "body": "@johnny: Sadly a lot of people don't understand that you don't always HAVE the code yourself and what you are asking about is a \"theory\". I understand the frustration. Just beware of copyright. Usually authors don't mind you sampling their work as long as you aren't claiming it as your own and cite them. Not sure why my comment from yesterday seemed to be implying that you weren't doing this, guess it was just a long day, sorry if you took that the wrong way." } ]
[ { "body": "<p><a href=\"http://martinfowler.com/eaaCatalog/activeRecord.html\" rel=\"nofollow noreferrer\">Active record</a> instances are not \"models\". They are anti-patterns which RoR likes call that way. And what you are implementing there is an active record.</p>\n\n<p>And no, those queries are not safe. They are wide open for SQL injection, because, instead of using proper SQL <a href=\"http://en.wikipedia.org/wiki/Prepared_statement\" rel=\"nofollow noreferrer\">prepared statements</a>, you opted for concatenation.</p>\n\n<p>As for build building model, you have to understand that <strong>model is a layer</strong>. One of two in MVC. The other being - presentation layer (made of controllers, views and templates). You might read <a href=\"https://stackoverflow.com/a/5864000/727208\">this answer</a>, but I am no sure how much of it you will be able to assimilate. </p>\n\n<p>I think your first priority should be to read the <a href=\"http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers\" rel=\"nofollow noreferrer\">hashphp PDO tutorial</a> and then watching the list if lecture that you can find a the bottom of <a href=\"https://stackoverflow.com/a/9855170/727208\">this post</a>. And only then try another stab at the whole \"mvc thing\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T01:59:33.677", "Id": "14689", "ParentId": "14688", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-14T20:21:26.323", "Id": "14688", "Score": "1", "Tags": [ "php", "mvc" ], "Title": "Are these MySQL Abstraction Classes safe from SQL Injection? Can they be made safe?" }
14688
<p>This might be a dumb question for you advanced developers.</p> <p>Below is a script on my own website that I want to modify, in order to <strong>avoid declaring same variables in each function</strong>. I want to avoid declaring variables in the main script structure.</p> <p>Below code works, still wanted to know if there is a more elegant way to do this. </p> <p>As Answered below, it's best to enclose everything in an object.</p> <pre><code>var var1 = document.getElementById("div1"); var var2 = document.getElementById("div2"); function foo1(){ div1.style.display = "none"; } function foo2(){ div2.style.display = "block"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T14:44:37.907", "Id": "23862", "Score": "4", "body": "why have you doubled `function function`?? Also where is this error? http://jsfiddle.net/rlemon/fxhK7/ I do not see it?? Unless you want to pass around the object, in what you have shown me this does use global variables. in JS you do not need to cast them as such." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T14:45:16.837", "Id": "23863", "Score": "0", "body": "`function function`? typo?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T14:47:18.940", "Id": "23864", "Score": "2", "body": "If it's not the `function function`. You're probably executing the function before you initialize the variables... I think this should work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T14:47:46.517", "Id": "23865", "Score": "0", "body": "@PitaJ, yes sorry typo" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T14:51:52.467", "Id": "23866", "Score": "0", "body": "@Xander I make a rollback from PitaJ removal of `function function` then a rollback again, to PitaJ's removel, when op said it was a typo and I then thought it's was not the meaning of the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:16:04.707", "Id": "23867", "Score": "0", "body": "@jacktrades http://jsfiddle.net/rlemon/EHZqM/ still don't see it boss." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:46:17.493", "Id": "23868", "Score": "0", "body": "@StephenSarcsamKamenar, you were right" } ]
[ { "body": "<pre><code>var var1 = \"hello\";\nvar var2 = \"hello2\";\n\nfunction foo1(){\n var1 += \"world\";\n var2 += \"world2\";\n}\nfunction foo2(){\n var1 += \"2world\";\n var2 += \"2world2\";\n}\n</code></pre>\n\n<p>try that. you had double function keyword , and you forgot braces to close</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T14:49:00.107", "Id": "23869", "Score": "0", "body": "Yup, this works for me: http://jsfiddle.net/Laxc7/" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T14:47:18.693", "Id": "14691", "ParentId": "14690", "Score": "1" } }, { "body": "<p>You can enclose your variables (and functions) in a closure to restrict your scope, although you then need someway to make those functions callable outside of that closure, e.g.:</p>\n\n<pre><code>(function() {\n var a;\n\n function increment() {\n a += 1;\n }\n\n function decrement() {\n a -= 1;\n }\n\n window.increment = increment;\n window.decrement = decrement;\n})();\n</code></pre>\n\n<p>It's pretty ugly, though. It would be better to enclose the whole thing as an object, e.g.:</p>\n\n<pre><code>function Counter() {\n var count = 0;\n\n return {\n increment: function() {\n return count++;\n },\n decrement: function() {\n return count--;\n },\n value: function() {\n return count;\n }\n };\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T14:51:40.980", "Id": "23870", "Score": "0", "body": "Correct, I tried that, wasn't aware of `window` You need that to make it callable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T14:52:38.250", "Id": "23871", "Score": "0", "body": "@jacktrades yes, that gives those inner functions global references that can be called. I might add a better example, though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T14:49:58.310", "Id": "14692", "ParentId": "14690", "Score": "4" } }, { "body": "<p>In order to avoid writing those as global variables, put them into a global variable. :)</p>\n\n<p>Before you downvote, let me explain.</p>\n\n<p>Javascript really doesn't have the concept of namespaces, but most big Javascript libraries need to have functions and data accessible to all the Javascript running on a page. They do this by creating <strong>one</strong> Javascript object and then putting everything in it. jQuery does it with a <code>jQuery</code> object, Google with their <code>google.maps</code> object and you can too.</p>\n\n<p>For your code, create a <code>myApp</code> object (should be a unique name for your application) like so:</p>\n\n<pre><code>myApp = myApp || {}; // No var keyword here, so it's global\nmyApp.var1 = \"hello\";\nmyApp.var2 = \"hello2\";\n\nfunction foo1(){\n var var1 = myApp.var1 + \"world foo1\";\n var var2 = myApp.var2 + \"world2 foo1\";\n}\n\nfunction foo2(){\n var var1 = myApp.var1 + \"world foo2\";\n var var2 = myApp.var2 + \"world2 foo2\";\n}\n</code></pre>\n\n<p>An important thing to remember is to be very careful what code in your application writes to the myApp object. It is still a global and access controls need to be enforced by good design because the code isn't going to do it for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:05:28.403", "Id": "23872", "Score": "0", "body": "upvoted, helped me. Can you explain me more on the declaration syntax? `myApp || {};`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:16:34.970", "Id": "23873", "Score": "0", "body": "ugh... global scope pollution here. ***NEVER!*** I repeat, ***NEVER*** do this!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:39:37.030", "Id": "23874", "Score": "1", "body": "@jacktrades - `myApp = myApp || {};` is a way to make sure you won't completely overwrite your global namespace by trying to declare it again. So basically `myApp` equals the existing `myApp` if it exists. If it doesn't, it equals an empty object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:46:16.623", "Id": "23875", "Score": "0", "body": "@rlemon - Is there a better way? All the major players do it and I always have one object that handles data in my application just like them for objects that need to be accessed by everything in my app, like my main map object, markers I may or may not be showing on the map at the moment, etc. There's no central lookup repository in Javascript, no central database (well, I guess there is for some browsers, is this what you recommend?), where else would you store runtime data and functions for your application?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T14:59:30.717", "Id": "14693", "ParentId": "14690", "Score": "1" } } ]
{ "AcceptedAnswerId": "14692", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T14:42:39.827", "Id": "14690", "Score": "1", "Tags": [ "javascript" ], "Title": "Better writing JS - from general variables to object" }
14690
<p>I have built a JavaScript PNG sequence engine that allows for playing, pausing and stopping and a time change event. I am asking for genuine opinions if the code is actually good. Its ONLY for the iDevice range (not for desktop browsers or anything) and here is the code and a link to the gist if you wanted to edit it for examples.</p> <p>Hope its as good as I think it is!</p> <pre><code>/** * @param slides ~ Array (ARRAY) of image locations * @param duration ~ Number - in milliseconds how long to run for * @param element ~ jQuery object - The &lt;img&gt; tag to change the src of. * @returns void * * @example * &lt;img src="#" id="sequence" data-loop="true" data-autoplay="true" /&gt; * &lt;script&gt;var vid = new PNGSequence(tiffanyCrystal, 4, $('#sequence'));&lt;/script&gt; */ var PNGSequence = function (slides, duration, element) { this.slides = slides; this.NSlides = slides.length; this.duration = duration; this.interval = (this.duration * 1000) / this.NSlides; this.element = element; this.index = 0; this.loop = this.element.data('loop') == true; this.autoplay = this.element.data('autoplay') == true; var inter; this.interGo = function () { var self = this; return setTimeout(function () { // Update the image element.attr({ "src": slides[self.index] }); // Increase the index self.index++; // Call the onTimeChange event if (self.hasOwnProperty('onTimeChange')) { if (self.onTimeChange) { self.onTimeChange.call(self, self.index, self.NSlides); } } // Check if its the end of the animation if (self.index &gt; self.NSlides) { // If we're not looping, clear the interval if (!self.loop) { clearTimout(inter); } else { // If we're looping then start the loop from the beginning self.index = 0; self.play(); } return; } //Fire the timeout again self.interGo(); }, this.interval); }; /** * Pauses the sequence */ this.pause = function () { clearTimout(inter); return this.index; }; /** * Plays the sequence from last known point */ this.play = function () { return inter = this.interGo(); }; /** * Stops the sequence and sets the pointer * at the beginning again */ this.stop = function () { clearTimout(inter); this.index = 0; return 0; }; this.onTimeChange = function () { return this; }; if (this.autoplay) { inter = this.interGo(); } return this; }; </code></pre> <p>And here is the link to the gist <a href="https://gist.github.com/3360011" rel="nofollow">https://gist.github.com/3360011</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T15:21:34.367", "Id": "23884", "Score": "1", "body": "As per the FAQ, you should include the code in the question. If the gist is changed or deleted the answers no longer match the question they were answering..." } ]
[ { "body": "<p>I would suggest a few minor changes:</p>\n\n<ol>\n<li><p>Use <code>setTimeout</code> instead of <code>setInterval</code> to ensure that callbacks don't stack up if they can't be serviced on time. This implies re-invoking <code>this.interGo</code> at the end of the callback to re-trigger the timer.</p></li>\n<li><p>Only declare and use <code>self</code> in the functions that need it, to avoid traversing the scope chain unnecessarily.</p></li>\n<li><p>Remove over-reliance on the <code>Number</code> constructor.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T14:04:25.647", "Id": "23877", "Score": "0", "body": "Thanks man! Only took 30 minutes to build, hadn't noticed I was using self. instead of this. in the functions IN scope lol. I've updated the gist :) https://gist.github.com/3360011" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T14:10:24.267", "Id": "23878", "Score": "1", "body": "In your new code I'd move the `var self = this` just inside the `interGo` function. It'll stop the interpreter from trying to build the closure around the whole function instead of just the inner function. Also, move your end-of-loop test to the end of the function, where you can merge together the question of resetting the index or firing again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T14:42:42.837", "Id": "23880", "Score": "0", "body": "I've updated the gist again, I didn't quite understand what you meant by \"merge together the question of resetting the index or firing again\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T14:48:30.287", "Id": "23883", "Score": "0", "body": "I mean that the last block just needs to say `if (self.looping && self.index > self.NSlides) { index = 0; }` and then just call `self.interGo`. There's no need for a `clearTimeout`. See http://jsfiddle.net/alnitak/mVF75/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T16:19:08.417", "Id": "23892", "Score": "0", "body": "oops, that's not quite right." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T13:54:18.697", "Id": "14696", "ParentId": "14694", "Score": "2" } }, { "body": "<p>Do you expect this to be called multiple times per page? If so, I would consider attaching your functions to the prototype, that way they're not instantiated every time a your object is new'd up.</p>\n\n<p>If this is primarily for use with jQuery, why not bundle it into a plugin? You can still keep your object as it is, just follow the kind of pattern used by twitter in the bootstrap plugins. Off the top of my head, something like this perhaps?</p>\n\n<pre><code>$.fn.pngSequence = function(options) {\n return this.each(function() {\n var $this = $(this),\n sequence = new PNGSequence(options.slides, options.duration, $this);\n\n //i like storuing the instance in the data collection\n //so consumer can interact with it later\n $this.data(\"pngSequence\", sequence);\n\n });\n};\n</code></pre>\n\n<p>Which could then be utilised as so. Note that it's hooked in declaratively using a data-* attribute :)</p>\n\n<pre><code>$(\"img[data-provider='pngSequence']\").pngSequence({\n slides : tiffanyCrystal,\n duration : 4\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T13:17:44.950", "Id": "25363", "Score": "0", "body": "Actually it turned out, no amount of optimisation ran smoothly on all the iPads, they all seemed to fall over or lag depending on different optimisations so this was ditched. Be ok for web use though, I like your idea of using it in a jQuery plugin and storing it in data." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T09:38:14.660", "Id": "15607", "ParentId": "14694", "Score": "1" } } ]
{ "AcceptedAnswerId": "14696", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T13:36:37.527", "Id": "14694", "Score": "0", "Tags": [ "javascript" ], "Title": "The efficiency and options of my PNG sequence JS class" }
14694
<p>I wrote this <code>downloadContent()</code> function.</p> <p>Is there some other way to download the content faster?</p> <pre><code>private string downloadContent() { try { WebRequest request = WebRequest.Create(testingUrl); request.Proxy = null; request.Method = "GET"; response = request.GetResponse(); Stream stream = response.GetResponseStream(); reader = new StreamReader(stream); string content = reader.ReadToEnd(); return content; } catch { return error; } } </code></pre> <p>Here the two functions I'm using to extract the text from in between tags after downloading:</p> <pre><code>private void GetProfileNames(string text) { names = new List&lt;string&gt;(); string startTag = "&lt;span class=\"message-profile-name\" &gt;&lt;a href='/profile/"; string endTag = "'&gt;"; int startTagWidth = startTag.Length; int endTagWidth = endTag.Length; index = 0; while (true) { index = text.IndexOf(startTag, index); if (index == -1) { break; } // else more to do - index now is positioned at first character of startTag int start = index + startTagWidth; index = text.IndexOf(endTag, start + 1); if (index == -1) { break; } // found the endTag profileName = text.Substring(start, index - start); names.Add(profileName); } } </code></pre> <p>And this is the <code>DoWork()</code> event which is not good the way I did it, but I just don't know how to make it better:</p> <pre><code>private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { string templastItem; BackgroundWorker worker = sender as BackgroundWorker; List&lt;string&gt; tempNamesAndTexts = new List&lt;string&gt;(); string tempDownload = downloadContent(); if (tempDownload == error) { if (InvokeRequired) { BeginInvoke(new Action(() =&gt; textBox1.AppendText(DateTime.Now + "===&gt; " + "Error The Web Site Is Not Responding Wait, Trying To Reconnect" + Environment.NewLine))); Logger.Write("Error The Web Site Was Not Responding"); } } else { GetProfileNames(tempDownload); GetTextFromProfile(tempDownload); for (int i = 0; i &lt; names.Count; i++) { tempNamesAndTexts.Add(names[i] + " " + texts[i]); } templastItem = tempNamesAndTexts.Last(); if (InvokeRequired) { BeginInvoke(new Action(() =&gt; tempNamesAndTexts.ForEach(Item =&gt; textBox1.AppendText(DateTime.Now + "===&gt; " + Item + Environment.NewLine)))); string[] array = File.ReadAllLines(full_path_log_file_name); if (array.Length == 2) { foreach (string item in tempNamesAndTexts) { Logger.Write(item); } } else { if (!array.Contains(templastItem)) { Logger.Write(templastItem); } } } } while (true) { testingDownload = downloadContent(); if (testingDownload == error) { if (InvokeRequired) { BeginInvoke(new Action(() =&gt; textBox1.AppendText(DateTime.Now + "===&gt; " + "Error The Web Site Is Not Responding Wait, Trying To Reconnect" + Environment.NewLine))); Logger.Write("Error The Web Site Was Not Responding"); } Thread.Sleep(1000); } else { Logger.exist(); namesAndTexts = new List&lt;string&gt;(); if ((worker.CancellationPending == true)) { e.Cancel = true; break; } else { string content = downloadContent(); if (content == error) { if (InvokeRequired) { BeginInvoke(new Action(() =&gt; textBox1.AppendText(DateTime.Now + "===&gt; " + "Error The Web Site Is Not Responding Wait, Trying To Reconnect" + Environment.NewLine))); Logger.Write("Error The Web Site Was Not Responding"); } Thread.Sleep(1000); } else { GetProfileNames(content); GetTextFromProfile(content); for (int i = 0; i &lt; names.Count; i++) { namesAndTexts.Add(names[i] + " " + texts[i]); } if (InvokeRequired) { result = tempNamesAndTexts.SequenceEqual(namesAndTexts); if (result == true) { } else { var t = namesAndTexts.Last(); if (textBox1.InvokeRequired) { BeginInvoke(new Action(() =&gt; textBox1.AppendText(DateTime.Now + "===&gt; " + t + Environment.NewLine)), null); Logger.Write(t); if (result == false) { tempNamesAndTexts = new List&lt;string&gt;(); for (int i = 0; i &lt; names.Count; i++) { tempNamesAndTexts.Add(names[i] + " " + texts[i]); } } } } } reader.Close(); response.Close(); Thread.Sleep(1000); } } } } } private void GetTextFromProfile(string text) { texts = new List&lt;string&gt;(); string str = "&lt;span class=\"message-text\"&gt;"; string startTag = str; string endTag = "&lt;/span&gt;"; int startTagWidth = startTag.Length; int endTagWidth = endTag.Length; index = 0; while (true) { index = text.IndexOf(startTag, index); if (index == -1) { break; } // else more to do - index now is positioned at first character of startTag int start = index + startTagWidth; index = text.IndexOf(endTag, start + 1); if (index == -1) { break; } // found the endTag profileNameText = text.Substring(start, index - start); Conditions(); } } </code></pre> <p><a href="https://skydrive.live.com/redir?resid=3B8A7D9F66FF985B!171&amp;authkey=!AFO6EmoF38MtkKQ" rel="nofollow">This</a> is the link to view/download the project, which is not big.</p>
[]
[ { "body": "<p>I don't know about faster, but please make sure you wrap your disposable resources (classes which implement <code>IDisposable</code>) in <code>using</code> statements to properly and deterministically manage resources:</p>\n\n<pre><code> private string downloadContent() \n {\n try\n {\n WebRequest request = WebRequest.Create(testingUrl);\n request.Proxy = null;\n request.Method = \"GET\";\n using (var response = request.GetResponse())\n using (var stream = response.GetResponseStream())\n using (var reader = new StreamReader(stream))\n {\n return reader.ReadToEnd();\n }\n }\n catch\n {\n return error;\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T15:29:53.347", "Id": "14700", "ParentId": "14695", "Score": "4" } }, { "body": "<p>First off, I like the use of white space and the layout.</p>\n\n<p>On top of what Jesse said here's my $0.02</p>\n\n<p>I think you're using too many class variables in this code. You also have way too many nested ifs. I have noted below where you should be removing the nesting and why it is not needed.</p>\n\n<p>Start in the <em>GetProfileNames</em> method. The while the loop works, but it is very messy, and the while(true) statement really confuses the code. I would try something like this, it is cleaner, and probably more efficient</p>\n\n<pre><code>private IEnumerable&lt;string&gt; GetProfileNames(string text)\n{\n const string startTag = \"&lt;span class=\\\"message-profile-name\\\" &gt;&lt;a href='/profile/\";\n const string endTag = \"'&gt;\";\n\n var names = text.Split(new[] {startTag, endTag}, StringSplitOptions.RemoveEmptyEntries);\n\n return names;\n}\n</code></pre>\n\n<p>Modify your <em>Conditions</em> method to be something a little more descriptive. You should change the signature too so you can pass in the string you're processing. This will clarify what call is supposed to be doing.</p>\n\n<pre><code>private void ProcessProfileNameTexts(string profileNameText)\n{\n ...\n}\n</code></pre>\n\n<p>You can then apply the same logic as you did in <em>GetProfileNames</em> to <em>GetTextFromProfile</em></p>\n\n<pre><code>private IEnumerable&lt;string&gt; GetTextFromProfile(string text)\n{\n\n const string startTag = \"&lt;span class=\\\"message-text\\\"&gt;\";\n const string endTag = \"&lt;/span&gt;\";\n\n var texts = text.Split(new[] { startTag, endTag }, StringSplitOptions.RemoveEmptyEntries).ToList();\n\n texts.ForEach(ProcessProfileNameTexts);\n\n return texts;\n}\n</code></pre>\n\n<p>Your DoWork method is a mess. I would start by adding a return to the if of the error check and removing the else. I would also stop using the '+' to concatenate strings, this is a very inefficient way of doing it. My suggestion would be to use string.Format()</p>\n\n<p>First off, add a few helper methods</p>\n\n<pre><code>private static void Invoke(string message)\n{\n BeginInvoke(new Action(() =&gt; textBox1.AppendText(string.Format(@\"{0} ===&gt; {1}\", DateTime.Now, message))));\n}\n\nprivate static void Log(string message)\n{\n Logger.Write(message);\n}\n\nprivate static void InvokeAndLogIfRequired(string message, string loggerMessage)\n{\n if (!InvokeRequired)\n {\n return;\n }\n\n Invoke(message);\n Log(loggerMessage);\n}\n</code></pre>\n\n<p>Then change your error check to</p>\n\n<pre><code>if (tempDownload == error)\n{\n\n InvokeAndLogIfRequired(\n string.Format(@\"Error The Web Site Is Not Responding Wait, Trying To Reconnect{0}\", Environment.NewLine), \n \"Error The Web Site Was Not Responding\");\n\n\n return;\n}\n</code></pre>\n\n<p>Your method lists can then be assigned:</p>\n\n<pre><code>names = GetProfileNames(tempDownload);\ntexts = GetTextFromProfile(tempDownload);\n\nvar tempNamesAndTexts = new List&lt;string&gt;();\nfor (var i = 0; i &lt; names.Count; i++)\n{\n tempNamesAndTexts .Add(string.Format(@\"{0} {1}\", names[i], texts[i]));\n}\n</code></pre>\n\n<p>The variable templastItem should be declared as it is assigned</p>\n\n<pre><code>var templastItem = tempNamesAndTexts.Last();\n</code></pre>\n\n<p>This next section is not as clean as I'd like, but it is a little cleaner that the original code.</p>\n\n<pre><code>if (InvokeRequired)\n{\n tempNamesAndTexts.ForEach(Invoke);\n\n var array = File.ReadAllLines(full_path_log_file_name);\n if (array.Length == 2)\n {\n tempNamesAndTexts .ForEach(Log);\n }\n else\n {\n if (!array.Contains(templastItem))\n {\n Log(templastItem);\n }\n }\n}\n</code></pre>\n\n<p>I'm not going to take out the next while loop because I don't think I have that much brain power right now, but lets clean it up:</p>\n\n<p>Make the error reporting a little cleaner but using helper methods and adding a <em>continue</em> instead of the else statement</p>\n\n<pre><code>testingDownload = downloadContent();\nif (testingDownload == error)\n{\n InvokeAndLogIfRequired(\"Error The Web Site Is Not Responding Wait, Trying To Reconnect\", \"Error The Web Site Was Not Responding\");\n\n Thread.Sleep(1000);\n\n continue;\n}\n</code></pre>\n\n<p>Remove the else from the cancel pending code too. The <em>break</em> takes care of the else. </p>\n\n<pre><code>Logger.exist();\nvar namesAndTexts = new List&lt;string&gt;();\nif ((worker.CancellationPending == true))\n{\n e.Cancel = true;\n break;\n}\n</code></pre>\n\n<p>Clean up the next error checking:</p>\n\n<pre><code>string content = downloadContent();\nif (content == error)\n{\n InvokeAndLogIfRequired(\n string.Format(@\"Error The Web Site Is Not Responding Wait, Trying To Reconnect{0}\", Environment.NewLine),\n \"Error The Web Site Was Not Responding\");\n\n Thread.Sleep(1000);\n\n continue;\n}\n</code></pre>\n\n<p>Now comes to the last Invoke, going to start after the if statement:</p>\n\n<p>The if here is useless. Check for false and continue through the false path.</p>\n\n<pre><code>result = tempNamesAndTexts.SequenceEqual(namesAndTexts);\nif (result == true)\n{\n}\n</code></pre>\n\n<p>Like this:</p>\n\n<pre><code>result = tempNamesAndTexts.SequenceEqual(namesAndTexts);\nif (result == false)\n{\n ...\n}\n</code></pre>\n\n<p>This next section is very confusing, within the </p>\n\n<pre><code>if (InvokeRequired) \n</code></pre>\n\n<p>you have </p>\n\n<pre><code>if (textBox1.InvokeRequired)\n</code></pre>\n\n<p>I'm assuming this is the same thing. If it is, the second one will <strong>ALWAYS</strong> be true.</p>\n\n<p>you also have a</p>\n\n<pre><code>if (result == false)\n</code></pre>\n\n<p>inside a</p>\n\n<pre><code>if (result == false)\n</code></pre>\n\n<p>again, the second one will <strong>ALWAYS</strong> be false, remove it.</p>\n\n<p>These suggestions just scratch the surface, there is much more I could do to this, but this is a good start.</p>\n\n<p>Here is the entire DoWork method as I've refactored it, I haven't tested it, but it should work.</p>\n\n<pre><code>private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)\n{\n var worker = sender as BackgroundWorker;\n\n string tempDownload = downloadContent();\n if (tempDownload == error)\n {\n InvokeIfRequires(\n string.Format(@\"Error The Web Site Is Not Responding Wait, Trying To Reconnect{0}\",\n Environment.NewLine),\n \"Error The Web Site Was Not Responding\");\n\n\n return;\n }\n\n names = GetProfileNames(tempDownload);\n texts = GetTextFromProfile(tempDownload);\n var tempNamesAndTexts = new List&lt;string&gt;();\n for (var i = 0; i &lt; names.Count; i++)\n {\n tempNamesAndTexts.Add(string.Format(@\"{0} {1}\", names[i], texts[i]));\n }\n\n var templastItem = tempNamesAndTexts.Last();\n\n if (InvokeRequired)\n {\n tempNamesAndTexts.ForEach(Invoke);\n\n var array = File.ReadAllLines(full_path_log_file_name);\n if (array.Length == 2)\n {\n tempNamesAndTexts.ForEach(Log);\n }\n else\n {\n if (!array.Contains(templastItem))\n {\n Log(templastItem);\n }\n }\n }\n\n while (true)\n {\n testingDownload = downloadContent();\n if (testingDownload == error)\n {\n InvokeAndLogIfRequired(\"Error The Web Site Is Not Responding Wait, Trying To Reconnect\",\n \"Error The Web Site Was Not Responding\");\n\n Thread.Sleep(1000);\n\n // Maybe put a count in here so you don't end up in an infinite loop of the web server is down\n continue;\n }\n\n Logger.exist();\n\n if ((worker.CancellationPending == true))\n {\n e.Cancel = true;\n break;\n }\n\n string content = downloadContent();\n if (content == error)\n {\n InvokeAndLogIfRequired(\n string.Format(@\"Error The Web Site Is Not Responding Wait, Trying To Reconnect{0}\",\n Environment.NewLine),\n \"Error The Web Site Was Not Responding\");\n\n Thread.Sleep(1000);\n\n // Maybe put a count in here so you don't end up in an infinite loop of the web server is down\n\n\n continue;\n }\n\n\n var namesAndTexts = new List&lt;string&gt;();\n names = GetProfileNames(content);\n texts = GetTextFromProfile(content);\n for (var i = 0; i &lt; names.Count; i++)\n {\n namesAndTexts.Add(string.Format(@\"{0} {1}\", names[i], texts[i]));\n\n }\n\n if (InvokeRequired)\n {\n result = tempNamesAndTexts.SequenceEqual(namesAndTexts);\n if (result == false)\n {\n var lastText = namesAndTexts.Last();\n Invoke(lastText);\n Log(lastText);\n }\n }\n\n tempNamesAndTexts = new List&lt;string&gt;();\n for (var i = 0; i &lt; names.Count; i++)\n {\n\n tempNamesAndTexts.Add(string.Format(@\"{0} {1}\", names[i], texts[i]));\n }\n\n reader.Close();\n response.Close();\n Thread.Sleep(1000);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T23:58:15.910", "Id": "23942", "Score": "0", "body": "very nice review Jeff, just two points I'd like to make: check out the first edit of the question, and you'll see I fixed the whitespace ;) and using `ProcessProfileNameTexts` like you suggest can't work because you're only replacing the parameter, right? parameters in C# are passed by value, so you're *not modifying the original reference*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T00:13:36.380", "Id": "23944", "Score": "0", "body": "forget the second one, I hadn't read the whole thing. However, the static helper methods need to be instance methods because they access `Invoke`, which is an instance method of `Form`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T01:30:45.967", "Id": "23947", "Score": "0", "body": "Thanks. It's hard to track some of those things without having the whole file. I would of picked that stuff up if I had it in front of me...and moving those around could be phase 2, as well as cleaning the multiple calls too downloadContent(). I think you need to clean the rest of it before tackling that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T02:00:27.777", "Id": "23949", "Score": "0", "body": "Jeff Vanzella this is the link to my complete project with all files. https://skydrive.live.com/redir?resid=3B8A7D9F66FF985B!171&authkey=!AFO6EmoF38MtkKQ" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T04:32:51.853", "Id": "23951", "Score": "0", "body": "I saw it, just didn't really have time to study it today. I'll look at it a little closer tomorrow :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T22:14:33.177", "Id": "14724", "ParentId": "14695", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T13:49:25.337", "Id": "14695", "Score": "2", "Tags": [ "c#" ], "Title": "Downloading content in the background" }
14695
<p>I am trying to use a map as a way to implement an object factory. In Python it is possible to store a class type in a map, and use it later to create objects from that type:</p> <pre><code>class Foo: # ... class Bar: # ... factory_map = { 'foo' : Foo, 'bar' : Bar } foo_object = factory_map['foo']() </code></pre> <p>I am not aware of a similar feature (i.e., storing a type in a map) in C++, so I came up with a solution based on lambda functions where the map stores functions responsible to create the objects:</p> <pre><code>class Base { public: typedef std::unique_ptr&lt;Base&gt; Pointer; virtual void hi() = 0; }; class Foo : public Base { public: void hi() { std::cout &lt;&lt; "Hi, it's foo\n"; } }; class Bar : public Base { public: void hi() { std::cout &lt;&lt; "Hi, it's bar\n"; } }; int main() { std::map&lt; std::string, std::function&lt;Base::Pointer()&gt;&gt; factory_map = { { "foo", []() { return Base::Pointer(new Foo()); } }, { "bar", []() { return Base::Pointer(new Bar()); } }, }; Base::Pointer b1 = factory_map["foo"](); b1-&gt;hi(); Base::Pointer b2 = factory_map["bar"](); b2-&gt;hi(); } </code></pre> <p>This might be the most straightforward solution to obtain Python's simplicity. I am wondering, however, if the usage of lambdas is the best way to create the factory. Specifically, I would like to know what are the pros/cons of this approach compared to a more "traditional" factory design (i.e., one using <code>if</code>/<code>else</code> conditionals to decide the type of the object to create).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T17:26:49.780", "Id": "23899", "Score": "0", "body": "I would not say if/else is more traditional. I would say that using a map was more traditional (were do you think python got that pattern from)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:26:43.713", "Id": "23906", "Score": "0", "body": "@LokiAstari Well, in many places I have seen factories implemented with conditionals. One example could be the [C++ example in Wikipedia](http://en.wikipedia.org/wiki/Abstract_factory_pattern#C.2B.2B)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T19:50:14.533", "Id": "23916", "Score": "1", "body": "Sure you can do it with conditionals just like you can in Python. Its an easy way to explain the concept this way. But in the real world you would use a map as you can add factory functions dynamically. Also I don't think wikipedia is not a great source for good examples. It is a good point to start research on a subject but follow the links to more authoritative pages (like SO)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T17:10:44.927", "Id": "24052", "Score": "1", "body": "Maybe try something like this [self-registering factory](http://stackoverflow.com/a/10677156/596781)." } ]
[ { "body": "<p>The common argument for preferring one over the other for a dictionary (map) look up and a conditional (switch) look up is performance over maintainability.</p>\n\n<p>The dictionary look up usually makes it easier to separate concerns. It also makes the code more concise and arguably more readable when invoking the factory functions.</p>\n\n<p>The conditional look up avoids traversing a map and any types of indirection allowing for arguably faster access to object creation. It also avoids the overhead of creating the map/registering functions in the map.</p>\n\n<p>There are also arguments for locality of reference vs. dependency management where the switch statement may keep object creation local to the call site, while the map approach passes off creation to a function or object that knows how to better handle the problem.</p>\n\n<p>These are the typical arguments that I see for each of those different approaches to this problem.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-16T17:14:05.227", "Id": "37520", "ParentId": "14698", "Score": "2" } }, { "body": "<p>It sounds like you're trying to achieve a sort of <a href=\"https://en.wikibooks.org/wiki/C%2B%2B_Programming/RTTI\" rel=\"nofollow\">RTTI</a> context? What are you trying to accomplish with the type checking you're doing?</p>\n\n<p>C++ is a strongly typed language and usually 'type checked' code can be rewritten into a templated interface or class hierarchy with inheritance. Sometimes there is code where type checking is unavoidable though.</p>\n\n<p>(software engineering note: C++ is not Python and should be treated as such).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T01:05:22.490", "Id": "37557", "ParentId": "14698", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T14:08:39.837", "Id": "14698", "Score": "2", "Tags": [ "c++", "c++11" ], "Title": "Creating a class object just based on the class type" }
14698
<p>My application hangs up on IE and mobile browsers when these functions are fired. Is there anything that stands out as being obviously performance-killing?</p> <pre><code>$this.find('input.bundle-check').live('change', function() { var $box = $(this), ntn = $box.data().ntn, price = $box.data().price, savings = $box.data().savings; if ($box.is(':checked')) { productsBundled[ntn] = { "price" : price, "savings" : savings, "ntnid" : ntn, "qty" : 1 }; $box.siblings('label').text(' Selected') $box.closest('.grid-product').fadeTo(300, 0.5) } else { $box.siblings('label').text(' Add Item'); delete productsBundled[ntn]; $box.closest('.grid-product').fadeTo(300, 1.0) } refreshSelectedItems(productsBundled); $this.find('.itemCount').text(concat('(',objectCount(productsBundled),')')); }) function refreshSelectedItems(products, remote) { var itemntns = [], totalPrice=0.00, totalSavings=0.00; products = products || {}; remote = remote || 2; if (objectCount(products) &gt; 0) { $.each(products, function(i, item) { $qtyBox = $('.selected-item[data-ntn=' + i + '] .cartqty'); itemntns.push(i); totalPrice += (item.price * ($qtyBox.val() || 1)); totalSavings += (item.savings * ($qtyBox.val() || 1)); // console.log('qtyBox', $qtyBox.val()) }); if(remote &gt; 1) { $.ajax({ url: '/Includes/pageHelper.cfc', type: 'post', async: true, data: { method: "getBundleSelectedItems", productList: itemntns.join(',') }, success: function(data) { var $container = $('.selected-items &gt; span'); $container.html(data); $.each($container.find('.selected-item'), function() { var myntn = $(this).data().ntn, $price = $(this).find('.price'), $bunPrice = $('&lt;span /&gt;').addClass('bundle-price'); $(this).find('.cartqty').val(productsBundled[myntn].qty); if (productsBundled[myntn].savings &gt; 0) { $bunPrice.text(concat(' $', productsBundled[myntn].price.toFixed(2))); $(this).find('em').hide(); $price.after($bunPrice.after($('&lt;span /&gt;').addClass('sale').text(concat(' You save $', productsBundled[myntn].savings.toFixed(2), '!')))); } }) } }) } } else { $('.selected-items &gt; span').html(''); } $this.find('.bundle-saving').text(concat("$", totalSavings.toFixed(2))); $this.find('.bundle-addons').text(concat("$", totalPrice.toFixed(2))); totalPrice = totalPrice + (parseFloat($('.original-products &gt; div:has(:checked)').data().price) * parseInt($('.original-products &gt; div:has(:checked) .cartqty').val())); $this.find('.bundle-total').text(concat("$", totalPrice.toFixed(2))); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T14:44:51.150", "Id": "23881", "Score": "1", "body": "well... live() should no longer be used.. it is deprecated. In newer versions use .on() and in older versions use .delegate() - not sure if this will impact performance ***that*** much, but .live() is known to be slow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T14:47:03.253", "Id": "23882", "Score": "0", "body": "I typically use `on`, but this content can be loaded with AJAX. maybe this was too much of a shortcut to simply rebinding?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T15:31:13.387", "Id": "23886", "Score": "0", "body": "@KyleMacey If the content can be added after the handler is attached, then bind to a parent element [that is always there] and provide the selector of the children to bind the handler to: `$this.on('click', 'input.bundle-check', handler);` . The API [explains this](http://api.jquery.com/on/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T15:32:57.117", "Id": "23887", "Score": "0", "body": "I always wondered what the advantage was of that syntax... thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T06:50:11.623", "Id": "23952", "Score": "0", "body": "it would probably be quicker to use a for() loop instead of $.each(products, function(i, item) {" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-02T12:05:28.020", "Id": "366691", "Score": "0", "body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about [what your code does](//codereview.meta.codereview.stackexchange.com/q/1226) and what the purpose of doing that is, the easier it will be for reviewers to help you. The current title states your concerns about the code; it needs an [edit] to simply *state the task*; see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>There are a few things which stand out to me:</p>\n\n<pre><code>var $box = $(this),\nntn = $box.data().ntn,\nprice = $box.data().price,\nsavings = $box.data().savings;\n</code></pre>\n\n<p>You use <code>$box.data()</code> several times; it may be faster to cache the return value of that function. </p>\n\n<pre><code>if ($box.is(':checked')) {\n</code></pre>\n\n<p><code>:checked</code> is not a standard CSS selector, so it will be slower than simply:</p>\n\n<pre><code>if (this.checked) {\n</code></pre>\n\n<p>Later, you used</p>\n\n<pre><code> $.each($container.find('.selected-item'), function() {\n</code></pre>\n\n<p>I'm not sure if it's faster, but you could just do:</p>\n\n<pre><code> $container.find('.selected-item').each(function() {\n</code></pre>\n\n<p>Finally, this line:</p>\n\n<pre><code>totalPrice = totalPrice + (parseFloat($('.original-products &gt; div:has(:checked)').data().price) * parseInt($('.original-products &gt; div:has(:checked) .cartqty').val()));\n</code></pre>\n\n<p><a href=\"http://api.jquery.com/has-selector/\" rel=\"nofollow\">The <code>:has</code> selector is not standard CSS, so it can't use browsers' native functions. instead, consider using the <code>has()</code> method instead</a>:</p>\n\n<pre><code>totalPrice = totalPrice + (parseFloat($('.original-products').children('div').has(':checked').data().price) * parseInt($('.original-products').children('div').has(':checked').find('.cartqty').val(), 10));\n</code></pre>\n\n<p>Note that I also added the <code>radix</code> argument to <code>parseInt</code>. A micro-optimization at best, but it does mean the JS engine doesn't need to guess.</p>\n\n<p>Hope that helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T16:35:16.417", "Id": "14703", "ParentId": "14699", "Score": "1" } } ]
{ "AcceptedAnswerId": "14703", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T14:38:50.020", "Id": "14699", "Score": "-3", "Tags": [ "javascript", "performance", "jquery" ], "Title": "Functions Giving Performance Issues" }
14699
<p>I made the following class to wrap <code>mysqli</code> for PHP using prepared statements. It seems to work well, but I was hoping to get opinions (on overall structure, performance, usage, etc.). Thanks for the insight.</p> <pre><code>&lt;?php class database { private $conn, $stmt, $arr, $eof=true, $error; public function __construct($host, $user, $pass, $db) { $this-&gt;conn = mysqli_connect($host, $user, $pass, $db); if(mysqli_connect_errno()) $this-&gt;error = mysqli_connect_error(); } public function __destruct() { if($this-&gt;stmt) mysqli_stmt_close($this-&gt;stmt); mysqli_close($this-&gt;conn); } /** Executes a prepared SQL query on the database * * The second argument (optional) is the types list, followed by the parameters * e.g. query('SELECT * FROM table WHERE id = ? OR name = ?', 'is', 5, 'Joe') * * @param string $query is the sql statement to execute * @return mixed false on error, * true on successful select, or * the number of affected rows */ public function query($query) { // create a new prepared statement $stmt = mysqli_prepare($this-&gt;conn, $query); if(!$stmt) { $this-&gt;error = mysqli_error($this-&gt;conn); return false; } // apply the arguments if any exist if(func_num_args() &gt; 2) { $args = array_slice(func_get_args(), 1); $refs = array(); foreach($args as $key=&gt;&amp;$value) $refs[$key] = &amp;$value; call_user_func_array(array($stmt, 'bind_param'), $refs); } // run the query $stmt-&gt;execute(); if($stmt-&gt;errno) { $this-&gt;error = mysqli_error($this-&gt;conn); return false; } // if the query was not a select, return the number of rows affected if($stmt-&gt;affected_rows &gt; -1) { $rows = $stmt-&gt;affected_rows; mysqli_stmt_close($stmt); return $rows; } // close any previous statement if($this-&gt;stmt) mysqli_stmt_close($this-&gt;stmt); $this-&gt;stmt = $stmt; $this-&gt;eof = false; // bind the results to the associative array $this-&gt;arr = array(); $refs = array(); $meta = mysqli_stmt_result_metadata($stmt); while($column = mysqli_fetch_field($meta)) { $refs[] = &amp;$this-&gt;arr[str_replace(' ', '_', $column-&gt;name)]; } call_user_func_array(array($stmt, 'bind_result'), $refs); // make the first result set available $this-&gt;next(); return true; } // fetches the next row public function next() { if($this-&gt;stmt) { $ret = mysqli_stmt_fetch($this-&gt;stmt); // populates $this-&gt;arr $this-&gt;eof = ($ret !== true); if($ret === false) $this-&gt;error = mysqli_error($this-&gt;conn); } } // returns an associative array of the results public function results() { // must make a copy when returning the entire array because // the array holds references that may be updated $ret = array(); foreach($this-&gt;arr as $key=&gt;$value) $ret[$key] = $value; return $ret; } // return the value for the specified field public function result($field) { return $this-&gt;arr[$field]; } public function __get($field) { return $this-&gt;result($field); } // returns true if eof has occured or an error public function eof() { return $this-&gt;eof; } // returns the number of rows in the result set public function count() { return ($this-&gt;stmt ? $this-&gt;stmt-&gt;num_rows : 0); } // returns the last error message, if clear is true, clears the error as well public function error($clear=false) { $err = $this-&gt;error; if($clear) $this-&gt;error = ''; return $err; } } ?&gt; </code></pre>
[]
[ { "body": "<p>Instead of assigning your properties null or empty values from the start, just define them with no values. If they aren't initialized, then they will resolve to null. Although, from what I can tell, you aren't doing much checking of these properties anyways, so I don't understand why you had default values anyways. You really should be verifying these properties before you use them.</p>\n\n<pre><code>private\n $conn,\n $stmt,\n $arr,\n $eof=true,\n $error\n;\n</code></pre>\n\n<p>You should always specify the access level of your methods and properties (public, private, protected). You did fairly well with your properties, but then you ignore your methods. Sure, right now PHP defaults to making each of these methods public by default, but this will be deprecated before too much longer. Plan for the future and define them properly. Besides, this is just good coding practice.</p>\n\n<p>Always, always, always use braces on your statement. In languages such as Python, where braces don't exist, this is fine, but in PHP this is wrong. Even though PHP allows this syntax, even they say it is wrong, because it CAN cause issues with the code. Not to mention problems with reading the code. Its two characters, and doesn't hurt anything to add them, but it could cause all kinds of problems by not adding them. You do this quite a bit, so I wont point out each case.</p>\n\n<pre><code>if(mysqli_connect_errno()) { $this-&gt;error = mysqli_connect_error(); }\n</code></pre>\n\n<p>When you have a lot to say in the comments, don't use single line comments, use block comments. Or better yet, since you seem to be documenting the behavior of a method here, you should be using PHPDoc comments.</p>\n\n<pre><code>/* returns false on error, true on successful select, number of affected rows otherwise\nat minimum, query is the sql statement to execute\nif there are query parameters, the second argument is is the types list, followed by the parameters\ne.g. query('SELECT * FROM table WHERE id = ?', 'i', 5)*/\n//OR PHPDoc Comments\n/** Queries database\n *\n * The second argument is is the types list, followed by the parameters\n *\n * e.g. query('SELECT * FROM table WHERE id = ?', 'i', 5)\n *\n * @param string $query At minimum, query is the sql statement to execute if there are query parameters\n *\n * @return mixed false on error, true on successful select, number of affected rows otherwise\n */\n</code></pre>\n\n<p>You lied to us in the documentation and promised us a third and, at the very least, fourth parameter in your <code>query()</code> method. But they are no where in sight. I do see that you have decided to use <code>func_get_args()</code> in there, but that's a big no-no (at least for something so simple). If you want to pass an unspecified number of parameters, do so as an array. That's all you are really getting with <code>func_get_args()</code> anyways. Either way, your documentation should properly reflect your code, otherwise it is useless. Besides the parameter issue, there is something fundamentally wrong with your <code>query()</code> method. It is entirely too busy. Two very common principles that are always associated with OOP are the \"Single Responsibility\" (SR) Principle and the \"Don't Repeat Yourself\" (DRY) Principle, the first isn't normally shortened to that acronym, but I will do so in this answer to avoid repeating myself. These two principles go hand in hand, and you have potentially violated both of them.</p>\n\n<p>SR tells me that this method should only be focused with querying the database and returning the results, after all, that's what you called it <code>query()</code>. However, you are doing so much more. Such as binding the parameters and executing the statement. I wont explain each deviation to you, because you need to be able to separate your code properly, but those two should help get you started. I'm also not entirely certain, but is it necessary for that array to be assigned values by reference? I didn't feel like following it all the way through to make sure.</p>\n\n<p>You have potentially violated the DRY principle because each of the tasks I listed above, and each of the others I didn't, could potentially be reused in this class. Instead they are hardcoded into the one method and therefore their potential is being wasted.</p>\n\n<p>Here's another DRY violator. If you have two methods performing the same task, either A) get rid of one of them, or B) have one of them point to the other. This way if you ever decided to change which array you were fetching from, you would only have to do so once. This is one of the key benefits of DRY.</p>\n\n<pre><code>function result($field) { return $this-&gt;arr[$field]; }\nfunction __get($field) { return $this-&gt;result($field); }\n</code></pre>\n\n<p>Ternary functions, unless nested (which they should never be), don't require parenthesis. So, this could be a stylistic point, but figured I'd let you know.</p>\n\n<pre><code>function count() { return $this-&gt;stmt ? $this-&gt;stmt-&gt;num_rows : 0; }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T23:56:21.853", "Id": "23941", "Score": "0", "body": "I agree with a few of your points and updated accordingly. The 3rd point I feel is stylistic and find it easier to read personally. Your 4th point: I use `func_get_args()` because that function serves 2 purposes, example: `query('SELECT * FROM table')` and `query('SELECT * FROM table WHERE name = ? AND email = ?', 'ss', 'Joe', 'email@email.com')`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T23:59:53.580", "Id": "23943", "Score": "0", "body": "Your 5th point, the point of the class is it easier to use prepared statements, which is part of the query to the database. I will break up the functions if it is ever needed to avoid duplicating code. The values must be passed by reference for `bind_result` to work. Thanks for the insights." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T01:26:16.573", "Id": "23945", "Score": "0", "body": "The 3rd point is not stylistic, it CAN cause issues with the code and is something that should never have been allowed. I understand why you are using `func_get_args()`, as I explained, that same thing can be accomplished by passing an array as a second parameter just give it a default empty value. If you break up the `query()` method now you wont have to later, and it makes reading your code easier. I'm not saying you can't do all of that in one method, but the details about how each step is performed should be separated into different methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T17:38:41.733", "Id": "28034", "Score": "0", "body": "@steveo225: I thought I'd revisit this since it came to my attention today and I've come to have a slightly better understanding of the braceless syntax. I still stand by what I said, but I would like to apologize. It IS a preference, though I still feel it is wrong. As long as you understand the pitfalls and have weighed the consequences it is perfectly fine to use this syntax. I'll just cringe every time I see it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T21:13:03.650", "Id": "14719", "ParentId": "14701", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T15:31:34.067", "Id": "14701", "Score": "4", "Tags": [ "php", "mysqli" ], "Title": "mysqli wrapper class" }
14701
<p>It's an interview question, I was asked to compare 2 strings, and the number in the string are evaluated to integers when comparing. </p> <p>I can use C/C++ and can not use stl or stdlib. Some test cases are showed in the code.</p> <p>I submitted the code below but failed. The interviewer said that the code is not clean enough. Can anybody review the code?</p> <pre><code>#include &lt;cstdio&gt; #include &lt;cmath&gt; bool is_num(char x) {return (x&gt;='0' &amp;&amp; x&lt;='9');} int get_num(const char* s, int len) { int j = 0; int ret = 0; while (len &gt; 0) { ret += (s[j++] - '0') * pow(10, len-1); len --; } return ret; } int my_compare(const char* s1, const char* s2) { while((*s1)&amp;&amp;(*s2)) { int value1 = 0; int value2 = 0; bool is_t1_num = false; bool is_t2_num = false; int len_t1 = 0; int len_t2 = 0; const char* t1; const char* t2; if (is_num(*s1)) { t1 = s1; while(is_num(*t1)&amp;&amp;(*t1)) { len_t1 ++; t1++; } value1 = get_num(s1, len_t1); is_t1_num = true; } if (is_num(*s2)) { t2 = s2; while(is_num(*t2)&amp;&amp;(*t2)) { len_t2 ++; t2++; } value2 = get_num(s2, len_t2); is_t2_num = true; } if ((!is_t1_num) &amp;&amp; (!is_t2_num)) { if ((*s1) &lt; (*s2)) return -1; if ((*s1) &gt; (*s2)) return 1; s1++; s2++; } if ((is_t1_num) &amp;&amp; (is_t2_num)) { if (value1 &lt; value2) return -1; if (value1 &gt; value2) return 1; s1 += len_t1; s2 += len_t2; } if ((is_t1_num) &amp;&amp; (!is_t2_num)) { if (value1&gt;0) return 1; s1 += len_t1; } if ((!is_t1_num) &amp;&amp; (is_t2_num)) { if (value2&gt;0) return -1; s2 += len_t2; } }//end while if (!(*s1) &amp;&amp; !(*s2)) return 0; if (!(*s1)) return -1; if (!(*s2)) return 1; } int main() { //TEST CASE 0 printf("%d\n", my_compare("ab", "1")); printf("%d\n", my_compare("123", "456")); printf("%d\n", my_compare("abc", "def")); printf("%d\n", my_compare("abc123def", "abc000def")); printf("%d\n", my_compare("ab", "abc")); //TEST CASE 1 printf("%d\n", my_compare("abc000def", "abcdef")); printf("%d\n", my_compare("abc101def", "abcdef")); //TEST CASE 2 printf("%d\n", my_compare("abc101def", "abceef")); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:41:21.880", "Id": "23907", "Score": "0", "body": "The requirements are not really clear: from the code it seems that the return value of the function is the value stored in the strings if both strings are the same. What about when they differ, what should be the returned value? Additionally, the requirements don't mention whether the number must be positive, what if the input is \"-1\"?" } ]
[ { "body": "<p>First pick a language.</p>\n\n<p>Either use C or use C++. Do <strong>NOT</strong> use a mixture of the two (its sloppy and can introduce bugs). So first off you should have picked a language. You seem to have picked both:</p>\n\n<pre><code> #include &lt;cmath&gt; // C++\n printf(\"%d\\n\", my_compare(\"ab\", \"1\")); // Why use printf in C++\n // It is obtuse dangerous (not type safe).\n</code></pre>\n\n<p>The two languages have a basic similar syntax but they are different languages treat them as such.</p>\n\n<p>Know what is available from the standard libraries:</p>\n\n<pre><code>bool is_num(char x) {return (x&gt;='0' &amp;&amp; x&lt;='9');}\n</code></pre>\n\n<p>This exists in the standard library as std::isdigit()</p>\n\n<p>If this is C++ why are you passing C-Strings around.</p>\n\n<pre><code>int get_num(const char* s, int len)\n</code></pre>\n\n<p>Much better to write:</p>\n\n<pre><code>int get_num(std::string const&amp; s)\n</code></pre>\n\n<p>Also there is no point in writing this function (especially since it is error prone to do so.</p>\n\n<ul>\n<li>In c++ use <code>operator&gt;&gt;</code> to stream to an int.</li>\n<li>In C use <code>sscanf(s, \"%d%n\", &amp;value, $length)</code>.</li>\n</ul>\n\n<p>Also your variable names are bad. Pick names that make it easy to read the code and understand what you are doing.</p>\n\n<pre><code> int j = 0;\n int ret = 0;\n while (len &gt; 0)\n {\n // Why add the extra complexity of `j++` here.\n // You have made the expression hard enough to read as it is.\n // You don;t get points for being clever in an interview its readability\n // we want to see.\n ret += (s[j++] - '0') * pow(10, len-1);\n len --;\n }\n return ret;\n}\n</code></pre>\n\n<p>Yes in C it is traditional to put all the variables at the top of the function (so fine for C). But in C++ this is considered bad practice and sloppy. Declare variables as close to the point you want to use them (preferably just before you use them). That way you can see the type at the point you are using them.</p>\n\n<pre><code> int value1 = 0;\n int value2 = 0;\n bool is_t1_num = false;\n bool is_t2_num = false;\n int len_t1 = 0;\n int len_t2 = 0;\n const char* t1;\n const char* t2;\n</code></pre>\n\n<p>You are repeating the same processes twice.<br>\nFirst you scan over the string finding the length of the number.<br>\nSecond you scan over the string calculating the value of the number.<br>\nThere is no need to do that. Use one pass.</p>\n\n<pre><code> while(is_num(*t1)&amp;&amp;(*t1))\n {\n len_t1 ++;\n t1++;\n }\n value1 = get_num(s1, len_t1);\n</code></pre>\n\n<p>Also you have the same boilerplate code for both t1 and t2. If you have code that does the same thing factor it out into a function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T08:30:36.777", "Id": "23955", "Score": "1", "body": "He said he could not use stl nor stdlib. If I'm right, `std::string` is part of the stl. I don't see the point in not being allowed to use them though since you'll have to use them when working. And saying that stdlib is not allowed, is it `stdlib.h` or the whole C standard library?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T17:47:59.033", "Id": "14706", "ParentId": "14705", "Score": "5" } } ]
{ "AcceptedAnswerId": "14706", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T17:26:04.520", "Id": "14705", "Score": "1", "Tags": [ "c++", "c", "interview-questions" ], "Title": "C/C++ code to do customized string comparing" }
14705
<p>I was selected for the third round of MS internships for third years. We were surprisingly asked a very easy question: “Make a program that counts the number of times the WORD "a" or "A" occurs”. I wrote the code below and was rejected from attending the final interview.</p> <p>What is wrong with my code? Please tell me how to improve it. People who used <code>Char[]</code> instead of <code>string</code> and those who didn't check for first and last words to be "A" were all selected. The condition for commas before and after 'a' was also ignored. What is the error? Is <code>str.at(i)</code> not good enough...? I know even if we use <code>str[i]</code> it is interpreted as <code>str.operator[](i)</code>, so I'm preventing the overhead conversion, right?</p> <pre><code>#include&lt;iostream&gt; #include&lt;ctype.h&gt; #include&lt;string&gt; using namespace std; int main() { string str; getline(cin,str); int i; int count=0; int l=str.length(); for(i=1;i&lt;l-1;i++) { if(toupper(str.at(i))=='A') if(str.at(i-1)==' ' &amp;&amp; str.at(i+1)==' ') count++; } if(toupper(str.at(0))=='A' &amp;&amp; str.at(1)==' ') count++; if(toupper(str.at(l-1))=='A' &amp;&amp; str.at(l-2)==' ') count++; cout&lt;&lt;"Count is "&lt;&lt;count&lt;&lt;endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:17:11.750", "Id": "23902", "Score": "1", "body": "What version of C++ are you using? I'm not familiar with the `included` statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:19:51.500", "Id": "23903", "Score": "2", "body": "One problem I see is: what happens if your input string is just 'A'?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:20:35.273", "Id": "23904", "Score": "0", "body": "\"a\" & 'a' are different, 'a' is a single character whereas \"a\" is a *string* i.e. 'a','\\0'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:21:45.907", "Id": "23905", "Score": "1", "body": "What I would have done is use a `std::stringstream`. I think that is the easiest possible way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T19:01:55.607", "Id": "23913", "Score": "1", "body": "I would have tried a state machine. It is probably quite simple to implement and have a single forwarding loop over the input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T09:55:51.373", "Id": "385236", "Score": "0", "body": "`using namespace std;` - I'd probably stop reading there, TBH." } ]
[ { "body": "<p>You should do this by using the standard library to its fullest:</p>\n\n<pre><code>std::istringstream ss(str);\nauto count = std::count_if(std::istream_iterator&lt;std::string&gt;(ss), std::istream_iterator&lt;std::string&gt;(), \n [](const std::string&amp; s){ return s == \"a\" || s == \"A\"; });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T19:01:24.967", "Id": "23912", "Score": "0", "body": "@David Rodríguez - dribeas You're both wrong. It works. Try it or read it more carefully. http://ideone.com/qq3Bd" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T19:56:51.090", "Id": "23918", "Score": "2", "body": "Unfortunately this fails if there is punctuation in the input stream." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T01:50:24.287", "Id": "24001", "Score": "0", "body": "More accurately it fails to detect 'a' or 'A' as a word if an adjacent character is punctuation. But, this just replaces the OPs code - it doesn't add extra functionality." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:35:22.657", "Id": "14712", "ParentId": "14711", "Score": "7" } }, { "body": "<pre><code>included &lt;iostream&gt; &lt;ctype.h&gt; &lt;string&gt;\n</code></pre>\n\n<p>If this is the actual code you sent, I probably wouldn't have read past this line. It's not valid C++ or anything. It suggests you didn't even try to compile and run this. </p>\n\n<pre><code>using namespace std;\n\nint main()\n{\n\n string str;\n\n getline(cin,str);\n\n int i;\n</code></pre>\n\n<p>Why are you declaring this here instead of the for loop</p>\n\n<pre><code> int count=0;\n int l=str.length();\n\n for(i=1;i&lt;l-1;i++)\n {\n if(toupper(str.at(i))=='A')\n if(str.at(i-1)==' ' &amp;&amp; str.at(i+1)==' ')\n count++;\n</code></pre>\n\n<p>I wouldn't have nested braceless blocks like this. It can making things harder to read. \n }</p>\n\n<pre><code> if(toupper(str.at(0))=='A' &amp;&amp; str.at(1)==' ')\n count++;\n\n if(toupper(str.at(l-1))=='A' &amp;&amp; str.at(l-2)==' ')\n count++;\n</code></pre>\n\n<p>This is an ugly solution. It'd be better if you worked this into the loop.</p>\n\n<pre><code> cout&lt;&lt;\"Count is \"&lt;&lt;count&lt;&lt;endl;\n return 0;\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:41:31.900", "Id": "23908", "Score": "0", "body": "I would hope the interviewer knows what the first line means. If this was on a whiteboard, I'd do the same." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T20:21:54.680", "Id": "23920", "Score": "0", "body": "@GManNickG: White board sure. In sample code sent for interview not so much. It must compile." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T12:31:59.100", "Id": "23959", "Score": "0", "body": "Guys..It was a written test...and I included it ..you mean I should put those limit checking constraints into the loop..why to execute it again and again if it doesn't depend on the index i...? You guys think i complicated things using str.at(i)...? After that round I discovered that a loop iterating from 1 to n-1 and using char[] without converting to toupper was selected for next round.....Is it advantageous to use char[]...???" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:36:08.070", "Id": "14713", "ParentId": "14711", "Score": "5" } }, { "body": "<h3>Not an answer</h3>\n<p>don't vote.</p>\n<p>Extended comment.</p>\n<p>My first pass at this would be:</p>\n<pre><code>int main()\n{\n std::cout &lt;&lt; &quot;Count of word 'a' or 'A': &quot;\n &lt;&lt; std::count_if(std::istream_iterator&lt;std::string&gt;(std::cin),\n std::istream_iterator&lt;std::string&gt;(),\n [](std::string const&amp; word)\n {\n return word == &quot;a&quot; || word == &quot;A&quot;;\n }\n );\n}\n</code></pre>\n<p>But the problem with this is that this only breaks up words based on space. What happens if there is punctuation in the input?</p>\n<p>Well just imbue the stream with a facet that tells the stream functors that all non word characters are space and then the stream operators will work.</p>\n<pre><code>class OnlyLettersNotSpaceFacet: public std::ctype&lt;char&gt;\n{\n public:\n typedef std::ctype&lt;char&gt; base;\n typedef base::char_type char_type;\n\n OnlyLettersNotSpaceFacet(std::locale const&amp; l) : base(table)\n {\n // Get the ctype facet of the current locale\n std::ctype&lt;char&gt; const&amp; defaultCType = std::use_facet&lt;std::ctype&lt;char&gt; &gt;(l);\n\n // Copy the default flags for each character from the current facet\n static char data[256];\n for(int loop = 0; loop &lt; 256; ++loop) {data[loop] = loop;}\n defaultCType.is(data, data+256, table);\n\n for(int loop = 0; loop &lt; 256; ++loop)\n {\n if (!std::isalpha(loop))\n { table[loop] |= base::space; // anything that is not alpha\n } // is now considered a space.\n }\n }\n private:\n base::mask table[256];\n};\n</code></pre>\n<p>Now we can write the code just like we did first time (after imbuing the stream).</p>\n<pre><code>int main()\n{\n // Create a local and imbue the stream with it.\n const std::locale olns(std::cin.getloc(), new OnlyLettersNotSpaceFacet(std::cin.getloc()));\n std::cin.imbue(olns);\n\n\n std::cout &lt;&lt; &quot;Count of word 'a' or 'A': &quot;\n &lt;&lt; std::count_if(std::istream_iterator&lt;std::string&gt;(std::cin),\n std::istream_iterator&lt;std::string&gt;(),\n [](std::string const&amp; word)\n {\n return word == &quot;a&quot; || word == &quot;A&quot;;\n }\n );\n}\n// Note some systems have a bug in the standard where imbue on std::cin\n// silently fails. If this is the case then convert the code to read from a file.\n// Note you need to imbue the filestream `before` opening it.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T12:36:17.723", "Id": "23960", "Score": "0", "body": "In the previous round there was a question on merging two sorted arrays...If I had used STL then it takes 1 or two lines...but..i felt they are actually trying to test the concepts..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T12:50:07.857", "Id": "24023", "Score": "0", "body": "@SekharanNatarajan Then you should have asked if you could use STL. Personally I'm more impressed by proper library usage than ability to write a trivial low level algorithm (which, with c++11, is becoming an increasingly rare task in the real world)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T10:36:41.877", "Id": "24431", "Score": "0", "body": "True...but writing algorithm is what I believe they wanted to test on..Using an inbuilt algo is such cases makes the prob too easy rite????" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T06:14:10.073", "Id": "24497", "Score": "0", "body": "@SekharanNatarajan: I doubt it. This problem is designed to see if you understand how the formatted input operators work. operator>> reads a word. Can you use it with algorithms (the built in ones) can you spot the inherent problem (punctuation). What are some simple solutions to those problems (strip punctuation manually or use a locale to strip automatically)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T20:14:55.093", "Id": "14717", "ParentId": "14711", "Score": "5" } }, { "body": "<blockquote>\n <p>... and those who didn't check for first and last words to be \"A\" were all selected</p>\n</blockquote>\n\n<p>maybe they wrote a loop that didn't <em>need</em> to special case the first &amp; last characters, and that was considered cleaner?</p>\n\n<blockquote>\n <p>Is str.at(i) not good enough...?</p>\n</blockquote>\n\n<p><code>std::basic_string::at</code> does bounds checking. You either <em>need</em> this, in which case you've arguably written your loop condition poorly and <em>should be prepared to handle a <code>std::out_of_range</code> exception</em>, or you wrote the loop safely, don't need the bounds checking, and needn't pay for it.</p>\n\n<p>Because you <em>might</em> fail the bounds checking here, but <em>don't</em> handle the exception, your program will just terminate for some valid input strings.</p>\n\n<blockquote>\n <p>I know even if we use str[i] it is interpreted as str.operator, so I'm preventing the overhead conversion, right?</p>\n</blockquote>\n\n<p>what conversion? this is syntactic sugar resolved at compile time. You're either calling</p>\n\n<pre><code>str.at[i] =&gt; std::basic_string&lt;char&gt;::at(int i)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>str[i] =&gt; std::basic_string&lt;char&gt;::operator[](int i)\n</code></pre>\n\n<p>the fact that one has a fancy-looking syntax doesn't affect the cost of calling it.</p>\n\n<p>Actually, as I mentioned above, <code>operator[]</code> is <em>cheaper</em> because it <em>doesn't</em> do the bounds checking (which you don't handle correctly anyway).</p>\n\n<hr>\n\n<p>Oh, and for completeness, a sample (untested) one-pass state machine that doesn't require special cases for the first and last characters:</p>\n\n<pre><code>class CountA\n{\n int count_;\n enum { NewWord, PossibleMatch, NonMatch } state_;\n\n void next(char c)\n {\n if (isalnum(c)) { // assuming words are alphanumeric strings only\n switch (state_) {\n case NewWord: // first char of a new word\n state_ = (toupper(c) == 'A') ? PossibleMatch : NonMatch;\n break;\n case PossibleMatch: // had \"A\", got \"Ax\"\n state_ = NonMatch;\n case NonMatch: ; // just a non-match getting longer\n }\n } else {\n if (state_ == PossibleMatch) ++count_; // complete match!\n state_ = NewWord;\n }\n }\npublic:\n CountA() : count_(0), state_(NewWord) {}\n int count() const { return count_; }\n\n void scan(std::string const &amp;str)\n {\n char const *p = str.c_str();\n do {\n next(*p);\n } while(*p++);\n }\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T09:40:45.263", "Id": "14770", "ParentId": "14711", "Score": "3" } }, { "body": "<p>First of all, these interview questions are often a trick. It doesn't really matter if your code works for all cases (everybody makes mistakes). What does matter is how you write the code.</p>\n\n<p>Even if they ask specifically for 'a' or 'A', you are not supposed to hardcode these values. They are a parameter. Understanding what is the input to your program is always the first task. If they ask you \"Make a program that counts the number of times the letter 'a' occurs in 'Example'\", the correct answer won't be <code>return 1;</code>. They also ask for words, you shouldn't assume that the program should search only for words withs 1 letter.</p>\n\n<p>Second - words are not usually delimited only by a space. You should consider all whitespace and punctuation characters. Or just declare a function <code>isWordDelimiter(char)</code> and don't implement it.</p>\n\n<p>Third - your code is not easily readable. An <code>if</code> inside another <code>if</code> in a <code>for</code>? Use functions. Example (pseudocode - I am not C++ programmer and I forgot STL):</p>\n\n<pre><code>while ((word = getNextWord(input)) != NULL) {\n if (word is in set of searched words) { //replace this with STL set\n count++\n }\n}</code></pre>\n\n<p>Summary:\nEven on a very simple program, they can see how much experienced you are. Good developer won't just write something that works. He has to think how the problem will evolve in the future (different parameters), how the program will be maintained (write readable code). Good developers also write programs from top to bottom - first define the structure using high level functions, then write the implementation of the functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T09:50:24.927", "Id": "385233", "Score": "1", "body": "I wouldn't call such questions a \"trick\" - instead, they are seemingly-simple questions that can be attempted by anybody, but can also be ramped up to exercise even outstanding candidates (*\"How do you identify word boundaries? In Japanese?\"*). Also, in an interview (unlike a written test), they give the candidate an opportunity to show how they gather requirements (\"*What size input are you giving me? Do I need to case-fold in a specific locale?*\")." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T10:14:54.517", "Id": "14773", "ParentId": "14711", "Score": "11" } } ]
{ "AcceptedAnswerId": "14773", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T18:13:09.237", "Id": "14711", "Score": "9", "Tags": [ "c++", "strings", "interview-questions" ], "Title": "Count the number of occurrences of a word" }
14711
<p>At work I've recently been tasked with creating an XSLT to transform some XML as it is being generated on a scanner. The point being to disregard some pages that we are not interested in for further processing, and this is what I've come up with:</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"&gt; &lt;xsl:output method="xml" indent="yes"/&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;!-- Do an indentity transform for all root nodes/attributes --&gt; &lt;xsl:template match="@* | node()"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="@* | node()"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;!-- Strip out the sheet with RETURN barcode by replacing it with nothing (blank template) --&gt; &lt;xsl:template match="Page[contains(Fields/Barcode, 'RETURN')]" /&gt; &lt;!-- Check if there is a page containing RETURN in the barcode field. If yes append 'return' to all barcodes If no just copy everything --&gt; &lt;xsl:template match="Barcode"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="count(../../../Page[Fields/Barcode[contains(text(), 'RETURN')]]) &gt; 0"&gt; &lt;xsl:element name="Barcode"&gt; &lt;xsl:value-of select="concat(ancestor::Page/Fields/Barcode, 'Return')"/&gt; &lt;/xsl:element&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="@* | node()"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>Running on XML files with the following simplified structure, the actual files have around 100-3000 pages on average with some 40 fields under <code>Field</code>s:</p> <pre><code>&lt;Data&gt; &lt;Batch&gt; &lt;Page&gt; &lt;Fields&gt; &lt;Barcode&gt;|||||||||||&lt;/Barcode&gt; &lt;/Fields&gt; &lt;/Page&gt; &lt;Page&gt; &lt;Fields&gt; &lt;Barcode&gt;|RETURN|||||||||&lt;/Barcode&gt; &lt;/Fields&gt; &lt;/Page&gt; &lt;Page&gt; &lt;Fields&gt; &lt;Barcode&gt;||5454|||||||||&lt;/Barcode&gt; &lt;/Fields&gt; &lt;/Page&gt; &lt;/Batch&gt; &lt;/Data&gt; </code></pre> <p>It is working, but I'm a bit worried about the <code>Barcode</code> template running too slow as it must be \$O(n^2)\$. A quick profiling showed my concern to be correct.</p> <p><a href="http://s9.postimg.org/6jdir3s31/hot_patch.png" rel="nofollow">Hot path during execution</a></p> <p>As this will be running on somewhat limited hardware, does anyone have any suggestions for improvements?</p>
[]
[ { "body": "<p>I'd go with a <code>&lt;xsl:key ...&gt;</code> index, like so (at top level):</p>\n\n<pre><code>&lt;xsl:key name=\"contains_RETURN\" match=\"Barcode\" use=\"contains(text(), 'RETURN')\"/&gt;\n</code></pre>\n\n<p>and then rewrite your hotspot to:</p>\n\n<pre><code>&lt;xsl:when test=\"count(key('contains_RETURN', 'true')) &gt; 0\"&gt;\n ...\n&lt;/xsl:when&gt;\n</code></pre>\n\n<p>The idea is to partition Barcode nodes into two sets, the ones that contain 'RETURN' and the ones that don't. The <code>key</code> function as shown then evaluates to a nodeset that only contains <code>Barcode</code> nodes that contain 'RETURN' and hence <code>count</code> works as expected.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T16:31:04.447", "Id": "23981", "Score": "0", "body": "Sounds exactly like what i need. Thanks :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T06:07:18.713", "Id": "14728", "ParentId": "14715", "Score": "2" } }, { "body": "<p>I wonder if your contains() should really be an \"=\"? It's common to find people translating the english requirement \"the element contains 'RETURN'\" into a call on contains() when it should be a call on \"=\" (i.e. Fields/Barcode[.='RETURN']).</p>\n\n<p>Either way, keys are the way to go, but the solution will be simpler if the test is '=' rather than contains().</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T16:30:23.587", "Id": "23980", "Score": "0", "body": "Yes, it is necessary to use contains, as the barcode fields contains a pipe delimited string and the 'RETURN' part can be within 10 of them." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T08:00:21.673", "Id": "14732", "ParentId": "14715", "Score": "1" } } ]
{ "AcceptedAnswerId": "14728", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T19:28:27.460", "Id": "14715", "Score": "4", "Tags": [ "xml", "xslt" ], "Title": "Transforming XML as it is being generated on a scanner" }
14715
<p>I was asked to create a TODO manager using JavaScript and CSS. I did not get a good review on the code nor specific comments on how to improve it.</p> <p>Can someone here help by give me tips on what is bad with my implementation?</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.13/jquery-ui.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="jquery.ui.all.css"&gt; &lt;link rel="stylesheet" href="demos.css"&gt; &lt;!-- for the linked list --&gt; &lt;script type="text/javascript" src="linked-list.js"&gt;&lt;/script&gt; &lt;!-- for the popup ui --&gt; &lt;script src="thickbox.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="thickbox.css"&gt; &lt;style&gt; a img {border:none;} #todo { float: left; width: 10%; min-height: 12em; } * html #todo { height: 12em; } /* IE6 */ .todo.custom-state-active { background: #eee; } .todo li { float: left; width: 96px; padding: 0.4em; margin: 0 0.4em 0.4em 0; text-align: center; } .todo li h5 { margin: 0 0 0.4em; cursor: move; } .todo li a { float: right; } .todo li a.ui-icon-zoomin { float: left; } .todo li img { width: 100%; cursor: move; } #newtask { float: left; width: 30%; min-height: 60em; margin-left: 20px; margin-top:15px;} * html #newtask { height: 12em; } /* IE6 */ .newtask.custom-state-active { background: #eee; } .newtask li { float: left; width: 96px; padding: 0.4em; margin: 0 0.4em 0.4em 0; text-align: center; } .newtask li h5 { margin: 0 0 0.4em; cursor: move; } .newtask li a { float: right; } .newtask li a.ui-icon-zoomin { float: left; } .newtask li img { width: 100%; cursor: move; } #inprogress { float: left; width: 30%; min-height: 60em; margin-left: 20px;margin-top:15px;} * html #inprogress { height: 12em; } /* IE6 */ .inprogress.custom-state-active { background: #eee; } .inprogress li { float: left; width: 96px; padding: 0.4em; margin: 0 0.4em 0.4em 0; text-align: center; } .inprogress li h5 { margin: 0 0 0.4em; cursor: move; } .inprogress li a { float: right; } .inprogress li a.ui-icon-zoomin { float: left; } .inprogress li img { width: 100%; cursor: move; } #done { float: left; width: 30%; min-height: 60em; margin-left: 20px;margin-top:15px;} * html #inprogress { height: 12em; } /* IE6 */ .done.custom-state-active { background: #eee; } .done li { float: left; width: 96px; padding: 0.4em; margin: 0 0.4em 0.4em 0; text-align: center; } .done li h5 { margin: 0 0 0.4em; cursor: move; } .done li a { float: right; } .done li a.ui-icon-zoomin { float: left; } .done li img { width: 100%; cursor: move; } .popupStyle { display: none; position: absolute; top: 30%; left: 40%; width: 25%; height: 16%; padding: 2px; border: 3px solid #555555; background-color: #c78505; z-index:1002; overflow: auto; font-family: tahoma, verdana, sans-serif;} &lt;/style&gt; &lt;script&gt; // the four living states of a task var taskStateEnum = { NEW_TASK : 0, IN_PROGRESS : 1, TASK_DONE : 2, TASK_DELETED : 3 // if we ever want to implement the recover capability. for now, its unused }; // all tasks are held here var tasksList = new LinkedList(); // monotonically increasing unique task ID var taskID = 0; $(function() { var $todo = $( "#todo" ), $newtask = $( "#newtask"), $inprogress = $( "#inprogress"), $done = $( "#done" ); // let the todo items be draggable $( "li:gt(0)", $todo ).draggable({ cancel: "a.ui-icon", // clicking an icon won't initiate dragging revert: "invalid", // when not dropped, the item will revert back to its initial position containment: $( "#demo-frame" ).length ? "#demo-frame" : "document", // stick to demo-frame if present helper: "clone", cursor: "move" }); // let the inprogress be droppable, accepting the todo items $inprogress.droppable({ accept: "#todo &gt; li, #done li", activeClass: "ui-state-highlight", drop: function( event, ui ) { itemDroppedInProgress( ui.draggable ); } }); // let the done be droppable, accepting the inprogress items $done.droppable({ accept: "#inprogress li", activeClass: "ui-state-highlight", drop: function( event, ui ) { itemDroppedInDone( ui.draggable ); } }); // let the todo be droppable as well, accepting items from the done and inprogress $todo.droppable({ accept: "#inprogress li, #done li", activeClass: "custom-state-active", drop: function( event, ui ) { recycleImage( ui.draggable ); } }); // let the todo be droppable as well, accepting items from the done $newtask.droppable({ accept: "#inprogress li, #done li", activeClass: "ui-state-highlight", drop: function( event, ui ) { itemDroppedInTodo( ui.draggable ); recycleImage( ui.draggable ); } }); // image deletion function var recycle_icon = ""; function itemDroppedInTodo( $item ) { var id = $item.attr("id"); moveTask(id, taskStateEnum.NEW_TASK); updateTaskCounters(); } function itemDroppedInProgress( $item ) { $item.fadeOut(function() { var $list = $( "ul", $inprogress ).length ? $( "ul", $inprogress ) : $( "&lt;ul class='todo ui-helper-reset'/&gt;" ).appendTo( $inprogress ); $item.find( "a.ui-icon-inprogress" ).remove(); $item.append( recycle_icon ).appendTo( $list ).fadeIn(function() { $item .animate({ width: "48px" }) .find( "img" ) .animate({ height: "36px" }); }); }); var id = $item.attr("id"); moveTask(id, taskStateEnum.IN_PROGRESS); updateTaskCounters(); } function itemDroppedInDone( $item ) { $item.fadeOut(function() { var $list = $( "ul", $done ).length ? $( "ul", $done ) : $( "&lt;ul class='inprogress ui-helper-reset'/&gt;" ).appendTo( $done ); $item.find( "a.ui-icon-done" ).remove(); $item.append( recycle_icon ).appendTo( $list ).fadeIn(function() { $item .animate({ width: "48px" }) .find( "img" ) .animate({ height: "36px" }); }); }); var id = $item.attr("id"); moveTask(id, taskStateEnum.TASK_DONE); updateTaskCounters(); } // image recycle function var done_icon = ""; function recycleImage( $item ) { $item.fadeOut(function() { $item .find( "a.ui-icon-refresh" ) .remove() .end() .css( "width", "96px") .append( done_icon ) .find( "img" ) .css( "height", "72px" ) .end() .appendTo( $todo ) .fadeIn(); }); } }); // when the create button is clicked function onCreateTask() { tb_show("Provide some details about this task...", "#TB_inline?height=100&amp;width=460&amp;inlineId=divTaskDetails", ""); return false; } // shows the details of the current task function onShowTask(task) { document.getElementById('divTaskContent').innerHTML = task; tb_show("Task Details...", "#TB_inline?height=300&amp;width=400&amp;inlineId=divTask", ""); return false; } // update the text on the screen that shows the various task counters function updateTaskCounters() { var total = 0, tasksInProgress = 0, tasksDone = 0, tasksInTodo = 0; for (i = 0; i &lt; tasksList.size(); i++) { taskObj = tasksList.item(i); switch (taskObj.state) { case taskStateEnum.NEW_TASK: tasksInTodo++; total++; break; case taskStateEnum.IN_PROGRESS: tasksInProgress++; total++; break; case taskStateEnum.TASK_DONE: tasksDone++; total++; break; default: break; } } document.getElementById("inProgressCount").innerHTML = tasksInProgress + " Projects"; document.getElementById("doneCount").innerHTML = tasksDone + " Projects"; document.getElementById("todoCount").innerHTML = tasksInTodo + " Projects"; document.getElementById("totalCount").innerHTML = "Total: " + total + " Projects"; } function moveTask(task_id, where) { /* first find it then move it */ if (task_id &gt;= 0 &amp;&amp; task_id &lt; tasksList.size()) { var taskObj = tasksList.item(task_id); taskObj.state = where; } } function deleteTask(task_id) { /* first find it then move it */ if (task_id &gt;= 0 &amp;&amp; task_id &lt; tasksList.size()) { var taskObj = tasksList.item(task_id); taskObj.state = taskStateEnum.TASK_DELETED; } } // when a user creates a new task. this adds it to the todo bin function onAddTask() { var taskData = document.getElementById("task").value; taskID++; var taskObj = {data: taskData, state: taskStateEnum.NEW_TASK, id:taskID}; tasksList.add(taskObj); // always add the master task creater var html = "&lt;li class='ui-widget-content ui-corner-tr'&gt;" + "&lt;h5 class='ui-widget-header'&gt;New Task&lt;/h5&gt;" + "&lt;a href='' onclick='return onCreateTask();'&gt;&lt;img src='images/newtask.png' width='96' height='72'/&gt;&lt;/a&gt;" + "Click to create" + "&lt;/li&gt;"; // now fill in the tasks in the todo column for (i = 0; i &lt; tasksList.size(); i++) { taskObj = tasksList.item(i); /* only show new tasks in the UL */ if (taskObj.state != taskStateEnum.NEW_TASK) { continue; } if (taskObj.data.length &gt; 8) { var displayText = taskObj.data.substring(0,8) + "..."; } else { var displayText = taskObj.data; } html += "&lt;li id='" + i + "' class='ui-widget-content ui-corner-tr ui-draggable' style='width: 96px; display: list-item;'&gt;" + "&lt;h5 class='ui-widget-header'&gt;Click for details&lt;/h5&gt;" + "&lt;a onclick='return onShowTask(\""+ taskObj.data + "\");'&gt;&lt;img src=images/task.png width=96 height=72&gt;&lt;/a&gt;" + "&lt;p style='text-align:center;'&gt;" + displayText + "&lt;/p&gt;" + "&lt;a onclick='return onShowTask(\""+ taskObj.data + "\");' title='Details' class='ui-icon ui-icon-zoomin'&gt;View details&lt;/a&gt;" + "&lt;a title='Delete task' class='ui-icon ui-icon-trash'&gt;Delete task&lt;/a&gt;" + "&lt;/li&gt;"; } // Set the innerHTML of the todo column to show all the Todo tasks var todoList = document.getElementById("todo"); todoList.innerHTML = html; // This causes all of them to be draggable $("#todo li:gt(0)").draggable({ cancel: "a.ui-icon", // clicking an icon won't initiate dragging revert: "invalid", // when not dropped, the item will revert back to its initial position containment: $( "#demo-frame" ).length ? "#demo-frame" : "document", // stick to demo-frame if present stop: function(event, ui) { // updateTaskCounters(); }, drop: function( event, ui ) { itemDroppedInTodo( ui.draggable ); }, helper: 'clone', cursor: "move" }); // when the user wants to just trash a task compeletely $(".ui-icon-trash").on("click", function(e) { tb_show("Warning!", "#TB_inline?height=100&amp;width=260&amp;inlineId=divDelete", ""); e.preventDefault(); var id = $(this).parent("li").attr("id"); deleteTask(id); updateTaskCounters(); $(this).parent("li").remove(); }); updateTaskCounters(); tb_remove(); return false; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="totalCount" style="margin-left: 20px; font-size: 30px;"&gt;Total: 0 Projects&lt;/div&gt; &lt;!-- New task column. Nw tasks are created here --&gt; &lt;div id="newtask" class="ui-widget-content ui-state-default"&gt; &lt;h4 class="ui-widget-header"&gt; &lt;span class="ui-icon ui-icon-done"&gt;New Task&lt;/span&gt; New Task &lt;div id="todoCount" style="float:right"&gt;0 Projects&lt;/div&gt; &lt;br&gt; &lt;br&gt; &lt;/h4&gt; &lt;!-- todo column. initially, it just has the task creater widget --&gt; &lt;ul id="todo" class="todo ui-helper-reset ui-helper-clearfix"&gt; &lt;li class="ui-widget-content ui-corner-tr" id="0"&gt; &lt;h5 class="ui-widget-header"&gt;New Task&lt;/h5&gt; &lt;a href="" onclick='return onCreateTask();'&gt;&lt;img src="images/newtask.png" width="96" height="72"/&gt;&lt;/a&gt; Create Task &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;!-- inprogress column. tasks can only be dragged here from the todo column --&gt; &lt;div id="inprogress" class="ui-widget-content ui-state-default"&gt; &lt;h4 class="ui-widget-header"&gt; &lt;span class="ui-icon ui-icon-done"&gt;In Progress&lt;/span&gt; In Progress &lt;div id="inProgressCount" style="float:right"&gt;0 Projects&lt;/div&gt; &lt;br&gt; &lt;br&gt; &lt;/h4&gt; &lt;/div&gt; &lt;!-- Done column. Tasks can only be dragged here from the inprogress column --&gt; &lt;div id="done" class="ui-widget-content ui-state-default"&gt; &lt;h4 class="ui-widget-header"&gt; &lt;span class="ui-icon ui-icon-done"&gt;Done&lt;/span&gt; Done &lt;div id="doneCount" style="float:right"&gt;0 Projects&lt;/div&gt; &lt;br&gt; &lt;br&gt; &lt;/h4&gt; &lt;/div&gt; &lt;!-- Task Details Popup --&gt; &lt;div id="divTaskDetails" class="popupStyle"&gt; &lt;br&gt; &lt;br&gt; &lt;form id="taskForm" name="task" style="margin: 0; padding: 0" onsubmit="return onAddTask();"&gt; &lt;input id="task" type="text" size="72" name="task"&gt; &lt;input name="submit" type="submit" value="Submit" onclick="return onAddTask();"&gt; &lt;/form&gt; &lt;/div&gt; &lt;!-- SHow Task Details Popup --&gt; &lt;div id="divTask" class="popupStyle"&gt; &lt;div id="divTaskContent"&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Error Details Popup --&gt; &lt;div id="divDelete" class="popupStyle"&gt; &lt;br&gt; &lt;br&gt; &lt;center&gt;You have permanently deleted the task&lt;/center&gt; &lt;/div&gt; &lt;!-- Background for all popups --&gt; &lt;div id="divFade" class="blankStyle"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T20:29:09.430", "Id": "23921", "Score": "1", "body": "[Read the FAQ](http://codereview.stackexchange.com/faq). This website is not for full code reviews, only for small snippets, algorithms, and such." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T01:28:23.980", "Id": "23946", "Score": "5", "body": "@FlorianMargaine What makes you think that \"full\" code reviews aren't allowed? There might be a practicable limit to how large the code can be before people will decide to simply not read the question, but as far as the rules are concerned, the only requirement is that all relevant code be included in the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T16:12:51.050", "Id": "23978", "Score": "1", "body": "@sepp2k - If that's the case then, IMHO, the requirements should change." } ]
[ { "body": "<p>You code look ok but I suggust using a MVC library, since this will abstract and simplify your logic.</p>\n\n<p>Check out this project on github, called <a href=\"https://github.com/addyosmani/todomvc\" rel=\"nofollow\">TodoMVC</a>.\nTodoMVC shows how to use popular <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">MVC</a> libraries to implement the popular 'todo list' project.</p>\n\n<p>Examples can be found <a href=\"https://github.com/addyosmani/todomvc/tree/gh-pages/architecture-examples\" rel=\"nofollow\">here</a>.</p>\n\n<p>The easiest MVC library to use is <a href=\"http://hay.github.com/stapes/\" rel=\"nofollow\">stapes.js</a></p>\n\n<p>Here are a few tips for your code.\n1) Be consistent. Use jQuery instead of raw DOM manipulation. \nExample:</p>\n\n<p>Previous Code:</p>\n\n<pre><code>document.getElementById(\"inProgressCount\").innerHTML = tasksInProgress + \" Projects\";\ndocument.getElementById(\"doneCount\").innerHTML = tasksDone + \" Projects\";\ndocument.getElementById(\"todoCount\").innerHTML = tasksInTodo + \" Projects\";\ndocument.getElementById(\"totalCount\").innerHTML = \"Total: \" + total + \" Projects\";\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>$(\"#inProgressCount\").html( tasksInProgress + \" Projects\" );\n$(\"#doneCount\").html( tasksDone + \" Projects\");\n$(\"#todoCount\").html( tasksInTodo + \" Projects\");\n$(\"#totalCount\").html( \"Total: \" + total + \" Projects\");\n</code></pre>\n\n<p>2) <code>onAddTask()</code> should be split up into multiple functions since it's longer then 8 - 12 lines.</p>\n\n<p>3) Also, place all your CSS in external separate css files.</p>\n\n<p>For more tips check out.\n<a href=\"https://github.com/rwldrn/idiomatic.js\" rel=\"nofollow\">https://github.com/rwldrn/idiomatic.js</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T16:50:42.430", "Id": "15329", "ParentId": "14718", "Score": "2" } } ]
{ "AcceptedAnswerId": "15329", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T20:17:59.490", "Id": "14718", "Score": "3", "Tags": [ "javascript", "css", "html5", "jquery-ui", "to-do-list" ], "Title": "JavaScript implementation of a TODO manager" }
14718
<p>The way I am using this method assumes all data is byte-aligned, so I don't really care about the rest of the bits.</p> <p>This method is written in an extension of BinaryReader which provides more methods when I'm reading binary data from files. The BinaryReader provided does not appear to support reading bits.</p> <p>Is there a better way I could write this method? Also I'm not sure if there's a more direct way to build a bitmask so I did it the long way.</p> <pre><code>/* Returns the value of the first n bits. */ public byte ReadBits(byte n) { byte val = base.ReadByte(); byte sum = 0; for (int i = 0; i &lt; n; i++) sum += (byte)(val &amp; (1 &lt;&lt; i)); return sum; } </code></pre> <p>I am using .NET 3.5</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T22:30:40.083", "Id": "23932", "Score": "0", "body": "I don't think so. For example you read 4 bits and it tells the length of the following data. I'd want it as an int or a byte." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T22:55:04.763", "Id": "23934", "Score": "0", "body": "It is similar to ReadInt32 or ReadByte: just return a single value that is represented by the bytes that were read. Or in this case, bits. I have not thought about the case where there is no byte alignment, but adobe's SWF format is always byte-aligned." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T23:00:19.320", "Id": "23935", "Score": "0", "body": "Oh, I should probably mention that this particular method is written in an extension of BinaryReader, which is why it explicitly reads bytes as the first line rather than taking a stream of bytes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T23:15:57.507", "Id": "23938", "Score": "0", "body": "That would be an appropriate method for the BitConverter, where it takes some input and returns a converted value. However I think since I just need to read n bits and ignore the rest, it would be fastest to just do the operation in one call rather than making the extra conversion afterwards." } ]
[ { "body": "<p>I have not tested this that well. If anyone finds a bug, please let me know.</p>\n\n<pre><code>// Throws away the unused bits\npublic byte ReadFirstNBits(int n)\n{\n Contract.Requires(n &gt;= 0 &amp;&amp; n &lt;= 8, \"Code contract may be too slow for your needs\");\n byte val = base.ReadByte();\n return val &gt;&gt; (8 - n);\n}\n\n// Throws away the unused bits\npublic byte ReadLastNBits(int n)\n{\n Contract.Requires(n &gt;= 0 &amp;&amp; n &lt;= 8, \"Code contract may be too slow for your needs\");\n byte val = base.ReadByte();\n byte mask = (byte)((1 &lt;&lt; n) - 1);\n return val &amp; mask;\n}\n</code></pre>\n\n<p>You can try this for yourself if you have a Python prompt:</p>\n\n<pre><code>&gt;&gt;&gt; a = 0b11001001 \n&gt;&gt;&gt; a\n201\n&gt;&gt;&gt; a &gt;&gt; 4\n12\n&gt;&gt;&gt; a &gt;&gt; 5\n6\n&gt;&gt;&gt; a &gt;&gt; 3\n25\n&gt;&gt;&gt; a &gt;&gt; 6\n3\n&gt;&gt;&gt; a &gt;&gt; 2\n&gt;&gt;&gt; for i in range(8): print bin(a &gt;&gt; i)\n\n0b11001001\n0b1100100\n0b110010\n0b11001\n0b1100\n0b110\n0b11\n0b1\n&gt;&gt;&gt; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T23:31:49.520", "Id": "23939", "Score": "0", "body": "Bit-shifting has always been a mystery to me. I was reading this http://stackoverflow.com/a/141873/536607 and it sort of gives me a better idea and can understand why shifting would work for this problem. Hopefully it will come to mind immediately when working with bit operations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T15:57:28.903", "Id": "23977", "Score": "0", "body": "Well, I am glad this was helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T16:23:25.600", "Id": "23979", "Score": "0", "body": "`>= 0 && <= 8` shouldn't it be `>= 0 && < 8`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T16:55:53.103", "Id": "23983", "Score": "0", "body": "@luiscubal, you could chose to read the entire byte, which is 8 bits long, in which case `val >> 0` should just give you `val`. It is not as fast as simply calling `base.ReadByte()`, but it works correctly. The number of bits to read could be stored in a variable. I find the case where you wish to read `0` bits more ridiculous, but ... the computers do not necessarily do what you meant; only what you told them." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T22:21:31.647", "Id": "14725", "ParentId": "14721", "Score": "3" } } ]
{ "AcceptedAnswerId": "14725", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T21:42:45.623", "Id": "14721", "Score": "1", "Tags": [ "c#" ], "Title": "Reading the first n bits of a byte" }
14721
<p>I want to check if all items of a list meet a set of criteria:</p> <pre><code>bool AreValid(list&lt;string&gt; vals) { bool allValid=true; foreach(string val in vals) { if(!condition1) ... allValid=false; else if(!condition2) ... allValid=false; } return allValid; } </code></pre> <p>The reason I can't use LINQ <code>All()</code> is that for each failed condition I'm doing some job.</p> <p>is it safe to set <code>allValid</code> as <code>true</code> by default?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T01:40:54.610", "Id": "23948", "Score": "3", "body": "Why don't you just return false if any of the conditions fail?" } ]
[ { "body": "<p>It's safe. A few things to consider: </p>\n\n<ol>\n<li><p>When the list is empty you might want to return <code>false</code>.</p></li>\n<li><p>Consider using an abstract data type (instead of string) which stores your data (the string) and move the validation logic to there.</p></li>\n<li><p>As <em>Jeff Vanzella</em> already suggested, you can return <code>false</code> immediately when you now that a value is not valid. It's faster and easier to read:</p>\n\n<pre><code>bool AreValid(list&lt;string&gt; vals)\n{\n foreach(string val in vals)\n {\n if(!condition1)\n ...\n return false;\n if(!condition2)\n ...\n return false;\n }\n\n return true;\n\n} \n</code></pre>\n\n<p>Note that you don't need the <code>else</code> keyword anymore.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T05:39:34.480", "Id": "14727", "ParentId": "14723", "Score": "3" } }, { "body": "<p>Yes, it is fine - I mean it definitelly works and there is nothing unsafe in assigning default value of <code>True</code> to <code>allValid</code>.</p>\n\n<p>My concern is the design. The name of your method <code>AreValid</code> suggest that it is just checking if objects meet specific criteria. You've mentioned that for all those objects that do not meet the criteria there is something being done on them. That doesn't seem to be the very greatest approach.\nI would suggest you consider separating checking if objects meets condition and changing state of the objects. It will make your code simpler and easier to read and understand to others. Is changing object state really what you expect from the method named <code>AreValid</code>? It would be quite a surprise for me if I found similar method in the code base.</p>\n\n<p>The other thing is that you could use LiNQ and check for all the objects that do not meet the criteria and then perform some actions on those objects.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T08:19:20.977", "Id": "23954", "Score": "0", "body": "I am glad you found it helpful. As for the separation - take a look at CQRS (http://martinfowler.com/bliki/CQRS.html)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T06:27:42.577", "Id": "14729", "ParentId": "14723", "Score": "3" } } ]
{ "AcceptedAnswerId": "14729", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T22:12:18.290", "Id": "14723", "Score": "1", "Tags": [ "c#", "asp.net" ], "Title": "Validation default value" }
14723
<p><a href="http://www.codeproject.com/Articles/11015/The-Impossibly-Fast-C-Delegates" rel="nofollow">This legendary C++ delegate article</a> can be easily converted into C++11, without the need for fancy preprocessor magic in the original. I'd like to know if I got all the necessary C++11 nuances right. Suggestions?</p> <pre><code>#pragma once #ifndef DELEGATE_HPP # define DELEGATE_HPP #include &lt;cassert&gt; #include &lt;memory&gt; #include &lt;new&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; template &lt;typename T&gt; class delegate; template&lt;class R, class ...A&gt; class delegate&lt;R (A...)&gt; { using stub_ptr_type = R (*)(void*, A&amp;&amp;...); delegate(void* const o, stub_ptr_type const m) noexcept : object_ptr_(o), stub_ptr_(m) { } public: delegate() = default; delegate(delegate const&amp;) = default; delegate(delegate&amp;&amp;) = default; delegate(::std::nullptr_t const) noexcept : delegate() { } template &lt;class C, typename = typename ::std::enable_if&lt; ::std::is_class&lt;C&gt;{}&gt;::type&gt; explicit delegate(C const* const o) noexcept : object_ptr_(const_cast&lt;C*&gt;(o)) { } template &lt;class C, typename = typename ::std::enable_if&lt; ::std::is_class&lt;C&gt;{}&gt;::type&gt; explicit delegate(C const&amp; o) noexcept : object_ptr_(const_cast&lt;C*&gt;(&amp;o)) { } template &lt;class C&gt; delegate(C* const object_ptr, R (C::* const method_ptr)(A...)) { *this = from(object_ptr, method_ptr); } template &lt;class C&gt; delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const) { *this = from(object_ptr, method_ptr); } template &lt;class C&gt; delegate(C&amp; object, R (C::* const method_ptr)(A...)) { *this = from(object, method_ptr); } template &lt;class C&gt; delegate(C const&amp; object, R (C::* const method_ptr)(A...) const) { *this = from(object, method_ptr); } template &lt; typename T, typename = typename ::std::enable_if&lt; !::std::is_same&lt;delegate, typename ::std::decay&lt;T&gt;::type&gt;{} &gt;::type &gt; delegate(T&amp;&amp; f) : store_(operator new(sizeof(typename ::std::decay&lt;T&gt;::type)), functor_deleter&lt;typename ::std::decay&lt;T&gt;::type&gt;), store_size_(sizeof(typename ::std::decay&lt;T&gt;::type)) { using functor_type = typename ::std::decay&lt;T&gt;::type; new (store_.get()) functor_type(::std::forward&lt;T&gt;(f)); object_ptr_ = store_.get(); stub_ptr_ = functor_stub&lt;functor_type&gt;; deleter_ = deleter_stub&lt;functor_type&gt;; } delegate&amp; operator=(delegate const&amp;) = default; delegate&amp; operator=(delegate&amp;&amp;) = default; template &lt;class C&gt; delegate&amp; operator=(R (C::* const rhs)(A...)) { return *this = from(static_cast&lt;C*&gt;(object_ptr_), rhs); } template &lt;class C&gt; delegate&amp; operator=(R (C::* const rhs)(A...) const) { return *this = from(static_cast&lt;C const*&gt;(object_ptr_), rhs); } template &lt; typename T, typename = typename ::std::enable_if&lt; !::std::is_same&lt;delegate, typename ::std::decay&lt;T&gt;::type&gt;{} &gt;::type &gt; delegate&amp; operator=(T&amp;&amp; f) { using functor_type = typename ::std::decay&lt;T&gt;::type; if ((sizeof(functor_type) &gt; store_size_) || !store_.unique()) { store_.reset(operator new(sizeof(functor_type)), functor_deleter&lt;functor_type&gt;); store_size_ = sizeof(functor_type); } else { deleter_(store_.get()); } new (store_.get()) functor_type(::std::forward&lt;T&gt;(f)); object_ptr_ = store_.get(); stub_ptr_ = functor_stub&lt;functor_type&gt;; deleter_ = deleter_stub&lt;functor_type&gt;; return *this; } template &lt;R (* const function_ptr)(A...)&gt; static delegate from() noexcept { return { nullptr, function_stub&lt;function_ptr&gt; }; } template &lt;class C, R (C::* const method_ptr)(A...)&gt; static delegate from(C* const object_ptr) noexcept { return { object_ptr, method_stub&lt;C, method_ptr&gt; }; } template &lt;class C, R (C::* const method_ptr)(A...) const&gt; static delegate from(C const* const object_ptr) noexcept { return { const_cast&lt;C*&gt;(object_ptr), const_method_stub&lt;C, method_ptr&gt; }; } template &lt;class C, R (C::* const method_ptr)(A...)&gt; static delegate from(C&amp; object) noexcept { return { &amp;object, method_stub&lt;C, method_ptr&gt; }; } template &lt;class C, R (C::* const method_ptr)(A...) const&gt; static delegate from(C const&amp; object) noexcept { return { const_cast&lt;C*&gt;(&amp;object), const_method_stub&lt;C, method_ptr&gt; }; } template &lt;typename T&gt; static delegate from(T&amp;&amp; f) { return ::std::forward&lt;T&gt;(f); } static delegate from(R (* const function_ptr)(A...)) { return function_ptr; } template &lt;class C&gt; using member_pair = ::std::pair&lt;C* const, R (C::* const)(A...)&gt;; template &lt;class C&gt; using const_member_pair = ::std::pair&lt;C const* const, R (C::* const)(A...) const&gt;; template &lt;class C&gt; static delegate from(C* const object_ptr, R (C::* const method_ptr)(A...)) { return member_pair&lt;C&gt;(object_ptr, method_ptr); } template &lt;class C&gt; static delegate from(C const* const object_ptr, R (C::* const method_ptr)(A...) const) { return const_member_pair&lt;C&gt;(object_ptr, method_ptr); } template &lt;class C&gt; static delegate from(C&amp; object, R (C::* const method_ptr)(A...)) { return member_pair&lt;C&gt;(&amp;object, method_ptr); } template &lt;class C&gt; static delegate from(C const&amp; object, R (C::* const method_ptr)(A...) const) { return const_member_pair&lt;C&gt;(&amp;object, method_ptr); } void reset() { stub_ptr_ = nullptr; store_.reset(); } void reset_stub() noexcept { stub_ptr_ = nullptr; } void swap(delegate&amp; other) noexcept { ::std::swap(*this, other); } bool operator==(delegate const&amp; rhs) const noexcept { return (object_ptr_ == rhs.object_ptr_) &amp;&amp; (stub_ptr_ == rhs.stub_ptr_); } bool operator!=(delegate const&amp; rhs) const noexcept { return !operator==(rhs); } bool operator&lt;(delegate const&amp; rhs) const noexcept { return (object_ptr_ &lt; rhs.object_ptr_) || ((object_ptr_ == rhs.object_ptr_) &amp;&amp; (stub_ptr_ &lt; rhs.stub_ptr_)); } bool operator==(::std::nullptr_t const) const noexcept { return !stub_ptr_; } bool operator!=(::std::nullptr_t const) const noexcept { return stub_ptr_; } explicit operator bool() const noexcept { return stub_ptr_; } R operator()(A... args) const { // assert(stub_ptr); return stub_ptr_(object_ptr_, ::std::forward&lt;A&gt;(args)...); } private: friend struct ::std::hash&lt;delegate&gt;; using deleter_type = void (*)(void*); void* object_ptr_; stub_ptr_type stub_ptr_{}; deleter_type deleter_; ::std::shared_ptr&lt;void&gt; store_; ::std::size_t store_size_; template &lt;class T&gt; static void functor_deleter(void* const p) { static_cast&lt;T*&gt;(p)-&gt;~T(); operator delete(p); } template &lt;class T&gt; static void deleter_stub(void* const p) { static_cast&lt;T*&gt;(p)-&gt;~T(); } template &lt;R (*function_ptr)(A...)&gt; static R function_stub(void* const, A&amp;&amp;... args) { return function_ptr(::std::forward&lt;A&gt;(args)...); } template &lt;class C, R (C::*method_ptr)(A...)&gt; static R method_stub(void* const object_ptr, A&amp;&amp;... args) { return (static_cast&lt;C*&gt;(object_ptr)-&gt;*method_ptr)( ::std::forward&lt;A&gt;(args)...); } template &lt;class C, R (C::*method_ptr)(A...) const&gt; static R const_method_stub(void* const object_ptr, A&amp;&amp;... args) { return (static_cast&lt;C const*&gt;(object_ptr)-&gt;*method_ptr)( ::std::forward&lt;A&gt;(args)...); } template &lt;typename&gt; struct is_member_pair : std::false_type { }; template &lt;class C&gt; struct is_member_pair&lt; ::std::pair&lt;C* const, R (C::* const)(A...)&gt; &gt; : std::true_type { }; template &lt;typename&gt; struct is_const_member_pair : std::false_type { }; template &lt;class C&gt; struct is_const_member_pair&lt; ::std::pair&lt;C const* const, R (C::* const)(A...) const&gt; &gt; : std::true_type { }; template &lt;typename T&gt; static typename ::std::enable_if&lt; !(is_member_pair&lt;T&gt;{} || is_const_member_pair&lt;T&gt;{}), R &gt;::type functor_stub(void* const object_ptr, A&amp;&amp;... args) { return (*static_cast&lt;T*&gt;(object_ptr))(::std::forward&lt;A&gt;(args)...); } template &lt;typename T&gt; static typename ::std::enable_if&lt; is_member_pair&lt;T&gt;{} || is_const_member_pair&lt;T&gt;{}, R &gt;::type functor_stub(void* const object_ptr, A&amp;&amp;... args) { return (static_cast&lt;T*&gt;(object_ptr)-&gt;first-&gt;* static_cast&lt;T*&gt;(object_ptr)-&gt;second)(::std::forward&lt;A&gt;(args)...); } }; namespace std { template &lt;typename R, typename ...A&gt; struct hash&lt;::delegate&lt;R (A...)&gt; &gt; { size_t operator()(::delegate&lt;R (A...)&gt; const&amp; d) const noexcept { auto const seed(hash&lt;void*&gt;()(d.object_ptr_)); return hash&lt;typename ::delegate&lt;R (A...)&gt;::stub_ptr_type&gt;()( d.stub_ptr_) + 0x9e3779b9 + (seed &lt;&lt; 6) + (seed &gt;&gt; 2); } }; } #endif // DELEGATE_HPP </code></pre> <p>Example use:</p> <pre><code>#include &lt;iostream&gt; #include "delegate.hpp" struct A { void foo(int a) { std::cout &lt;&lt; "method got: " &lt;&lt; a &lt;&lt; std::endl; } }; void foo(int a) { std::cout &lt;&lt; "function got: " &lt;&lt; a &lt;&lt; std::endl; } int main(int argc, char* argv[]) { auto d1(delegate&lt;void (int)&gt;::from&lt;foo&gt;()); A a; auto d2(delegate&lt;void (int)&gt;::from&lt;A, &amp;A::foo&gt;(&amp;a)); auto d3(delegate&lt;void (int)&gt;{foo}); auto d4(delegate&lt;void (int)&gt;(&amp;a, &amp;A::foo)); d1(1); d2(2); d3(3); d4(4); int b(2); auto dx(delegate&lt;void ()&gt;( [b](){std::cout &lt;&lt; "hello world: " &lt;&lt; b &lt;&lt; std::endl;})); dx(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T11:51:53.470", "Id": "43958", "Score": "0", "body": "Is there any reason for using this instead of `std::function`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T12:32:34.313", "Id": "43961", "Score": "0", "body": "@ony It is usually faster, especially when using pointer to member template parameters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T12:52:07.637", "Id": "43965", "Score": "0", "body": "is there any reason to have slower implementation of `std::function` in C++ lib/run-time? As well there is code `return from([object, method_ptr](A const... args){ return (object.*method_ptr)(args...); }); }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T13:24:12.147", "Id": "43970", "Score": "0", "body": "@ony Benchmark and you'll see. If you like it, use it. Is there something wrong with the code? Does it fail to compile? If so, please post compile error. The code is C++11. You can also post a critique as an answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T10:30:30.110", "Id": "44915", "Score": "0", "body": "Last time I checked `std::function` is quite fast compared to the impossibly fast delegate class. I did this benchmark by using my [library](https://github.com/miguelishawt/Wink-Signals) awhile ago with Apple clang 4.1 (although the benchmark for std::function isn't actually there, I'm sure you could test it out yourself using your own code or even mine)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T10:38:33.380", "Id": "44916", "Score": "0", "body": "@miguel.martin Thanks, I don't really present the class here as some kind of holy grail delegate, but want to gather comments on the C++11 style I use. In my compiler setup `std::function` is about 10x slower than the impossibly fast delegate (when using template function pointer parameters)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T11:25:15.847", "Id": "48899", "Score": "0", "body": "Hey, I'd like to use this in one of my project. Is this the definitive version or have you improved it further?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T12:04:40.590", "Id": "48905", "Score": "0", "body": "@VittorioRomeo Hope it's going to work for you. I don't know, if this is the best solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T12:44:52.517", "Id": "48909", "Score": "0", "body": "@user1095108: check my answer below - so far so good" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T05:00:29.077", "Id": "70568", "Score": "0", "body": "Hi, can you please explain a bit how you came up with your hash function for this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T08:09:59.953", "Id": "70581", "Score": "0", "body": "@bjackfly It comes from `boost`: http://stackoverflow.com/questions/16471691/good-hash-function-for-pair-of-primitive-types" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T10:05:19.713", "Id": "70825", "Score": "0", "body": "@user1095108 You said *\"In my compiler setup, `std::function` is about 10x slower...\"*. What compiler/library is that? I've spent hours trying to beat gcc's libstdc++ implementation and everything I tried was exactly the same speed as `std::function`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T11:48:06.613", "Id": "70827", "Score": "0", "body": "@doug65536 That's the beauty of open-source development. What I wrote was true at the time, but it may not be anymore. Both `g++` and `libstdc++` change over time. You can use `::std::function`, if you think it is better than this delegate. I've had bad experiences with it, when doing some `OpenGL` programming. It showed high in the profiler output and so I've looked around for alternatives. In hindsight, I should not have bothered with it, though the subject is fascinating and has a long history." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T12:08:28.617", "Id": "70829", "Score": "0", "body": "@user1095108 If you were using MSVC, I remember a bug on [microsoft connect](https://connect.microsoft.com) complaining of an unbelievably slow `std::function` implementation. I tried to find it to quote the link, but it seems they purge old bugs or their search is really badly implemented (like their `std::function` implementation ;). Something like \"std::function copies the object more than 10x\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T12:12:23.853", "Id": "70830", "Score": "0", "body": "@user1095108 [Here it is](http://connect.microsoft.com/VisualStudio/feedback/details/649268)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-04T13:40:27.850", "Id": "85893", "Score": "0", "body": "The repeated, and ongoing edits to this question have completely invalidated the existing answers. This question has turned in to a mess of revisions, interleaved history, and is a very poor example of how Code Review questions should be managed. See [Can I edit my own question to include revised code? Also, how to handle iterative reviews?](http://meta.codereview.stackexchange.com/questions/1763/can-i-edit-my-own-question-to-include-revised-code-also-how-to-handle-iterativ)" } ]
[ { "body": "<p>It looks by and large OK. Just some nitpicks</p>\n\n<ul>\n<li><p>the default constructor could just be <code>delegate() = default;</code>, or otherwise initialize <em>all</em> members... or remove it entirely if it makes no sense.</p></li>\n<li><p>the copy constructor should use initialization, not assignment.</p></li>\n<li><p><code>swap</code> should return <code>void</code>.</p></li>\n<li><p>Assignment should pass-by-value:</p>\n\n<pre><code>delegate&amp; operator=(delegate rhs) { rhs.swap(*this); return *this; }\n</code></pre></li>\n<li><p>Invocation should use arbitrary arguments and forwarding:</p>\n\n<pre><code>template &lt;typename ...B&gt;\nR operator()(B &amp;&amp;... b)\n{\n return (*stub_ptr)(object_ptr, std::forward&lt;B&gt;(b)...);\n}\n</code></pre>\n\n<p>In fact, you should add <code>enable_if</code> with some variadic version of <code>is_constructible&lt;A, B&gt;...</code> to the operator so you don't create impossible overloads.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T19:01:00.947", "Id": "24057", "Score": "0", "body": "Thanks for your comments! I think the forwarding is still shaky, as the static function stubs still make copies of their arguments. Can this be fixed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T19:11:10.980", "Id": "24058", "Score": "0", "body": "@user1095108: I thought the invocation was `auto d = delegate::from_function<foo>();` -- there's no room for arguments, is there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-30T00:16:38.220", "Id": "28787", "Score": "0", "body": "What about lambdas? Can we turn them into delegates?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T23:20:25.263", "Id": "35032", "Score": "0", "body": "@WarrenSeine I've added lambda support." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-31T00:07:46.690", "Id": "46090", "Score": "0", "body": "Why should assignment pass by value?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:42:21.793", "Id": "48918", "Score": "4", "body": "@doug65536 to avoid having to have `const T&` and `T&&` versions of assignment; passing by value will choose move construction or copy construction automatically for `rhs`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T17:02:22.750", "Id": "14795", "ParentId": "14730", "Score": "15" } }, { "body": "<p>I love this! Ran some quick benchmarks:</p>\n\n<pre><code>int x{0}; \nfor(int xx = 0; xx &lt; 5; ++xx)\n{\n startBenchmark();\n {\n std::function&lt;int(int)&gt; t2 = [&amp;x](int i){ return i + x; };\n std::function&lt;void(int)&gt; t1 = [&amp;x, &amp;t2](int i){ x = t2(i); };\n for(int i = 0; i &lt; 1000000000; ++i) t1(i);\n } lo &lt;&lt; lt(\"std::func\") &lt;&lt; endBenchmark() &lt;&lt; endl;\n\n startBenchmark();\n {\n delegate&lt;int(int)&gt; t2 = [&amp;x](int i){ return i + x; };\n delegate&lt;void(int)&gt; t1 = [&amp;x, &amp;t2](int i){ x = t2(i); };\n for(int i = 0; i &lt; 1000000000; ++i) t1(i);\n } lo &lt;&lt; lt(\"ssvu::fastfunc\") &lt;&lt; endBenchmark() &lt;&lt; endl;\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>[std::func] 3278 ms\n[ssvu::fastfunc] 2147 ms\n[std::func] 3264 ms\n[ssvu::fastfunc] 2126 ms\n[std::func] 3302 ms\n[ssvu::fastfunc] 2182 ms\n[std::func] 3306 ms\n[ssvu::fastfunc] 2135 ms\n...\n</code></pre>\n\n<p>Your <code>delegate</code> class is always faster by 1 seconds, even in this naive benchmark.</p>\n\n<hr>\n\n<p><strong>Actual review:</strong></p>\n\n<p>I tested changing all <code>std::function&lt;R(A...)&gt;</code> to your <code>delegate&lt;R(A...)&gt;</code> in <em>all of my projects</em>.</p>\n\n<p>After making a small adjustment to the <code>delegate</code> code, <strong>everything works</strong> as expected!</p>\n\n<p>In some of my code I used to do this:</p>\n\n<pre><code>void a(std::function&lt;void()&gt; mMaybe = nullptr)\n{\n // do something\n if(mMaybe != nullptr) mMaybe();\n}\n</code></pre>\n\n<p>This code broke when using <code>delegate</code> instead of <code>std::function</code>. I fixed it by adding these lines to your <code>delegate</code> class:</p>\n\n<pre><code>delegate(std::nullptr_t) : object_ptr_{nullptr}, stub_ptr_{nullptr} { }\nbool operator==(std::nullptr_t) const noexcept { return object_ptr_ == nullptr; }\nbool operator!=(std::nullptr_t) const noexcept { return object_ptr_ != nullptr; }\n</code></pre>\n\n<p>Now the above code compiles and works correctly. With this small adjustment, the <code>delegate</code> class is a <strong>probably faster drop-in replacement</strong> for <code>std::function</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T12:47:34.807", "Id": "48910", "Score": "0", "body": "I'll add your code to the `delegate` class, thanks for the contribution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T23:38:47.977", "Id": "49091", "Score": "0", "body": "Try the `staticdelegate.hpp` from the repository as well, please." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T00:10:00.923", "Id": "49095", "Score": "0", "body": "@user1095108: http://pastebin.com/YwEaLhhF" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T00:11:48.120", "Id": "49097", "Score": "0", "body": "Note: *rawfunc* is `delegate<int(int&, int)> t1 = &rawFunc;`, with `rawFunc` being a simple global function. \n\nNote 2: if you manage to optimize *rawfunc*, *mem rawfunc* can be optimized using the same concepts behind Don's fastdelegate (binding it as if it was a global function)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T00:14:00.317", "Id": "49098", "Score": "0", "body": "Note 3: [I greatly cleaned up my Don's fastdelegate implementation](https://gist.github.com/SuperV1234/6455139), if you want to see how it handles raw global functions" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T00:38:00.190", "Id": "49099", "Score": "0", "body": "`g++` gives greatly different results, with same compiler options: http://pastebin.com/UxDfd0rE" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T11:03:20.827", "Id": "49123", "Score": "0", "body": "@user1095108: I'll try in a while and report :) consider making it automatically use `from<rawFunc>()` when constructing like this, though: `delegate<int(int&, int)> = &rawFunc;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T11:06:08.373", "Id": "49124", "Score": "0", "body": "Can't. See that `rawFunc` is a template parameter? It is a compile-time thing. Basically, it is a faster way to achieve the same thing as Don's delegate without `reinterpret_cast`s" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T11:08:22.743", "Id": "49125", "Score": "0", "body": "staticdelegate is making use of shady tricks, add `static_new` to Don's delegate and revel in the speed. `static_new` is a fast alternative to the `::std::shared_ptr<void>` trick." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T12:13:25.390", "Id": "49128", "Score": "0", "body": "@user1095108: http://pastebin.com/EC7jn3b4 - there may be something wrong with my `g++` installation, but I'm not sure; I think it may just be the optimizer sucking at unrolling the giant loops" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T12:23:19.013", "Id": "49129", "Score": "0", "body": "Also, I implemented your `static_storage` in my `FastFunc` implementation, but no performance gains - strange" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T12:31:07.697", "Id": "49130", "Score": "0", "body": "Ah well, never mind then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T12:35:18.457", "Id": "49132", "Score": "0", "body": "The fact is that I'm benchmarking only the calls (`operator()`) - I guess the bottleneck is somewhere else in my code, not the `operator new`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T15:33:12.517", "Id": "49143", "Score": "0", "body": "Would you mind deleting your 2 answers? We polluted the page quite a bit :) I still think btw, that for calls of raw functions and member functions your are instantiating the delegate incorrectly. You need to do `delegate<..sig..>::from<rawfunc>()`. Note, the pointer to function is a template parameter. Don't put the pointer between ()." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T15:34:12.180", "Id": "49144", "Score": "0", "body": "Also, I've updated the staticdelegate once more. Get it from the repository." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T23:06:58.193", "Id": "49184", "Score": "0", "body": "I found a cool SFINAE trick to save some memory (and an allocation): check if a functor/lambda is trivial (can be constructed like a global function pointer) at compile time. If it is, store it's address in a simple `void*` instead of allocating. http://pastie.org/8304603" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T23:17:40.507", "Id": "49185", "Score": "0", "body": "Actually, there's no need for storage at all in that case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T10:54:33.750", "Id": "49203", "Score": "0", "body": "This is what I am trying to tell you for several days now, Yeah, no storage is needed, you're instantiating the delegate wrongly. You need to pass the pointers as template parameters and as a reward you don't need the ugly `reinterpret_cast`s in the code. Runtime pointers are provided for people who don't care about performance. Anyway I've made slight improvements, as far as handling raw functions is concerned, but probably nothing substantial :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T12:47:00.923", "Id": "49205", "Score": "0", "body": "@user1095108: new benchies http://pastie.org/8305796" } ], "meta_data": { "CommentCount": "19", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T12:40:34.620", "Id": "30767", "ParentId": "14730", "Score": "4" } }, { "body": "<p>Problematic results:</p>\n\n<pre><code>[std::func] 31855 ms\n[ssvu::fastfunc] 123848 ms\n</code></pre>\n\n<p>Benchmark code:</p>\n\n<pre><code>int x{0};\nfor(int xx = 0; xx &lt; 5; ++xx)\n{\n startBenchmark();\n {\n for(int i = 0; i &lt; 1000000000; ++i)\n {\n std::function&lt;int(int)&gt; t2 = t2impl;\n std::function&lt;void(int)&gt; t1 = [&amp;x, &amp;t2](int i){ x = t2(i); };\n t1(i);\n }\n } lo &lt;&lt; lt(\"std::func\") &lt;&lt; endBenchmark() &lt;&lt; endl;\n startBenchmark();\n {\n for(int i = 0; i &lt; 1000000000; ++i)\n {\n FastFunc&lt;int(int)&gt; t2 = t2impl;\n FastFunc&lt;void(int)&gt; t1 = [&amp;x, &amp;t2](int i){ x = t2(i); };\n t1(i);\n }\n } lo &lt;&lt; lt(\"ssvu::fastfunc\") &lt;&lt; endBenchmark() &lt;&lt; endl;\n}\n</code></pre>\n\n<p><code>std::function</code> performed <strong>way</strong> better on this benchmark. Any idea why?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:12:18.600", "Id": "48913", "Score": "0", "body": "It probably has to do something with initialization of functors. `::std::function` supposedly optimizes initialization with small functors. I didn't optimize that use case. Try to move the definition of FastFunc objects outside of the loop, and then simply `std::move` the lambda object into it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:15:53.343", "Id": "48914", "Score": "0", "body": "I did some profiling with valgrind (only for the `delegate` class): it seems the real bottleneck is dynamic memory allocation http://i.imgur.com/k01y9fA.png" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:18:55.957", "Id": "48915", "Score": "0", "body": "Try to just assign in the loop: `t2 = std::move(t2impl); t1 = std::move([&x, &t2](int i){ x = t2(i); };);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:21:11.023", "Id": "48916", "Score": "0", "body": "@user1095108 no dice - results are same to the original benchmark code (`delegate` is a lot slower than `std::function`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:27:55.870", "Id": "48917", "Score": "0", "body": "If this is a frequent use-case in your code, you need to find some other delegate or optimize this code for it (i.e. instead of `new`-ing, you can use a small `char[]` array to store the functor - watch out for alignment issues) or you can try using `Boost.Pool` or some small object allocator. Note that the original delegate didn't support functors (lambda objects) at all, but exploited the possibility of compile-time pointer-to-function and pointer-to-function-member template parameters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:42:45.343", "Id": "48919", "Score": "0", "body": "@user1095108: I tried allocating a `char` buffer and using placement new on it but hit a roadblock: I need to call the allocated `obj_ptr_` destructor before `delete[]`-ing the buffer, but I have no way of knowing what type `obj_ptr_` is. Also, I can't seem to understand how I may circumvent `shared_ptr` reference counting if two `delegate` objects can point to the same function. It would be great if you could show an example on how to do this, because I've been looking for a `C++11`-compliant fast delegate forever, and this one is very promising" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:50:29.717", "Id": "48921", "Score": "0", "body": "You need to define 2 new function templates, say, `copier` and `mover`, similar to the existing `deleter` to move and copy the contained functors in the `char[]` array. Don't forget `alignof` and `std::align`.The more significant question to me is, whether placement `new` into a `char[]` is faster than into the heap? There is no other way to copy the lambda object, that is known to me. It shouldn't be significantly faster/slower. Did you really move the delegate instantiations out of the loop and assigned in the loop?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:59:32.963", "Id": "48923", "Score": "0", "body": "*\"Did you move delegate instantiations out of the loop...\"*: yes, but `std::function` is still a lot faster, even if I keep its initialization in the other loop. I've done some research and there is another way to store functors/memfn pointers: [Don Clugston's fastest possible delegates](http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible). There is a [C++11 implementation here](http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible?msg=4489700#xx4489700xx) but I couldn't get it to work properly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:02:07.693", "Id": "48924", "Score": "0", "body": "The idea, as far as I understand, is to use `reinterpret_cast` and some other tricks to *convert* any kind of function pointer into a global-like function pointer. [Someone managed to implement lambda expressions into it easily](http://www.codeproject.com/Messages/4609198/Support-for-Lambda-Expressions.aspx) but I don't understand the code well enough to attempt an implementation of its cast magic into your `delegate` class - I'm trying to, though. Maybe it could give you some ideas on how to tackle this problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:10:32.380", "Id": "48925", "Score": "0", "body": "Yes, write your own delegate, by all means :) I don't understand the other delegate too well, I wanted easily inline-able, easily understandable code in the current implementation. Without `reinterpret_cast`s." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:19:14.463", "Id": "48928", "Score": "0", "body": "Another improvement could be `FastFunc<int(int)> t2 = FastFunc<int(int)>::from<t2impl>();` if `t2impl` is a function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T17:45:16.473", "Id": "48956", "Score": "0", "body": "Please check https://code.google.com/p/cpppractice/ for `arraydelegate`, but it only works with `gcc`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T09:56:40.507", "Id": "49024", "Score": "0", "body": "@user1095108, thanks for the link. I use clang, and I was trying to get it to work, but `max_align_t` is probably not available on clang. Is there any suitable alternative?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T10:05:46.330", "Id": "49025", "Score": "0", "body": "for now, put in 8 instead of max_align_t. It doesn't work fast anyway. Next clang version will probably fix this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T10:23:22.597", "Id": "49026", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/10467/discussion-between-vittorio-romeo-and-user1095108)" } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:04:02.837", "Id": "30768", "ParentId": "14730", "Score": "0" } } ]
{ "AcceptedAnswerId": "14795", "CommentCount": "16", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T07:02:36.217", "Id": "14730", "Score": "29", "Tags": [ "c++", "c++11" ], "Title": "Impossibly fast delegate in C++11" }
14730
<p>What needs to be corrected, added, or subtracted here?</p> <pre><code>class mutexLocker { private: /* Declaration of a Mutex variable `mutexA`. */ pthread_mutex_t &amp;mutexA; /* `mutexStatus` holds the return value of the function`pthread_mutex_lock `. This value has to be returned to the callee so we need to preserve it in a class variable. */ int mutexStatus; public: /* Constructor attempts to lock the desired mutex variable. */ mutexLocker (pthread_mutex_t argMutexVariable) : mutexA (argMutexVariable) { /* Return value is needed in order to know whether the mutex has been successfully locked or not. */ int mutexStatus = pthread_mutex_lock (&amp;argMutexVariable); } /* Since the constructor can't return anything, we need to have a separate function which returns the status of the lock. */ int getMutexLockStatus () { return mutexStatus; } /* We may need this Mutex variable as an argument for `pthread_cond_wait()`*/ pthread_mutex_t getLockedMutex () { if (mutexStatus &gt;= 0) return mutexA; } /* The destructor will get called automatically whereever the callee's scope ends, and will get the mutex unlocked. */ ~mutexLocker () { if (mutexStatus &gt;= 0) pthread_mutex_unlock (&amp;mutexA); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T01:56:18.250", "Id": "24002", "Score": "0", "body": "What's wrong with the standard threading library? Or, if you don't have it, boost thread?" } ]
[ { "body": "<p>If you are keeping a reference to an object you should pass that object to the constructor as a reference:</p>\n\n<pre><code>mutexLocker (pthread_mutex_t argMutexVariable) \n // ^^^ Missing reference.\n</code></pre>\n\n<p>You return the state of the lock operation:</p>\n\n<pre><code>int getMutexLockStatus ()\n</code></pre>\n\n<p>But if the mutext failed to lock what are you going to do.<br>\nIf the mutext fails to lock there is probably something fundamentally wrong so you should probably stop the current action by throwing an exception.</p>\n\n<p>You can't conditionally return a value.<br>\nYou must always return something from a function that expects to return value.</p>\n\n<pre><code>pthread_mutex_t getLockedMutex ()\n{\n if (mutexStatus &gt;= 0)\n return mutexA;\n\n\n // What happens if the code gets here?\n // Letting a function return without an explicit return (in a non void method)\n // is undefined behavior.\n}\n</code></pre>\n\n<p>Also I see no point in testing the status.<br>\nIf the lock failed to lock you should have exited the code much earlier than this. If the lock fails throw an exception.</p>\n\n<p>Your test is also incorrect (here and the destructor)</p>\n\n<pre><code>if (mutexStatus &gt;= 0) \n</code></pre>\n\n<p>If the mutex did lock then it returned <code>0</code> and thus the <code>mutexStatus</code> is zero.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T20:19:42.380", "Id": "14758", "ParentId": "14731", "Score": "3" } }, { "body": "<p>Think about it this way: The sole purpose of the locker class is to provide a scoped variable that ex&shy;pres&shy;ses the notion of the associated mutex being locked. The mere existence of a locker variable is sup&shy;pos&shy;ed to guarantee that you are the sole execution inside a critical section.</p>\n\n<p>Thus it makes no sense for your class to have an error state. If you cannot successfully obtain a lock, you should throw an exception, since it is not possible for your object to be constructed if there is an error.</p>\n\n<p>Moreover, you have to take the mutex variable <em>by reference</em>.</p>\n\n<p>Putting it all together, the following picture emerges:</p>\n\n<pre><code>struct MutexLocker\n{\n MutexLocker(pthread_mutex_t &amp; m)\n : _m(m)\n {\n if (pthread_mutex_lock(&amp;_m) != 0)\n {\n throw std::logic_error(\"Could not lock mutex\");\n }\n }\n\n ~MutexLocker()\n {\n pthread_mutex_unlock(&amp;m);\n }\n\nprivate:\n pthread_lock_t &amp; _m;\n};\n</code></pre>\n\n<p>If you check the <a href=\"http://linux.die.net/man/3/pthread_mutex_unlock\" rel=\"nofollow\">documentation for <code>pthread_mutex_unlock</code></a>, you will find that our destructor is indeed correct and can never fail.</p>\n\n<hr>\n\n<p>If you do want to have a C++ wrapper around a mutex that allows trivial construction, optional locking and early unlocking, you will need to write a more comprehensive, complex class. I believe <code>std::unique_lock</code> is a standard library template that already possesses such a set of features; you should <a href=\"http://en.cppreference.com/w/cpp/thread/unique_lock\" rel=\"nofollow\">take a look at what it offers</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T16:43:51.877", "Id": "14794", "ParentId": "14731", "Score": "2" } } ]
{ "AcceptedAnswerId": "14758", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T07:41:21.703", "Id": "14731", "Score": "1", "Tags": [ "c++", "multithreading", "pthreads" ], "Title": "Mutex locker class in C++" }
14731
<p>I'm just learning the basics of animating with Javascript and HTML5. I'm trying to create this scrolling logos element for my site, and I'm pretty sure that my code is very inefficient. Can anyone give me any tips on how to do a better job of what I'm trying to do here?</p> <p><a href="http://jsbin.com/anagug/1/edit" rel="nofollow">http://jsbin.com/anagug/1/edit</a></p> <p>Thanks!</p> <p>EDIT: Here is the code:</p> <pre><code> var ctx; var count = 0; var xpos; var ypos; var revealTimer; var img = new Image(); img.src = "http://www.firewalkcreative.com/2012/images/logos_1.png"; function switchImage(){ xpos = count * 150; ypos = 0; count++; ctx.globalAlpha = 0.1; revealTimer = setInterval(revealImage,100); if(count == 5) count = 0; } function revealImage() { ctx.drawImage(img, 0, 0, 840, 90, xpos, count, 840, 90); ctx.drawImage(img, 0, 0, 840, 90, xpos-900, 0, 840, 90); ctx.save(); ctx.globalAlpha += 0.1; if (ctx.globalAlpha &gt;= 1.0) clearInterval(revealTimer); ctx.restore(); } function init() { ctx = document.getElementById("canvas").getContext("2d"); setInterval(switchImage,3000); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T06:25:29.833", "Id": "23956", "Score": "3", "body": "drawing objects is always going to be expensive. It would be much smoother to draw those elements before the timer function starts, so that you're not expending resources to draw every time the function fires every 5 seconds" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T13:09:16.650", "Id": "24024", "Score": "0", "body": "I don't see any scrolling, only fading. Anyway, it may be because I'm not experienced with it, but I wouldn't use canvas for this." } ]
[ { "body": "<p>Always do a <code>clearInterval()</code> before doing a new <code>setInterval()</code> on the same variable. Doesn't matter if it has been cleared or not.</p>\n\n<p>e.g.</p>\n\n<pre><code>clearInterval(revealImage);\nrevealTimer = setInterval(revealImage,100);\n</code></pre>\n\n<p>You're code has a bug where the <code>revealTimer</code> is being reset before being cleared. </p>\n\n<p>Why do you need to reset it?</p>\n\n<pre><code>function init() { \n ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n setInterval(switchImage,3000);\n setInterval(revealImage,100);\n}\n</code></pre>\n\n<p>Should work just as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T06:05:05.543", "Id": "35806", "ParentId": "14734", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T05:44:50.843", "Id": "14734", "Score": "3", "Tags": [ "javascript", "html5" ], "Title": "How to optimize this HTML5 animation?" }
14734
<p>I'm making requests to <a href="http://www.parse.com" rel="nofollow">Parse.com</a> to 3 different objects that are needed to render a View. I'd like to know what's the general/best approach in cases like these in which there are multiple requests before actually handling the data.</p> <p><strong>Code:</strong></p> <pre><code> var Parse = require('parse-api').Parse; var parse = new Parse(); exports.single = function() { parse.find('Class_1',params1,function(error,response1){ parse.find('Class_2',params2,function(error, response2){ parse.find('Class_3',params3,function(error3, response3){ // handle responses.... // render view.... }) }) }) } </code></pre> <p>Thanks!</p>
[]
[ { "body": "<p>Use <a href=\"https://github.com/creationix/step/\" rel=\"nofollow\">Step.js</a> or <a href=\"https://github.com/caolan/async/\" rel=\"nofollow\">async.js</a> to make this look cleaner. Step.js is simpler, but async.js gives you more flexibility. </p>\n\n<p>Also, your function single needs to have a callback, and cannot return values since the functions it's invoking are not returning values.</p>\n\n<p>Additionally, generally the data retrieval methods should be separate from the rendering methods.</p>\n\n<p>With Step.js, this could look like:</p>\n\n<pre><code> var Parse = require('parse-api').Parse,\n Step = require('step');\n var parse = new Parse();\nexports.getAndRenderData = function(res, params1, params2, params3){\n getData(params1, params2, params3, function(err, data){\n if(err)\n throw err:\n else {\n res.render('viewname', data);\n }\n });\n}\n\nvar getData = function(params1, params2, params3, callack) {\n var data = {}; \n Step()(\n function getClass1(){\n parse.find('Class_1',params1, this);\n },\n function getClass2(err, class1data){\n if (err) throw err;\n data.class1 = class1data;\n parse.find('Class_2',params2, this);\n },\n function getClass3(err, class2data){\n if (err) throw err;\n data.class2 = class2data;\n parse.find('Class_3',params3, this);\n },\n function callbackWithAll(err, class3data){\n if (err) callback(err); \n else {\n data.class3 = class3data;\n callback(null, data);\n }\n }\n );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T12:47:53.443", "Id": "23961", "Score": "0", "body": "`single` is not returning anything, it just renders the view. I'll look into Steps.js. Btw, What's the benefit of doing this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T17:42:22.087", "Id": "23988", "Score": "0", "body": "If you have a lot of nested callbacks your code can become unwieldy..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T11:55:05.090", "Id": "14737", "ParentId": "14736", "Score": "1" } } ]
{ "AcceptedAnswerId": "14737", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T10:28:31.370", "Id": "14736", "Score": "1", "Tags": [ "javascript", "node.js", "asynchronous" ], "Title": "Node.js Nested Callbacks, multiple requests" }
14736
<p>I have many <code>&lt;spans&gt;</code>s which need to group to change opacity after hover. All of them need to have unique IDs. Is there a way to combine all these hover functions to one function?</p> <p><strong>jQuery</strong></p> <pre><code>//09 $('#c_09_241a, #c_09_241b, #c_09_241c, #c_09_241d').hover( function() { $('#c_09_241a, #c_09_241b, #c_09_241c, #c_09_241d').stop(true, true).css('opacity','1'); }, function() { $('#c_09_241a, #c_09_241b, #c_09_241c, #c_09_241d').stop(true, true).css('opacity','0'); }); $('#c_09_242a, #c_09_242b').hover( function() { $('#c_09_242a, #c_09_242b').stop(true, true).css('opacity','1'); }, function() { $('#c_09_242a, #c_09_242b').stop(true, true).css('opacity','0'); }); $('#c_09_245a, #c_09_245b').hover( function() { $('#c_09_245a, #c_09_245b').stop(true, true).css('opacity','1'); }, function() { $('#c_09_245a, #c_09_245b').stop(true, true).css('opacity','0'); }); $('#c_09_246a, #c_09_246b').hover( function() { $('#c_09_246a, #c_09_246b').stop(true, true).css('opacity','1'); }, function() { $('#c_09_246a, #c_09_246b').stop(true, true).css('opacity','0'); }); //08 $('#c_08_235a, #c_08_235b, #c_08_235c, #c_08_235d').hover( function() { $('#c_08_235a, #c_08_235b, #c_08_235c, #c_08_235d').stop(true, true).css('opacity','1'); }, function() { $('#c_08_235a, #c_08_235b, #c_08_235c, #c_08_235d').stop(true, true).css('opacity','0'); }); $('#c_08_236a, #c_08_236b').hover( function() { $('#c_08_236a, #c_08_236b').stop(true, true).css('opacity','1'); }, function() { $('#c_08_236a, #c_08_236b').stop(true, true).css('opacity','0'); }); $('#c_08_239a, #c_08_239b').hover( function() { $('#c_08_239a, #c_08_239b').stop(true, true).css('opacity','1'); }, function() { $('#c_08_239a, #c_08_239b').stop(true, true).css('opacity','0'); }); $('#c_08_240a, #c_08_240b').hover( function() { $('#c_08_240a, #c_08_240b').stop(true, true).css('opacity','1'); }, function() { $('#c_08_240a, #c_08_240b').stop(true, true).css('opacity','0'); }); //07 $('#c_07_227a, #c_07_227b').hover( function() { $('#c_07_227a, #c_07_227b').stop(true, true).css('opacity','1'); }, function() { $('#c_07_227a, #c_07_227b').stop(true, true).css('opacity','0'); }); $('#c_07_228a, #c_07_228b, #c_07_228c').hover( function() { $('#c_07_228a, #c_07_228b, #c_07_228c').stop(true, true).css('opacity','1'); }, function() { $('#c_07_228a, #c_07_228b, #c_07_228c').stop(true, true).css('opacity','0'); }); $('#c_07_007a, #c_07_007b').hover( function() { $('#c_07_007a, #c_07_007b').stop(true, true).css('opacity','1'); }, function() { $('#c_07_007a, #c_07_007b').stop(true, true).css('opacity','0'); }); $('#c_07_008a, #c_07_008b').hover( function() { $('#c_07_008a, #c_07_008b').stop(true, true).css('opacity','1'); }, function() { $('#c_07_008a, #c_07_008b').stop(true, true).css('opacity','0'); }); </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div id="rzuty09p" class="rzuty"&gt; &lt;span id="c_09_241a" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_09_241b" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_09_241c" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_09_241d" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_09_242a" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_09_242b" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_09_243" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_09_244" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_09_245a" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_09_245b" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_09_246a" class="mieszkanie nie" title=""&gt;&lt;/span&gt; &lt;span id="c_09_246b" class="mieszkanie nie" title=""&gt;&lt;/span&gt; &lt;/div&gt; &lt;div id="rzuty08p" class="rzuty"&gt; &lt;span id="c_08_235a" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_08_235b" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_08_235c" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_08_235d" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_08_236a" class="mieszkanie nie" title=""&gt;&lt;/span&gt; &lt;span id="c_08_236b" class="mieszkanie nie" title=""&gt;&lt;/span&gt; &lt;span id="c_08_237" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_08_238" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_08_239a" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_08_239b" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_08_240a" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_08_240b" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;/div&gt; &lt;div id="rzuty07p" class="rzuty"&gt; &lt;span id="c_07_226" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_07_227a" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_07_227b" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_07_228a" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_07_228b" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_07_228c" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_07_229" class="mieszkanie nie" title=""&gt;&lt;/span&gt; &lt;span id="c_07_005" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_07_006" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_07_007a" class="mieszkanie nie" title=""&gt;&lt;/span&gt; &lt;span id="c_07_007b" class="mieszkanie nie" title=""&gt;&lt;/span&gt; &lt;span id="c_07_008a" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;span id="c_07_008b" class="mieszkanie" title=""&gt;&lt;/span&gt; &lt;/div&gt; </code></pre>
[]
[ { "body": "<pre><code>var groups = [\n '09_241', '09_242', '09_245', '09_246',\n '08_235', '08_236', '08_239', '08_240',\n '07_227', '07_228', '07_007', '07_008'\n];\n\n$.each(groups, function(i, group) {\n\n var $group = $('[id^=c_' + group + ']');\n\n $group.hover(function() {\n $group.stop(true, true).css('opacity', '1');\n }, function() {\n $group.stop(true, true).css('opacity', '0');\n });\n});\n</code></pre>\n\n<p>Here's the fiddle: <a href=\"http://jsfiddle.net/W8GA3/\" rel=\"nofollow\">http://jsfiddle.net/W8GA3/</a></p>\n\n<p>This is similar to @Matt's solution, with the following key differences:</p>\n\n<ol>\n<li><strong>Sane Selectors</strong> - There's no need to add all those selectors by hand. Simply use an <a href=\"http://api.jquery.com/attribute-starts-with-selector/\" rel=\"nofollow\">attribute selector</a> to select all elements that start with a given string.</li>\n<li><strong>Selector caching</strong> - If there's one thing you can do to your code to keep it fast, it's <a href=\"http://ejohn.org/blog/learning-from-twitter/\" rel=\"nofollow\">selector caching</a>.</li>\n<li><strong>$.each</strong> - We're using <a href=\"http://api.jquery.com/jQuery.each/\" rel=\"nofollow\">jQuery's <code>each</code> helper</a> to loop through the array, since it also supports older browsers (<code>forEach</code> is not supported in IE &lt; 9).</li>\n</ol>\n\n<hr>\n\n<p>If you want to, you could even build that original <code>groups</code> array dynamically, which will make this <em>much</em> easier to maintain:</p>\n\n<pre><code>var groups = [];\n\n$('[id^=c_]').each(function() {\n // Extract group number from ID\n var group = this.id.substring(2, 8);\n // If the ID is not in the groups array, add it\n ~$.inArray( group, groups ) || groups.push( group );\n});\n</code></pre>\n\n<p>Here's the fiddle: <a href=\"http://jsfiddle.net/W8GA3/1/\" rel=\"nofollow\">http://jsfiddle.net/W8GA3/1/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T22:04:09.943", "Id": "23995", "Score": "0", "body": "this is super cool, new level for me, thx a lot" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T22:38:44.867", "Id": "23996", "Score": "0", "body": "@gidzior - Glad it helped you. You might have to modify some bits of the code depending on your naming conventions. `$('[id^=c_]')` and `this.id.substring(2, 8)` make a lot of assumptions, and I hope I wasn't too wrong..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T15:23:25.153", "Id": "14747", "ParentId": "14738", "Score": "3" } } ]
{ "AcceptedAnswerId": "14747", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T12:32:22.357", "Id": "14738", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Combining hover functions" }
14738
<pre><code>function check_itv(key) { if (key.length){ if(key=="left"){ left_itv = setInterval(left,100); check_left= false; check_right=true; check_up=true; check_down=true; clearInterval(right_itv); clearInterval(down_itv); clearInterval(up_itv); } if(key=="right"){ right_itv = setInterval(right,100); check_left= true; check_right=false; check_up=true; check_down=true; clearInterval(left_itv); clearInterval(down_itv); clearInterval(up_itv); } if(key=="up"){ up_itv = setInterval(up,100); check_left= true; check_right=true; check_up=false; check_down=true; clearInterval(left_itv); clearInterval(right_itv); clearInterval(down_itv); } if(key=="down"){ down_itv = setInterval(down,100); check_left= true; check_right=true; check_up=true; check_down=false; clearInterval(left_itv); clearInterval(right_itv); clearInterval(up_itv); } } } check_left = true; check_right = true; check_up = true; check_down = true; left_itv = ""; right_itv = ""; up_itv = ""; down_itv = ""; </code></pre> <p>Try to do shorter and better, Any idea ?</p> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T13:07:31.173", "Id": "23966", "Score": "0", "body": "http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T13:10:06.413", "Id": "23967", "Score": "2", "body": "Don't have all of these intervals... have one, and set a variable for the direction." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T13:28:06.103", "Id": "23968", "Score": "0", "body": "i know about global & local , thanks @rlemon" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T14:33:08.167", "Id": "23973", "Score": "0", "body": "@l2aelba What do you mean with \"better\"? (Faster? Easier to maintain? More compliant with standards? Working in <old browser>?) **What are you trying to accomplish?** Why are you not using var: `var check_left = true;`? Why do you have variables and methods in multiples of 4 and not a single variable for the direction? Etc." } ]
[ { "body": "<p>Without changing too much, here are some tips on improving your code.</p>\n<p>Assumptions:</p>\n<ul>\n<li>You're working in modern web browser.</li>\n<li>left, up, down, right are defined else where.</li>\n</ul>\n<h1>1)</h1>\n<p>Define all the variables at the top. I'm not sure where the fucntions left, up, down, right are.</p>\n<h1>2)</h1>\n<p>Use a switch instead of multiple if else.</p>\n<h1>3)</h1>\n<p>Perform an operation to collection if multiple elements share the same functionality. Refer to <code>resetValues()</code></p>\n<h1>4)</h1>\n<p>Try to make all the if conditions as small as possible. Refer to <code>!key.length</code></p>\n<p>Here's what I came up with.</p>\n<pre><code>Array.prototype.forEach = Array.prototype.forEach || function(fn, scope) {\n for(var i = 0, len = this.length; i &lt; len; ++i) {\n fn.call(scope || this, this[i], i, this);\n }\n};\n\nvar self = this,\n check_left, check_right, check_up, check_down,\n left_itv, right_itv, up_itv, down_itv;\n \nvar resetValues = function(){\n [&quot;left_itv&quot;, &quot;right_itv&quot;, &quot;up_itv&quot;, &quot;down_itv&quot;].forEach(function(el){\n clearInterval( self[el] );\n });\n [&quot;check_left&quot;, &quot;check_right&quot;, &quot;check_up&quot;, &quot;check_down&quot;].forEach(function(el){\n self[el] = true;\n });\n};\n\nresetValues();\n\nfunction check_itv(key) {\n if (!key.length) {\n return;\n }\n resetValues();\n switch( key ){\n case &quot;left&quot;:\n left_itv = setInterval(left, 100);\n check_left = false;\n break;\n case &quot;right&quot;:\n right_itv = setInterval(right, 100);\n check_right = false;\n break;\n case &quot;up&quot;:\n up_itv = setInterval(up, 100);\n check_up = false;\n break;\n case &quot;down&quot;:\n down_itv = setInterval(down, 100);\n check_down = false;\n }\n}\n</code></pre>\n<p>Alternatively, you could swap the global variables inside a singleton(namespace) that has a reset functions. But that add a bit of complexity.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-07T08:27:39.407", "Id": "24989", "Score": "0", "body": "Nice, but use have to use :\nvar check_left = true;\nvar check_right = true;\nvar check_up = true;\nvar check_down = true;\n\nso thats work ! :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-07T17:52:13.137", "Id": "25011", "Score": "1", "body": "@l2aelba Updated the code, so that `resetValues()` set the check direction values when the script loads. Thanks for the update." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T18:37:25.107", "Id": "15332", "ParentId": "14739", "Score": "1" } } ]
{ "AcceptedAnswerId": "15332", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T12:39:43.367", "Id": "14739", "Score": "0", "Tags": [ "javascript" ], "Title": "Better jQuery function argument with if-statement?" }
14739
<p>This is one idea of implementation:</p> <pre><code> Array.prototype.unique = function () { unique_array = []; for (var i = 0, l = this.length; i &lt; l; i++) { if(unique_array.indexOf(this[i]) == -1){ unique_array.push(this[i]); } } return unique_array; } </code></pre> <p>This version uses Object.keys which is a ECMAScript 5 only feature, as you can see on this website <a href="http://kangax.github.com/es5-compat-table/">http://kangax.github.com/es5-compat-table/</a></p> <pre><code>Array.prototype.unique_e5 = function () { unique_object = {}; for (var i = 0, l = this.length; i &lt; l; i++) { unique_object[this[i]] = 1; } return Object.keys(unique_object); } </code></pre> <p>And this is how is done in prototype.js <a href="https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/array.js">https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/array.js</a></p> <pre><code> /** * Array#uniq([sorted = false]) -&gt; Array * - sorted (Boolean): Whether the array has already been sorted. If `true`, * a less-costly algorithm will be used. * * Produces a duplicate-free version of an array. If no duplicates are * found, the original array is returned. * * On large arrays when `sorted` is `false`, this method has a potentially * large performance cost. * * ##### Examples * * [1, 3, 2, 1].uniq(); * // -&gt; [1, 2, 3] * * ['A', 'a'].uniq(); * // -&gt; ['A', 'a'] (because String comparison is case-sensitive) **/ function uniq(sorted) { return this.inject([], function(array, value, index) { if (0 == index || (sorted ? array.last() != value : !array.include(value))) array.push(value); return array; }); } </code></pre> <p>Also not that the prototype version uses the Prototype <strong>enumerable method include</strong>, which is:</p> <pre><code> /** * Enumerable#include(object) -&gt; Boolean * - object (?): The object to look for. * * Determines whether a given object is in the enumerable or not, * based on the `==` comparison operator (equality with implicit type * conversion). * * ##### Examples * * $R(1, 15).include(10); * // -&gt; true * * ['hello', 'world'].include('HELLO'); * // -&gt; false ('hello' != 'HELLO') * * [1, 2, '3', '4', '5'].include(3); * // -&gt; true ('3' == 3) **/ function include(object) { if (Object.isFunction(this.indexOf)) if (this.indexOf(object) != -1) return true; var found = false; this.each(function(value) { if (value == object) { found = true; throw $break; } }); return found; } </code></pre> <p>Is there a better way to do it? faster or "better" cross browser compatible?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T21:05:45.223", "Id": "25200", "Score": "1", "body": "I'm not entirely sure, but I think you're asking a similar question to mine, [on SO](http://stackoverflow.com/questions/12041837/javascript-unique-method-for-array-prototype). I was trying to get people to close-vote it, but as luck would have it, it hasn't been closed yet. It's not that good of a fit for SO, and I have my answer and a couple of ppl suggested it to be moved to this site, but I haven't gotten round to that either." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T09:29:46.863", "Id": "25280", "Score": "0", "body": "The issue with using an object is that you won't be able to recognize \"__proto__\". (ES6 Map solves this issue.) But it's the best algorithm in term of big-o cost so it could be interesting if you're going to have laaaarge arrays." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T09:52:54.400", "Id": "25644", "Score": "0", "body": "(I meant `__proto__`.)" } ]
[ { "body": "<p>For me, I'd always avoid methods that require lots of includes to things get working - and in my mind, the more code used.. the slower things will be <em>(unless some form of caching is used)</em>. Which is why I would opt for a simple JavaScript solution. Your idea will work, but I think this one is faster:</p>\n\n<pre><code>Array.prototype.unique = function () {\n var a = this, b = [], c, i = a.length;\n again: while ( i-- ) {\n c = a[i];\n k = i; while( k-- ){ if (a[k] == c){ continue again; } }\n b.unshift( a[i] );\n }\n return b;\n}\n</code></pre>\n\n<p>There are probably other improvements that can be made, for example it might be faster to find a way to use .push() rather than .unshift().</p>\n\n<p>I haven't tested the above excessively, but it seems to work in all my tests so far. The reason why it gets a speed increase is because it reduces the area it is checking each time; it is also using subtle other speed increases like a decrementing while loop <em>(means there are less conditional statements to check on each iteration)</em>, and creating shortcut vars that cut down access time.</p>\n\n<p>As proof here is a jsPerf... albeit only tested on my set-up so far ;)</p>\n\n<p><a href=\"http://jsperf.com/compare-array-unique-versions\" rel=\"nofollow\">http://jsperf.com/compare-array-unique-versions</a></p>\n\n<p><strong>side note:</strong> -- the downside to my method is that it will only include the last found occurance of a duplicate <em>(not the first as your's will)</em>. So if that ordering is important to you, then you'll have to refactor the code.</p>\n\n<p><strong>revision:</strong> -- after a few jsPerfs it seems clear that the <code>while(i--)</code> no longer holds a speed difference <em>(at least not for FireFox 16 Mac OSX)</em>. Whilst on Chrome Mac OSX <code>i--;</code> seems slower than <code>i++;</code></p>\n\n<p><a href=\"http://jsperf.com/compare-a-dec-while-against-a-for-loop\" rel=\"nofollow\">http://jsperf.com/compare-a-dec-while-against-a-for-loop</a></p>\n\n<p>So taking in to account BillyBarry's comments the improved version should be:</p>\n\n<pre><code>Array.prototype.unique8 = function () {\n var a = this, b = [], c, i, l = a.length, j, k = 0;\n again: for ( i = 0; i &lt; l; i++ ) {\n c = a[i];\n for ( j = 0; j &lt; k; j++ ) { if (b[j] === c){ continue again; } }\n b[k++] = c;\n }\n return b;\n}\n</code></pre>\n\n<p>Working from <code>b</code>, rather than <code>a</code> improves things quite a lot. Plus using <code>k++;</code> rather than <code>.length</code> for the internal loop makes quite a bit of difference for FireFox (Mac OSX) but has no affect on Chrome.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T18:02:13.373", "Id": "25231", "Score": "1", "body": "It would be slightly faster to use `b.push()` than unshift, but it will be significantly faster to change the inner loop to loop over `b` instead of `a` if you know that it has many repetitions. see: http://jsperf.com/compare-array-unique-versions/2" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T00:03:04.700", "Id": "25271", "Score": "0", "body": "+1 Yep, I was pretty certain .push() would be better - and from looking at your jsPerf I'm surprised the for loop version seems to win out *(I guess that while trick is no longer true in recent interpreters - need to refresh my assumptions ;)*. Good point about interating over b instead - I was trying to cut down on variable usage and length checks but it seems these don't impact so much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T00:17:24.217", "Id": "25272", "Score": "1", "body": "Ah, actually, have just added another revision not using .length *(keeping track of the length by incrementing a var instead)* and that made quite a bit of difference http://jsperf.com/compare-array-unique-versions/4" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T13:26:02.690", "Id": "15537", "ParentId": "14741", "Score": "2" } }, { "body": "<p>Here's my version, however there are three major downsides.</p>\n<ul>\n<li>Requires more memory.</li>\n<li>Only works with primitive datatypes or objects with a string method that returns unique values. In other words, this doesn't work with objects or object literals.</li>\n<li>Harder to read and maintain</li>\n</ul>\n<h2>Code:</h2>\n<pre><code>Array.prototype.getUnique = function () {\n var arr = this;\n var newArr = [],\n i = 0,\n j = 0,\n obj = {},\n len = arr.length;\n while (len--) {\n if (!obj[arr[i]]) {\n obj[arr[i]] = 1;\n newArr[j] = arr[i];\n j++;\n }\n i++;\n }\n return newArr;\n};\n</code></pre>\n<p>Demo here:\n<a href=\"http://jsperf.com/compare-array-unique-versions/3\" rel=\"nofollow noreferrer\">http://jsperf.com/compare-array-unique-versions/3</a></p>\n<h2>Update</h2>\n<p>Here's the same code but revised to make it easier to read.</p>\n<pre><code>Array.prototype.getUnique_simple = function () {\n var arr = this, newArr = [], obj = {};\n for(var i = 0, len = arr.length; i &lt; len; i++){\n if (obj[arr[i]]) {\n continue;\n }\n obj[arr[i]] = 1;\n newArr.push(arr[i]);\n }\n return newArr;\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T19:27:28.670", "Id": "15548", "ParentId": "14741", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T12:53:18.210", "Id": "14741", "Score": "10", "Tags": [ "javascript", "optimization" ], "Title": "Optimize/Refactor Javascript Unique Array function" }
14741
<p>I have the following code, which acts like a turntable and plays Sgt. Pepper when you load the page. This works only in Safari (I suppose I can delete the FF parts then), so I'm wondering how I can make the code better. The reason for there being a <code>first</code>, <code>last</code>, and <code>main</code> class on most <code>div</code>'s is because records start out slower, then slow down once they're finished, and this was the only way I could accomplish it (that I knew).</p> <p><strong>HTML:</strong></p> <pre><code>&lt;div class="noise"&gt;&lt;/div&gt; &lt;div class="container"&gt; &lt;div class="cover"&gt;&lt;/div&gt; &lt;div class="content"&gt; &lt;div class="switch"&gt; &lt;div class="toggle"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="arm_container"&gt; &lt;div class="pivot"&gt;&lt;/div&gt; &lt;div class="front_arm"&gt; &lt;div class="tip"&gt;&lt;/div&gt; &lt;div class="thick"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="back_arm"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="rest"&gt;&lt;/div&gt; &lt;div class="center"&gt; &lt;div class="small"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="first top_vinyl vinyl"&gt; &lt;div class="last top_vinyl vinyl"&gt; &lt;div class="main top_vinyl vinyl"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="first bottom_vinyl vinyl"&gt; &lt;div class="last bottom_vinyl vinyl"&gt; &lt;div class="main bottom_vinyl vinyl"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ring_container"&gt; &lt;div class="first ring"&gt; &lt;div class="last ring"&gt; &lt;div class="main ring"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="inside_container"&gt; &lt;div class="first inside"&gt; &lt;label&gt;Sgt. Pepper&lt;/label&gt;&lt;br /&gt;&lt;span&gt;Sgt. Pepper's Lonely Hearts Club Band&lt;br /&gt;Lucy in the Sky with Diamonds&lt;br /&gt;When I'm Sixty- Four&lt;br /&gt;A Day in the Life&lt;/span&gt; &lt;div class="last inside"&gt; &lt;label&gt;Sgt. Pepper&lt;/label&gt;&lt;br /&gt;&lt;span&gt;Sgt. Pepper's Lonely Hearts Club Band&lt;br /&gt;Lucy in the Sky with Diamonds&lt;br /&gt;When I'm Sixty- Four&lt;br /&gt;A Day in the Life&lt;/span&gt; &lt;div class="main inside"&gt; &lt;label&gt;Sgt. Pepper&lt;/label&gt;&lt;br /&gt;&lt;span&gt;Sgt. Pepper's Lonely Hearts Club Band&lt;br /&gt;Lucy in the Sky with Diamonds&lt;br /&gt;When I'm Sixty- Four&lt;br /&gt;A Day in the Life&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;audio class="audio" controls="" onloadeddata="var audioPlayer = this; setTimeout(function() { audioPlayer.play(); }, 11500)"&gt;&gt; &lt;source src="song.mp3" type="audio/mp3" /&gt; &lt;/audio&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS:</strong></p> <pre><code>*{ -webkit-text-size-adjust: none; -moz-text-size-adjust: none; line-height: normal; margin:0; padding:0; } body{ background-color:#222; } div{ -webkit-backface-visibility:hidden; -moz-backface-visibility: hidden; position: absolute; } .audio{ display: none; } /* Animations */ @-webkit-keyframes arm { 0% { -webkit-transform: rotate(0deg); } 2% { -webkit-transform: rotate(18deg); } 99% { -webkit-transform: rotate(38deg); } 100% { -webkit-transform: rotate(0deg); } } @-moz-keyframes arm { 0% { -moz-transform: rotate(0deg); } 2% { -moz-transform: rotate(18deg); } 99% { -moz-transform: rotate(38deg); } 100% { -moz-transform: rotate(0deg); } } @-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } } @-moz-keyframes spin { 0% { -moz-transform: rotate(0deg); } 100% { -moz-transform: rotate(360deg); } } @-webkit-keyframes toggle { 0% { -webkit-transform: translateX(0); } 1% { -webkit-transform: translateX(-10px); background-color:red; } 1.1% { background-color:#1EEC04; } 99%{ -webkit-transform: translateX(-10px); } 100% { background-color:#1EEC04; } } @-moz-keyframes toggle { 0% { -moz-transform: translateX(0); } 1% { -moz-transform: translateX(-10px); background-color:red; } 1.1% { background-color:#1EEC04; } 99%{ -moz-transform: translateX(-10px); } 100% { background-color:#1EEC04; } } /* Container */ .content{ width:258px; height:200px; margin:20px; } .cover{ width:298px; height:238px; z-index: 1000; background: -webkit-linear-gradient( top, rgba(125,126,125,.2) 0%, rgba(14,14,14,.2) 100% ); background: -moz-linear-gradient( top, rgba(125,126,125,.2) 0%, rgba(14,14,14,.2) 100% ); opacity: 1; border:1px solid #181818; box-shadow: 0 5px 0 rgba(0,0,0,.3), 0 0 100px #333; } .container{ width:298px; height:238px; left:50%; margin-left:-149px; top:50%; margin-top:-119px; } .noise{ top:0; bottom:0; right:0; left:0; background-image:url(noise.png); z-index: 10000; } /* Switch */ .switch{ width:20px; height:10px; border-radius: 5px; background-color:#333; margin-top:180px; margin-left:190px; box-shadow:inset 0 0 2px #666; } .toggle{ width:10px; height:10px; border-radius: 5px; background-color:red; margin-left:10px; -webkit-animation-name: toggle; -webkit-animation-duration:123s; -webkit-animation-delay:9s; -webkit-animation-iteration-count:1; -moz-animation-name: toggle; -moz-animation-duration:123s; -moz-animation-delay:9s; -moz-animation-iteration-count:1; box-shadow: inset 0 0 2px #000; } /* Arm */ .arm_container{ width:50px; height:93px; z-index: 2; margin-left:185px; margin-top:40px; -webkit-animation-name: arm; -webkit-animation-duration:125s; -webkit-animation-iteration-count:1; -webkit-animation-delay:10s; -webkit-animation-timing-function: ease-out; -moz-animation-name: arm; -moz-animation-duration:125s; -moz-animation-iteration-count:1; -moz-animation-delay:10s; -moz-animation-timing-function: ease-out; } .front_arm{ width:4px; height:50px; background-color:#999; margin-left:37px; margin-top:47px; z-index: 2; -webkit-transform: rotate(27deg); -moz-transform: rotate(27deg); } .back_arm{ width:4px; height:50px; background-color:#999; margin-left:48px; z-index: 2; } .thick{ background-color:#ccc; width:6px; height:10px; margin-top:34px; margin-left:-1px; } .tip{ border-left:2.5px solid transparent; border-right:2.5px solid transparent; border-top:7px solid #999; width:0px; height:0px; margin-top:49px; margin-left:0px; } .pivot{ background-color:#999; width:10px; height:10px; border-radius: 10px; margin-left:45px; margin-top:-3px; z-index: 2; box-shadow: 0 0 0 6px #111; } .rest{ width:8px; height:10px; background-color:#fff; -webkit-transform: rotate(30deg); -moz-transform: rotate(30deg); margin-left:223px; margin-top:101px; border-radius: 1px; } /* Center */ .center{ width:7px; height: 7px; background-color:#ccc; border-radius: 10px; z-index: 4; margin-top:95px; margin-left:96px; } .small{ width:5px; height: 5px; background-color:#222; border-radius: 2px; z-index: 5; margin-top:1px; margin-left:1px; } /* Vinyl */ .first { -webkit-animation-name: spin; -webkit-animation-duration:3s; -webkit-animation-iteration-count:1; -webkit-animation-timing-function: ease-in; -webkit-animation-delay:10s; -moz-animation-name: spin; -moz-animation-duration:3s; -moz-animation-iteration-count:1; -moz-animation-timing-function: ease-in; -moz-animation-delay:10s; } .last { -webkit-animation-name: spin; -webkit-animation-duration:10s; -webkit-animation-iteration-count:1; -webkit-animation-delay:134s; -webkit-animation-timing-function: ease-out; -moz-animation-name: spin; -moz-animation-duration:10s; -moz-animation-iteration-count:1; -moz-animation-delay:134s; -moz-animation-timing-function: ease-out; } .main { -webkit-animation-name: spin; -webkit-animation-duration:1.1s; -webkit-animation-delay:13s; -webkit-animation-iteration-count:110; -webkit-animation-timing-function:linear; -moz-animation-name: spin; -moz-animation-duration:1.1s; -moz-animation-delay:13s; -moz-animation-iteration-count:110; -moz-animation-timing-function:linear; } .vinyl { border-radius: 50%; width: 200px; height: 200px; box-shadow: 0 0 1px #000; } .top_vinyl { background:-webkit-linear-gradient( left, #111111 50%, #1c1c1c 50% ); background:-moz-linear-gradient( left, #111111 50%, #1c1c1c 50% ); } .bottom_vinyl { background:-webkit-radial-gradient( center, ellipse cover, #000000 0%, #333333 20%, #000000 20%, #333333 40%, #000000 40%, #333333 55%, #000000 55%, #333333 70%, #000000 70%, #333333 100% ); background:-moz-radial-gradient( center, ellipse cover, #000000 0%, #333333 20%, #000000 20%, #333333 40%, #000000 40%, #333333 55%, #000000 55%, #333333 70%, #000000 70%, #333333 100% ); opacity: .3; } /* Rainbow ring */ .ring_container{ margin-top:69px; margin-left:70px; } .ring{ height:61px; background-image:url(ring.png); width: 60px; background-position: center center; background-repeat: no-repeat; border-radius:30px; } /* Inside ring */ .inside_container{ margin-top:115px; margin-left:75px; } .inside{ width:50px; height:50px; background-color:#333; border-radius: 25px; font-size: 5px; color:#fff; font-family: sans-serif; text-align: center; margin-top:-40px; } .inside span{ font-size: 2px; display: block; text-align: left; margin-top:10px; margin-left:8px; } .inside label{ margin-top:10px; display: block; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:40:39.220", "Id": "83190", "Score": "0", "body": "is this even real code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:43:14.160", "Id": "83191", "Score": "4", "body": "So real you could taste it, but you can't, cause it's code." } ]
[ { "body": "<p>One of the first things that you can to do improve the HTML is to remove the <code>&lt;br /&gt;</code> tags, and to replace the <code>&lt;label&gt;</code> tags with <code>&lt;span&gt;</code> tags. Labels in HTML should only be found in forms.</p>\n\n<p>To achieve the same effects that the line break tags gave you, you can use CSS with semantic class names (e.g.: <code>.songTitle</code>).</p>\n\n<p>Additionally, I would avoid duplicate markup to achieve the difference in the record's speed in the beginning and end of the song. Applying the <code>first</code>, <code>last</code>, and <code>main</code> classes to the same mark-up using JavaScript would be more appropriate.</p>\n\n<p>I also am not a fan of the <code>&lt;div&gt;</code>-heavy markup, but if this is something experimental I suppose it is alright for now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-01T00:06:08.527", "Id": "32047", "ParentId": "14748", "Score": "3" } }, { "body": "<p>If you are going to write HTML code, use HTML Tags</p>\n\n<ul>\n<li><code>&lt;p&gt;</code> for paragraphs</li>\n<li><code>&lt;h1&gt;</code> for Main Headers</li>\n<li><code>&lt;h2&gt;</code> for secondary Headers</li>\n<li><code>&lt;h3&gt;</code>-<code>&lt;h6&gt;</code> for other headers</li>\n<li><code>&lt;img&gt;</code> for images</li>\n</ul>\n\n<p>You should really look at using other tags and how they are used. </p>\n\n<p>HTML Tags have a purpose, use them. </p>\n\n<p>Something that I think you could benefit from (and myself as well) is a site called <a href=\"http://diveintohtml5.info/semantics.html\" rel=\"nofollow\">Dive Into HTML 5</a> this is the semantics section, but it looks like it has some really good information, I know that I will be reading it later on sometime.</p>\n\n<p>Your code with the Label should look like this</p>\n\n<pre><code>&lt;h1&gt;Sgt. Pepper&lt;/h1&gt;\n&lt;p&gt;\n Sgt. Pepper's Lonely Hearts Club Band\n &lt;br /&gt;\n Lucy in the Sky with Diamonds\n &lt;br /&gt;\n When I'm Sixty- Four\n &lt;br /&gt;\n A Day in the Life\n&lt;/p&gt;\n</code></pre>\n\n<p>Instead of like this:</p>\n\n<pre><code>&lt;label&gt;Sgt. Pepper&lt;/label&gt;&lt;br /&gt;&lt;span&gt;Sgt. Pepper's Lonely Hearts Club Band&lt;br /&gt;Lucy in the Sky with Diamonds&lt;br /&gt;When I'm Sixty- Four&lt;br /&gt;A Day in the Life&lt;/span&gt;\n</code></pre>\n\n<p>The <code>&lt;h1&gt;</code> tag has an automatic break following it.</p>\n\n<p>If this is a partial list of the songs on the Record you could also us an ordered list like this:</p>\n\n<pre><code>&lt;ol&gt;\n &lt;li&gt;\n Sgt. Pepper's Lonely Hearts Club Band\n &lt;/li&gt;\n &lt;li&gt;\n Lucy in the Sky with Diamonds\n &lt;/li&gt;\n &lt;li&gt;\n When I'm Sixty- Four\n &lt;/li&gt;\n &lt;li&gt;\n A Day in the Life\n &lt;/li&gt; \n&lt;/ol&gt;\n</code></pre>\n\n<p>Each List Item will now have a number in front of it. if you don't want the numbers than use an unordered list (switch the <code>&lt;ol&gt;</code> to a <code>&lt;ul&gt;</code>) and then add a style to of <code>text-decoration:none;</code> (<em>that might not be entirely correct syntax wise.</em>)</p>\n\n<p>I also think that a lot of these <code>&lt;div&gt;</code> tags need to be <code>&lt;img&gt;</code> tags instead.</p>\n\n<hr>\n\n<p>your <code>div</code> tag with the class <code>noise</code> is going to sit on top of everything on this page too , by the way.</p>\n\n<pre><code>.noise{\n top:0;\n bottom:0;\n right:0;\n left:0;\n background-image:url(noise.png);\n z-index: 10000;\n}\n</code></pre>\n\n<p>I didn't see anything with a higher z-index, which means this is the top item. Is that what you want? This style houses an image which means the image will cover everything else.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-02T21:19:58.203", "Id": "85720", "Score": "0", "body": "It would be beneficial if you could provide an example with these changes in use. http://jsfiddle.net/charlescarver/2gjvm/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-02T22:01:25.323", "Id": "85725", "Score": "0", "body": "I will try to get to it this weekend if I remember" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-04T14:06:31.803", "Id": "85896", "Score": "0", "body": "It's not required, but this project was a long time ago and I've more or less forgotten about it. But for the sake of completeness, I'd like to accept an answer, but only if the hypothetical changes work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-04T19:16:08.737", "Id": "85917", "Score": "0", "body": "everything that you do is based on tags, what they tags are shouldn't make any difference. especially if the tags that are suggested are the correct tags to be using in the situation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T13:40:06.100", "Id": "86174", "Score": "4", "body": "@charlie, changing tags isn't that hard to try out yourself. This is a legit review and you can upvote/accept after you tried to change your code. It is not the responsability of the reviewer to change all your code." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:02:45.213", "Id": "47489", "ParentId": "14748", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T15:43:50.820", "Id": "14748", "Score": "2", "Tags": [ "html", "css", "html5", "animation" ], "Title": "CSS3 animations of a turntable" }
14748
<p>I have a central domain assembly which contains various rich domain models. Lots of business logic, etc. To keep this example simple, here's probably the simplest one:</p> <pre><code>public class Location { private int _id; public int ID { get { return _id; } private set { if (value == default(int)) throw new ArgumentNullException("ID"); _id = value; } } private string _name; public string Name { get { return _name; } set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentNullException("Name"); _name = value; } } public string Description { get; set; } private string _address; public string Address { get { return _address; } set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentNullException("Address"); _address = value; GeoCoordinates = IoCContainerFactory.Current.GetInstance&lt;Geocoder&gt;().ConvertAddressToCoordinates(Address); } } public Coordinates GeoCoordinates { get; private set; } private Location() { } public Location(string name, string address) { Name = name; Description = string.Empty; Address = address; } public Location(int id, string name, string description, string address, Coordinates coordinates) { if (coordinates == null) throw new ArgumentNullException("GeoCoordinates"); ID = id; Name = name; Description = description; Address = address; } public class Coordinates { public decimal Latitude { get; private set; } public decimal Longitude { get; private set; } private Coordinates() { } public Coordinates(decimal latitude, decimal longitude) : this() { Latitude = latitude; Longitude = longitude; } public override bool Equals(object obj) { if (obj == null) return false; if (!(obj is Coordinates)) return false; var coord = obj as Coordinates; return ((coord.Latitude == this.Latitude) &amp;&amp; (coord.Longitude == this.Longitude)); } public override string ToString() { return string.Format("Latitude: {0}, Longitude: {1}", Latitude.ToString(), Longitude.ToString()); } } } </code></pre> <p>For a number of reasons, I don't want to use these domain models as my presentation models in my MVC application. At first I was just creating very similar DTOs for the models to use as presentation models. Something like this:</p> <pre><code>public class LocationViewModel { public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } public string Address { get; set; } public decimal Latitude { get; set; } public decimal Longitude { get; set; } } </code></pre> <p>However, that doesn't make sense for every view situation. A <code>Create</code> action, for example, shouldn't have an <code>ID</code> property. A <code>Delete</code> action doesn't need all of that information. And so on.</p> <p>So now I'm ending up with presentation models that are one-to-one with the presentations themselves. Something like this:</p> <pre><code>public class LocationCreateViewModel { public string Name { get; set; } public string Description { get; set; } public string Address { get; set; } } public class LocationDetailsVieWModel { public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } public string Address { get; set; } public decimal Latitude { get; set; } public decimal Longitude { get; set; } } </code></pre> <p>And so on, customized for the views that bind to them. This became further useful as I could use data annotations to make cleaner use of the ASP.NET MVC tooling. Something like this:</p> <pre><code>public class LocationCreateViewModel { [Required] public string Name { get; set; } public string Description { get; set; } [Required] public string Address { get; set; } } </code></pre> <p>These can get more complex, but the point is that I'm keeping them on the presentation models because I don't feel they have a place in the business domain. I think it would be misleading to have a <code>[Required]</code> annotation on a class property if it doesn't <em>actually</em> make it <em>required</em> unless interpreted by a very specific set of tools. And since lots of other things use these domain models, not just this one MVC website, then I want to make sure the logic is really baked in to the models and not loosely applied for an assumed set of tools.</p> <p>A recurring piece of functionality in this setup is to convert between presentation models and domain models. So presentation models which need to convert to domain models have instance methods on them:</p> <pre><code>public Location ToDomainModel(); </code></pre> <p>And presentations models which need to be built <em>from</em> domain models have static methods on them:</p> <pre><code>public static ConstructFromDomainModel(int id); public static ConstructFromDomainModel(Location location); </code></pre> <hr> <p>The original goal in all of this was to separate concerns. A lot. But I wonder if I've taken a wrong turn in that effort. This isn't necessarily an unmanageable amount of code, but I don't want it to <em>become</em> unmanageable. There's sort of a "class explosion" going on as more and more gets added. And the unit tests are increasing at an even faster rate (which will become a question all its own once I sort out this question).</p> <p>Is there a "better" way? Are there known patterns which would be better followed and still maintain the separation of concerns in a tool-agnostic approach?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-06T23:08:47.420", "Id": "24971", "Score": "0", "body": "I wonder if something like [AutoMapper](https://github.com/AutoMapper/AutoMapper) would work for you. It probably wouldn't completely solve the problem though, as it would only remove the need for conversion methods. BTW, very good question - I'm interested to hear what others have to say as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-07T12:06:09.623", "Id": "25000", "Score": "0", "body": "@AlexSchimp: I thought about AutoMapper at one point and may re-visit it. Another thing to note on this implementation is that it frees me to de-couple the `LocationViewModel`s from the `Location` in yet another way. The view models are coupled to the views they populate, and can be highly customized for those views. So a single view model might be a composite of a handful of models for a more complex view. (For example, say a Location-based view also needs some Event data or User data or something else. Rather than send all the models, I make a lighter composite view model.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-19T09:36:01.083", "Id": "88223", "Score": "0", "body": "@David Does you domain model have 1:1 mapping with your data model (DB) ?" } ]
[ { "body": "<p>I was just playing around with this concept today. I have a User class defined in another assembly. Then I created three classes \"based on\" (but not derived from) that User class: CreateUser, EditUser, and DetailsUser. Each contains View-specific DataAnnotations (Required, DataType, etc.).</p>\n\n<pre><code>public class CreateUser\n{\n [Required]\n public String FirstName { get; set; }\n [Required]\n public String LastName { get; set; }\n [Required]\n [DataType(DataType.EmailAddress)]\n public String Email { get; set; }\n [Required]\n [DataType(DataType.Password)]\n public String Password { get; set; }\n [Required]\n [DataType(DataType.Password)]\n public String VerifyPassword { get; set; }\n}\n</code></pre>\n\n<p>CreateUser has no ID, and has an extra property, VerifyPassword. My validation logic ensures that VerifyPassword==Password. There is no ID property, because it's a new User. After validation in my Create action, I can then map it to a User and add it to my data store.</p>\n\n<pre><code>public class EditUser \n{\n [HiddenInput(DisplayValue = false)]\n public int Id { get; set; }\n [Required]\n public String FirstName { get; set; }\n [Required]\n public String LastName { get; set; }\n [Required]\n [DataType(DataType.EmailAddress)]\n public String Email { get; set; }\n}\n</code></pre>\n\n<p>For Edit User, I pull the user from the database, and map it to an EditUser object. EditUser has a read-only and hidden ID, and no Password properties. MVC's model binder prevents anyone from injecting properties on the User object that don't exist on the EditUser object. </p>\n\n<pre><code>public class DetailsUser\n{\n [HiddenInput(DisplayValue = true)]\n public int Id { get; set; }\n public String FirstName { get; set; }\n public String LastName { get; set; }\n public String Email { get; set; }\n public String Password { get { return \"Not Shown\"; } }\n}\n</code></pre>\n\n<p>For DetailsUser, I do something similar, again hiding the Password property. </p>\n\n<p>You are right about the class explosion. However, each class is very tiny and self-contained. The nice thing about keeping all of this in the ViewModels is that I am free to use Html.EditorForModel() in my views. For me, the choice is extra code in my ViewModels, or extra code in my Views. It's up to you where to put it. </p>\n\n<p>It does seem to violate DRY, having multiple User-based classes with duplicate properties. I thought perhaps they could derive from a common class, and maybe even User itself. I'm still thinking on that, and am open to thoughts and suggestions.</p>\n\n<p>As for the mapping, I have been playing around with the Moo project (https://github.com/dclucas/MOO). It has a simple mapper that I find easier to use than AutoMapper. </p>\n\n<pre><code>var editUser= user.MapTo&lt;EditUser&gt;();\n</code></pre>\n\n<p>This creates an EditUser object from an existing User object, provided the property names match.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T19:20:32.963", "Id": "25616", "Score": "0", "body": "It sounds like we're reaching the same conclusion about the DRY violations. Right now my reasoning is that it's doing the same things but for very different reasons, which is a bit of a borderline case. Certain changes would propagate across many objects, but many changes would be isolated to the tiny classes with their tightly-scoped responsibilities. As for deriving from common classes, I have a tendency to be _very_ hesitant to jump to inheritance in general. Inheritance often feels like tight coupling to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T19:26:35.323", "Id": "25617", "Score": "0", "body": "One thing I neglected to mention is that I typically use Entity Framework for my data layer. I haven't figured out how to take the partially-completed EditUser object and tell EF to update only the columns/properties listed. When mapping back to the User object, all of the missing properties end up being null." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-26T17:18:24.973", "Id": "129656", "Score": "0", "body": "Can you please provide an example for the code in the controller say, for the edit action. Do you have to query the database with the User model and then immediately before displaying convert the User model to the EditUser model?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T19:15:38.673", "Id": "15744", "ParentId": "14752", "Score": "11" } }, { "body": "<p>As @Alex Schimp suggested <a href=\"http://automapper.codeplex.com/\" rel=\"nofollow\">AutoMapper</a> is a an excellent tool for this scenario and exactly what it was built for. I use AutoMapper all of the time to translate between domain models and view models and it greatly simplifies the process and eliminates a lot of coding for the translation between the two. It does a great job of handling the mapping, especially if you keep the field names the same between the domain and the view. So in the example of where the view may not need the ID then AutoMapper will figure out that it does not need to map it to the view just because it is not present. The other advantage of this is if your models change you do not have to remember to update your translation code as well. As long as there is a clear mapping that AutoMapper can figure out then the translation layer is automatically handled. There are also methods for more advanced translations in AutoMapper if the default ones are not sufficient. Your approach of using DTO's is excellent and will pay off in the long run for ease of maintenance, extensibility and scalability. Martin Fowler discuses the benefits of the <a href=\"http://martinfowler.com/eaaCatalog/dataTransferObject.html\" rel=\"nofollow\">DTO design pattern</a> in his book <a href=\"http://martinfowler.com/books/eaa.html\" rel=\"nofollow\">Patterns of Enterprise Application Architecture</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T20:12:53.227", "Id": "15746", "ParentId": "14752", "Score": "3" } }, { "body": "<p>I don't believe there is a \"<strong>right way</strong>\" or a \"<strong>wrong way</strong>\" as such (well maybe there is a wrong way :)). I think it all depends on the context of the situation and what is required.</p>\n\n<p>However, I've always been a fan of using ViewModels and DTO's so will suggest that the approach you are doing is a \"<strong><em>accepted</em></strong>\" way. When I first used this approach I had the same kind of problems that you mention in that some views shared data sets and I didn't want to duplicate those properties everywhere. My approach in this instance was to use inheritance. However, I ended up often having 3 levels deep and any changes to objects became difficult after a while.</p>\n\n<p>In retrospect of that I am approaching ViewModel creation slightly differently these days. I've read a few articles that suggest you should just have one big flat ViewModel and duplicate the properties as required. This means the ViewModel is specific to your need and although you may have a slight class explosion and duplication you can be confident when changing one viewModel you will not effect anything else in the project. Also tools such as <strong>AutoMapper</strong> (as suggested by Kevin) help with not having to worry about the mapping between Model and ViewModel anyway.</p>\n\n<p>However I still like the thought of sharing common information so an alternative approach is to break down the properties into sub ViewModels. So in your example above you could take this approach:</p>\n\n<p>Create a bunch of Viewmodels that contain explicit separation of data concerns:</p>\n\n<pre><code>public class UserInformationViewModel\n{\n [Required]\n public String FirstName { get; set; }\n [Required]\n public String LastName { get; set; }\n}\n\npublic class UserContactDetailsViewModel\n{\n [Required]\n [DataType(DataType.EmailAddress)]\n public String Email { get; set; } \n}\n\npublic class UserPasswordViewModel\n{\n [DataType(DataType.Password)]\n public String Password { get; set; }\n [Required]\n [DataType(DataType.Password)]\n public String VerifyPassword { get; set; }\n}\n</code></pre>\n\n<p>Now create using composition any top level view models for the different view requirements of the system:</p>\n\n<pre><code>public class CreateUserViewModel\n{\n private UserInformationViewModel _information;\n\n public UserInformationViewModel Information\n {\n get { return _information ?? (_information = new UserInformationViewModel()); }\n set { _information = information; }\n }\n\n private UserContactDetailsViewModel _contactDetails;\n\n public UserContactDetailsViewModel ContactDetails\n {\n get { return _contactDetails ?? (_contactDetails = new UserContactDetailsViewModel()); }\n set { _contactDetails = information; }\n }\n private UserPasswordViewModel _password;\n\n public UserPasswordViewModel Verification\n {\n get { return _password ?? (_password = new UserPasswordViewModel()); }\n set { _password = information; }\n } \n}\n\npublic class EditUserViewModel\n{\n [HiddenInput(DisplayValue = false)]\n [ReadOnly(true)]\n public int Id { get; set; }\n\n private UserInformationViewModel _information; \n public UserInformationViewModel Information\n {\n get { return _information ?? (_information = new UserInformationViewModel()); }\n set { _information = information; }\n }\n\n private UserContactDetailsViewModel _contactDetails; \n public UserContactDetailsViewModel ContactDetails\n {\n get { return _contactDetails ?? (_contactDetails = new UserContactDetailsViewModel()); }\n set { _contactDetails = information; }\n } \n}\n\n// For details view I would use either inheritence or simply add the Verification attribute onto a new\n// class. Lets go with inheritence for now\npublic class UserDetailsViewModel \n{\n private UserPasswordViewModel _password;\n\n public UserPasswordViewModel Verification\n {\n get { return _password ?? (_password = new UserPasswordViewModel()); }\n set { _password = information; }\n } \n}\n</code></pre>\n\n<p><strong>Mapping model to ViewModel</strong></p>\n\n<p>As Kevin has suggested there are great tools out there already that do this for you. I haven't personally used any of them but I have heard good things about <a href=\"http://automapper.codeplex.com/\">AutoMapper</a>.</p>\n\n<p><strong>Making use of Partials for sub view models</strong></p>\n\n<p>Because we have now separated the different elements into components I would consider creating a different partial view per view model. This way even your views become re-usable and you share common view presentation around.</p>\n\n<p>i.e</p>\n\n<pre><code>UserContactDetailsViewModel =&gt; _UserContactDetails.cshtml\nUserInformationViewModel =&gt; _UserInformation.cshtml\nUserPasswordViewModel =&gt; _UserNewPassword.cshtml\nUserPasswordViewModel =&gt; _UserEditPassword.cshtml\n</code></pre>\n\n<p>Doing this each view requirement would be a case of incorporating the partials in as required.</p>\n\n<p><strong>Pitfalls on view model composition and partials</strong>:\nOn problem with this approach I had was that when using these viewModels within the views the resultant elements created meant that the bindings did not come back on posts.</p>\n\n<p>What was happening was that I would render a partial as such</p>\n\n<pre><code>@Html.Partial(\"_UserInformation\", Model.Information)\n</code></pre>\n\n<p>However that was great until I looked at the resultant html elements created.</p>\n\n<pre><code>&lt;input id = \"Firstname\" name=\"Firstname\" type=\"text\" /&gt; // etc\n</code></pre>\n\n<p>The problem here is that on binding back there will be no Firstname element on our encapsulating viewModel. What the input really should have looked like was</p>\n\n<pre><code>&lt;input id = \"Information_Firstname\" name=\"Information_Firstname\" type=\"text\" /&gt; // etc\n</code></pre>\n\n<p>What I ended up doing was creating an extension method that would handle this for me without worrying about any of this. So I ended up righting code like so to generate the correct element naming.</p>\n\n<pre><code>@Html.Partial(\"_UserInformation\", model =&gt; model.Information)\n</code></pre>\n\n<p>As for how that works, I'll leave you to figure that one out, or I might post it if you go down this route? However what that partial does is ends up printing exactly what you need:</p>\n\n<pre><code>&lt;input id = \"Information_Firstname\" name=\"Information_Firstname\" type=\"text\" /&gt; // etc\n</code></pre>\n\n<p><strong>Summary</strong>\nI like your approach. You are correct in that class explosion might be a problem but I think this potentially is outweighed by the clear separation of concerns in the system. As for TDD, I don't think every class in an application needs testing. For example if you classes are DTO's there's nothing to test, so class explosion might not necessarily be a cause for concern (or a reason to not go down this route).</p>\n\n<p>Well just my two cents. I hope you get some answers and reviews that enable you to produce code that you are happy and proud of. After all, isn't that what we are after :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T03:06:25.030", "Id": "25631", "Score": "1", "body": "+2 if I could. This shows the different way of thinking about viewmodels vs models. Something I am still learning as I go!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T03:59:50.600", "Id": "25632", "Score": "0", "body": "@JamesKhoury cheers James. I'm constantly learning too. One of the reasons I joined this site to get good feedback and different ideas/opinions and better ways of doing things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T12:18:07.210", "Id": "25647", "Score": "0", "body": "You make a clear point on favoring composition over inheritance, which I've found to usually be a good approach. (Which I believe was also in the Gang Of Four book.) I also like the idea of taking that same philosophy to the views much more than is normally prescribed, I'll have to give that a try as well. For TDD, I guess I'm hooked on getting to that 100% coverage, but you're right in that DTOs don't need to be tested directly. I should instead test the functionality that uses them, and if those tests leave parts of the DTOs uncovered then I don't need those parts anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-21T00:41:26.087", "Id": "353932", "Score": "0", "body": "This is resurrecting a very old thread, but I find that a better way of dealing with the components of a view are to create editor templates, then use @@Html.EditorFor or display templates and use @@Html.DisplayFor. Very similar to using partials, but MVC handles the logic when you post. It also handles the logic when there are 1-many relationships/collections" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T20:43:48.303", "Id": "15747", "ParentId": "14752", "Score": "11" } }, { "body": "<p>In a nutshell there are THREE types of model classes to consider:</p>\n<ol>\n<li><p><strong>Data Model classes</strong> - These are classes that are used for reading/writing data to/from storage. These classes almost always match your table schemes exactly, plus some navigation properties. If you use entity framework (you should), you will have DBSets of these classes defined on your DbContext. These classes almost never contain any code.</p>\n</li>\n<li><p><strong>Presentation classes</strong> - These are basically denormalized versions of your data model classes that are used to display or report data. For example you may have an Order data model class that contains a CustomerID and an OrderDate. The Customer name, however, is defined on the Customer data model class. If you want to display a grid that contains Customer Name and Order Date you may want to use a presentation class that is composed of selected properties of both the Order data model class and the Customer data model class. The only code these classes usually contain is a constructor that allows the class to be instantiated from one or data model classes and perhaps a method or two to construct a data model class from the presentation class. Avoid defining business logic code on these classes.</p>\n</li>\n<li><p><strong>ViewModel classes</strong> - These classes are backing classes for views. Think of them as code behind. The term &quot;Model&quot; in the name is a bit misleading because these classes have less to do with your data or presentation model and more to do with providing properties to make your views work correctly. Unlike Data Model classes or Presentation model classes, ViewModel classes often contain code to react to user events.</p>\n<p>ViewModel classes contain properties for helping the user input data. For example, on an order entry screen the ViewModel may contain a property which is a collection of OrderTypes. This collection may be used to populate a dropdown list. The ViewModel may also contain a OrderType property which is used to store the currently selected OrderType. By comparison, the Order presentation class may contain a property of type string that simply displays the name of the OrderType. On the Data Model class the OrderType may be represented by an integer which is a foreign key to the OrderType table. You should avoid defining business logic on your ViewModel classes. Make calls to your business logic layer instead.</p>\n</li>\n</ol>\n<p>For more info on this subject and for a complete article on how to define a repository and business logic layer, please see the article <strong>A service oriented approach to implementing repository pattern with Entity Framework, MVC, and MVVM</strong> on my web site <a href=\"http://www.samwheat.com\" rel=\"noreferrer\">www.samwheat.com</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-21T07:37:48.560", "Id": "266151", "Score": "0", "body": "In some cases, there are also \"domain model\" or \"business model\" classes. They are somewhere between your data and presentation classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-22T22:21:21.667", "Id": "266517", "Score": "0", "body": "@TomPažourek I think the term \"domain model\" is the correct one... it is what I mean when I say data model." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-23T05:00:10.893", "Id": "266535", "Score": "0", "body": "I'm just pointing out that in some cases you have separate models for reading/writing to storage and separate models that you do business logic with. In those cases it could be considered as fourth kind of models. But again, different projects will need different abstractions and it's not always beneficial." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-01T19:36:38.250", "Id": "79273", "ParentId": "14752", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T17:17:10.160", "Id": "14752", "Score": "31", "Tags": [ "c#", "asp.net-mvc-3" ], "Title": "Separating Models and ViewModels" }
14752
<p>This is a slightly specialised A* algorithm, basically it allows you to search to and from disabled nodes. It's for a game and we the entities spawn in houses and go into them. The rest of the search behaves normally, it doesn't traverse any disabled nodes in between the start and end points.</p> <p>NavData is a class which has the collections of nodes and edges in as well as some other things listed below:</p> <p>(also edges and nodes are simple. edges have two integers - connect from node and connected to node. They also have a value for their weight. Nodes have an int index, a vector3 position and an enabled bool)</p> <pre><code>private List&lt;Node&gt; nodes; //just a list of all nodes in the level, unsorted private Dictionary&lt;int, Dictionary&lt;int, Edge&gt;&gt; edges;//edges[fromNode][toNode] private List&lt;List&lt;int&gt;&gt; nodeAdjacencies; //maintains a list of each node's connected nodes which can be used to index into 'nodes' private List&lt;Edge&gt; simpleEdges; //this keeps all the edges in one big list for easy traversal private bool aStarCore( int start, int goal, out List&lt;Edge&gt; shortestPath, out Dictionary&lt;int, Edge&gt; SPT ) { SPT = new Dictionary&lt;int, Edge&gt;(); //[toNode] = Edge NavData ND = NavData.GetSingleton; Vector3 targetCoords = ND.Nodes[goal].Position; // for calculating heuristic shortestPath = new List&lt;Edge&gt;(); SortedList&lt;float, List&lt;int&gt;&gt; openList = new SortedList&lt;float, List&lt;int&gt;&gt;();//lump nodes with same cost together, doesn't matter which one we grab List&lt;int&gt; searchedNodes = new List&lt;int&gt;(); // could definitely make this more efficient (find a better collection for lookup) // push the start node onto the open list openList.Add( Vector3.Distance( ND.Nodes[start].Position, targetCoords ), new List&lt;int&gt;() ); openList[ Vector3.Distance( ND.Nodes[start].Position, targetCoords ) ].Add( start ); int openListCount = 1; searchedNodes.Add(start); // while there are still nodes on the open list while ( openListCount &gt; 0 ) { // look at the next lowest cost node int source = openList[ openList.Keys[0] ][0];//first node of first list if (openList[ openList.Keys[0]].Count == 1) openList.Remove( openList.Keys[0] ); else openList[ openList.Keys[0] ].RemoveAt(0); openListCount--; //Debug.Log( "source: " + source ); // only allow the code to look at enabled nodes, ( unless it's the start // node as I assume we'll want the agents to emerge from occupied tiles ) if ( ND.Nodes[source].Enabled == true || source == start ) { for ( int i = 0; i &lt; ND.NodeAdjacencies[source].Count; i++ ) { //Debug.Log("adjacency count: " + nodeAdjacencies[source].Count); int target = ND.NodeAdjacencies[source][i]; if ( !searchedNodes.Contains( target ) ) { SPT.Add( ND.Edges[source][target].ToNode, ND.Edges[source][target] ); //does the key(cost) already exist? float costToNode = ND.Edges[source][target].Weight + Vector3.Distance(ND.Nodes[target].Position, targetCoords); if ( openList.ContainsKey(costToNode) ) { openList[costToNode].Add(target); } else { openList.Add( costToNode, new List&lt;int&gt;() ); openList[costToNode].Add(target); } searchedNodes.Add( target ); openListCount++; if ( target == goal ) { //calculate shortest path from the SPT int counter = target; while ( counter != start ) { shortestPath.Add(SPT[counter]); counter = SPT[counter].FromNode; } return true; } } } } } shortestPath = null; return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T18:01:13.927", "Id": "23989", "Score": "0", "body": "if it would be helpful I'll happily share the class that instantiates the data structures the search uses." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T18:37:07.970", "Id": "23990", "Score": "0", "body": "`return aStarCore( start, goal, out shortestPath, ref SPT );` I'm assuming that line shouldn't be there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T12:02:57.387", "Id": "24120", "Score": "0", "body": "@BlueRaja-DannyPflughoeft ah yes, sorry that was a copy-paste error!" } ]
[ { "body": "<p>There are a few things you could do here.</p>\n\n<p>A common optimization is to break ties towards smaller h-values. See <a href=\"http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#breaking-ties\" rel=\"nofollow noreferrer\">here</a>. This will cause your pathfinder to try the most direct routes first.</p>\n\n<p>You may also want to look into using a <a href=\"https://gamedev.stackexchange.com/questions/32813/how-does-dwarf-fortress-keep-track-of-so-many-entities-without-losing-performanc/32831#32831\">hierarchical search algorithm</a> if you're running this many different times on the same map, with different start/end points.</p>\n\n<p>Finally, a minor optimization you could do is use an actual PriorityQueue instead of a <code>SortedList&lt;float, List&lt;int&gt;&gt;</code>. If you're going to run this on a system with a crappy garbage collector (XBox 360), make sure to use one which doesn't require any extra allocations.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T18:35:56.747", "Id": "14754", "ParentId": "14753", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T18:00:33.087", "Id": "14753", "Score": "3", "Tags": [ "c#", "lookup", "pathfinding" ], "Title": "How can I make my A* algorithm faster?" }
14753
<p>I have created a class for reading data from an Excel sheet and holding on the variable. I am not sure if my code is optimized, meaning I will be reading heavily from Excel.</p> <p>Is there a room to further optimized this code? I will be using this class heaving in my code, and I wanted to get some opinions/feedback.</p> <p>I will be calling something like this:</p> <pre><code>ExcelReader xl = new ExcelReader(); string sss = xl.ExcelOpenSpreadsheets("mysheet"); //etc... public class ExcelReader { Application _excelApp; public ExcelReader() { _excelApp = new Application(); } public string ExcelOpenSpreadsheets(string sheetName) { string _txt = string.Empty; try { Workbook workBook = _excelApp.Workbooks.Open("filename_here",....); _txt = ExcelScanIntenal(workBook, sheetName); } catch { // // Deal with exceptions. // } return _txt; } private string ExcelScanIntenal(Workbook workBookIn, string sheetName) { Worksheet sheet = workBookIn.Sheets[sheetName] as Worksheet; Range a1 = sheet.get_Range("A1", "B2"); if (a1 != null) { string formattedText = r.Text; } return formattedText; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T21:12:40.507", "Id": "23994", "Score": "1", "body": "Do you HAVE to read from Excel? Reading from a CSV file is a lot easier. Where does this data in Excel come from? It would help if the source Excel had named ranges. Also, you do not need to invoke COM if you are just reading - you could operate on the data directly as in this example: http://stackoverflow.com/questions/15828/reading-excel-files-from-c-sharp (but there exist other ways as well)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T07:53:20.793", "Id": "24008", "Score": "2", "body": "What do you mean by \"optimized\"? Optimized for what?" } ]
[ { "body": "<p>Variable names make sense, except the r one.</p>\n\n<p>Good use of white space and tabs.</p>\n\n<p>I'm not sure if this can be optimized any more, but I do notice this method will not work</p>\n\n<pre><code>private string ExcelScanIntenal(Workbook workBookIn, string sheetName)\n{\n Worksheet sheet = workBookIn.Sheets[sheetName] as Worksheet;\n\n Range a1 = sheet.get_Range(\"A1\", \"B2\");\n if (a1 != null)\n {\n string formattedText = r.Text; \n }\n\n return formattedText; \n}\n</code></pre>\n\n<p>formattedText is declared within your if statement which may or may not be true.</p>\n\n<p>You have a random variable r show up in the middle of your function, I'm assuming it should be a1.</p>\n\n<p>I'd change it to this:</p>\n\n<pre><code>private string ExcelScanIntenal(Workbook workBookIn, string sheetName)\n{\n Worksheet sheet = workBookIn.Sheets[sheetName] as Worksheet;\n\n Range a1 = sheet.get_Range(\"A1\", \"B2\");\n if (a1 != null)\n {\n return a1.Text; \n }\n\n return string.Empty; \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T20:54:20.180", "Id": "14761", "ParentId": "14756", "Score": "1" } }, { "body": "<p>Seems to me that caching will help to the extent that you avoid reading from disk. If \"20% of the sheets get read 80% of the time\" - i.e. some sheets get read many times.</p>\n\n<p><code>System.Web.Caching</code> has a Cache class. Even though this is in the Web namespace it will work. Here is a quote from <a href=\"https://stackoverflow.com/questions/581119/object-cache-for-c-sharp\">a StackOverflow Posting</a></p>\n\n<blockquote>\n <p>How are you implementing your cache?</p>\n \n <p>You can use the Cache class from System.Web.Caching, even in non-web\n applications, and it will purge items on an LRU basis if/when it needs\n the memory.</p>\n \n <p>In a non-web application you'll need to use HttpRuntime.Cache to\n access the Cache instance.</p>\n \n <p>Note that the documentation states that the Cache class isn't intended\n to be used outside of ASP.NET, although it's always worked for me.\n (I've never relied on it in any mission-critical app though.)</p>\n</blockquote>\n\n<p>P.S. \"LRU\" means Least Recently Used. It's an algorithm for deciding what to discard to make room as the cache fills up.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T22:19:06.740", "Id": "14762", "ParentId": "14756", "Score": "1" } }, { "body": "<p>I'd change the code so that every implicit constant value is an argument in the constructor, with default values.</p>\n\n<p>In addition, I guess this excel application is the COM API for Excel, so perhaps a better approach would be using the <code>IDisposable</code> interface and implementation.</p>\n\n<p>I changed the typo and now the inner method's name is <code>ExcelScanInternal</code> (and not <code>ExcelScanIntenal</code>).</p>\n\n<p>So the result looks like this (I didn't compile it, so it might have syntax errors):</p>\n\n<pre><code>public class MyRange\n{\n public string @From { get; set; }\n public string @To { get; set; }\n}\n\npublic class ExcelReader : IDisposable\n{ \n Application _excelApp;\n string _fileName;\n MyRange _scanRange;\n\n public ExcelReader() : this (\"the_file_name\", new MyRange{From = \"A1\", To = \"B2\"})\n {\n }\n\n public ExcelReader(string fileName, MyRange scanRange)\n {\n if (null == fileName) throw new ArgumentNullException(\"fileName\");\n _fileName = fileName;\n if (null == scanRange) throw new ArgumentNullException(\"scanRange\");\n _scanRange = scanRange;\n _excelApp = new Application(); \n }\n\n public string ExcelOpenSpreadsheets(string sheetName)\n {\n string _txt = string.Empty;\n try\n {\n Workbook workBook = _excelApp.Workbooks.Open(_fileName,....);\n _txt = ExcelScanInternal(workBook, sheetName);\n }\n\n catch\n {\n //\n // Deal with exceptions.\n //\n }\n return _txt;\n }\n\n private string ExcelScanInternal(Workbook workBookIn, string sheetName)\n {\n Worksheet sheet = workBookIn.Sheets[sheetName] as Worksheet;\n\n Range a1 = sheet.get_Range(_scanRange.From, _scanRange.To);\n if (a1 != null)\n {\n string formattedText = a1.Text; \n }\n\n return formattedText; \n }\n\n public void Dispose()\n {\n _excelApp.Quit();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T20:58:26.850", "Id": "14839", "ParentId": "14756", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T20:10:18.630", "Id": "14756", "Score": "5", "Tags": [ "c#", "optimization", "excel" ], "Title": "Reading from an Excel sheet" }
14756
<p>I'm working an <a href="http://www.groovyexamples.org/2010/05/03/list-all-files-in-a-directory/" rel="nofollow">example to list directory contents</a>. When I process each directory the code works. Now I'd like to put both directories in an array and iterate the array. I get an error when I declare 'dir_c' because I've not given it a directory name which will change.</p> <pre><code> def outfile = new File('Y:/TEMP/dirlist.txt') def dir_a = new File('z:/pathA/pathB') def dir_b = new File('z:/pathA/pathQ') // def dir_c = new File() //causes error ==&gt;Could not find which method &lt;init&gt;(to invoke from this list outfile.write('') dir_a.eachFile { if (it.isFile()) { outfile.append(it.name + '\n') } dir_b.eachFile { if (it.isFile()) { outfile.append(it.name + '\n') } // Up to this point code works def searchDir = ["z:/pathA/pathB","z:/pathA/pathQ"] searchDir.each{ //was thinking using ==&gt;dir_c = it // then carry on like singleton cases // but I get error message when I declare dir_c } </code></pre>
[]
[ { "body": "<p>Do you mean like this:</p>\n\n<pre><code>def searchDir = [\"z:/pathA/pathB\",\"z:/pathA/pathQ\"]\nsearchDir.each { d -&gt;\n new File( d ).eachFile {\n if (it.isFile()) {\n outfile.append( \"$it.name\\n\" )\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T20:38:02.533", "Id": "14760", "ParentId": "14757", "Score": "2" } } ]
{ "AcceptedAnswerId": "14760", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T20:19:25.710", "Id": "14757", "Score": "0", "Tags": [ "groovy" ], "Title": "How can use array to imitate repeated individual instances?" }
14757
<p>I need to solve this problem in Python 3 (within 3 sec):</p> <blockquote> <p><code>A</code> is a given (NxM) rectangle, filled with characters "a" to "z". Start from <code>A[1][1]</code> to <code>A[N][M]</code> collect all character which is only one in its row and column, print them as a string.</p> <p>Input:</p> <p>\$N\$, \$M\$ in first line (number of row and column \$1 \le N\$, \$M \le &gt; 1000\$). Next, \$N\$ lines contain exactly \$M\$ characters.</p> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>A single string </code></pre> <p>Sample input 1:</p> <pre class="lang-none prettyprint-override"><code>1 9 arigatodl </code></pre> <p>Sample output 1:</p> <pre class="lang-none prettyprint-override"><code>rigtodl </code></pre> <p>Sample input 2:</p> <pre class="lang-none prettyprint-override"><code>5 6 cabboa kiltik rdetra kelrek dmcdnc </code></pre> <p>Sample output 2:</p> <pre class="lang-none prettyprint-override"><code>codermn </code></pre> </blockquote> <p>This is still not fast enough when \$N\$, \$M\$ = 1000. I'd like suggestions on improving the speed, or any other ways to solve the given problem, as long as the solution is in Python 3 and is faster than mine.</p> <pre class="lang-py prettyprint-override"><code>from operator import itemgetter Words,Chars,answer=[],"abcdefghijklmnopqrstuvwxyz","" N,M=[int(i) for i in input().split()] for _ in range(N): Words.append(input()) # got the inputs for row,word in enumerate(Words): # going through each words Doubts=[] # collect chars only one in its row. for char in Chars: if (word.count(char)==1): Doubts.append((char,word.index(char))) for case in sorted(Doubts,key=itemgetter(1)): #sorting by index doubtless=True #checking whether 1 in its column or not. for i in range(N): if (Words[i][case[1]]==case[0] and i!=row): doubtless=False break if (doubtless): answer+=case[0] #if char is one in its row and column, adds to answer. print (answer) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T19:21:32.937", "Id": "24060", "Score": "4", "body": "Not an observation about optimization, but why aren't you using [PEP8 guidelines](http://www.python.org/dev/peps/pep-0008/) to write your code? It's not a dealbreaker by any means, but 1) Why don't you have spaces between operators and 2) Capital/CamelCase is usually reserved for class definitions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T02:31:43.377", "Id": "24078", "Score": "0", "body": "Thanks, but this time I wasn't wondering about how it looks. I was worrying about how it works :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T11:23:17.580", "Id": "24088", "Score": "0", "body": "For info, this has been [cross-posted at StackOverflow](http://stackoverflow.com/questions/11969733/optimisations-for-this-code-in-python-3)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T11:49:53.637", "Id": "24090", "Score": "0", "body": "You didn't have to delete it, just **declare** the cross-posting. Then people can use the hyperlink to determine whether you still need assistance. It's about being considerate of other people's time, and as I said on the other thread, this has been part of netiquette for thirty years or so." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T23:03:05.750", "Id": "24094", "Score": "0", "body": "I'll take a look at it a bit more in depth, but it appears that you're iterating over the elements in the matrix more times then necessary. You *should* be able to write an algorithm that does at most `N * M * k_nm` checks, where k is the number of unique letters in each row/column. (by unique I mean a member of the set of letters, I don't mean that they don't repeat in the sequence)" } ]
[ { "body": "<p>I would suggest to create a 1000x1000 testcase and measure the performance before the optimization process. Please use the following test generator:</p>\n\n<pre><code>import os\nimport random\n\nf = open('1000x1000.in','w')\nf.write('1000 1000\\n')\nALPHABET = 'abcdefghijklmnopqrstuvwxyz'\nfor _ in range(1000):\n f.write(''.join([ALPHABET[random.randint(0, len(ALPHABET)-1)] for _ in range(1000)]) + '\\n')\nf.close()\n</code></pre>\n\n<p>After that just run it and measure the performance of your application. I got about <strong>47 ms</strong> on my pretty old C2D E7200.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:26:15.317", "Id": "15140", "ParentId": "14766", "Score": "2" } }, { "body": "<p>You could improve part of your loop.</p>\n\n<pre><code>Doubts=[] \nfor char in Chars:\n if (word.count(char)==1):\n Doubts.append((char,word.index(char)))\n</code></pre>\n\n<p>Can be done with list-comprehension.</p>\n\n<pre><code> Doubts = [(char, word.index(char)) for char in Chars if word.count(char) == 1]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T12:45:45.007", "Id": "20121", "ParentId": "14766", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T04:54:45.727", "Id": "14766", "Score": "5", "Tags": [ "python", "performance" ], "Title": "Printing characters in a matrix as a string" }
14766
<p>I have to display a menu where some buttons have dropdown submenus and show if the current button is active or not and put a CSS class to it for each of the two situations (or in both).</p> <pre><code>&lt;?php $menus_array = array( array('item1', false), array('item2', true), array('item3', false) ); $active_item = 'item2'; foreach ($menus_array as $menu_item) { if ($menu_item == $active_item &amp;&amp; $menu_item[1] != true) { $css_class = ' class="active"'; } else if ($menu_item != $active_item &amp;&amp; $menu_item[1] == true) { $css_class = ' class="dropdown"'; } else if ($menu_item == $active_item &amp;&amp; $menu_item[1] == true) { $css_class = ' class="active dropdown"'; } else { $css_class = ''; } } ?&gt; </code></pre> <p>I've written the code as above, but I don't really like it. Is there a way to write it better? I'm talking about the <code>foreach</code> loop.</p>
[]
[ { "body": "<p>A few things first:</p>\n\n<ul>\n<li><code>$menu_item == $active_item</code> should probably be <code>$menu_item[0] == $active_item</code></li>\n<li>Depending on where that array is coming from, it should probably be associative. Imagine if you came across the code out of context. You'd quickly find yourself wondering what in the world <code>menu_item[0]</code> and <code>menu_item[1]</code> are. <code>menu_item['name']</code> and <code>menu_item['down']</code> would be much more descriptive (or something like that).</li>\n<li><code>if (... &amp;&amp; $x == true) {}</code> is identical to <code>if (... &amp;&amp; $x) { }</code>. Don't include the implicit truth comparison. The only time you should compare against booleans is if you're wanting to compare type too. <code>if ($result === false) {}</code></li>\n</ul>\n\n<hr>\n\n<p>Anyway, I would probably do something like this:</p>\n\n<pre><code>foreach ($menus_array as $menu_item) {\n\n $classes = array();\n\n if ($menu_item[0] == $active_item) {\n $classes[] = 'active';\n }\n\n if ($menu_item[1]) {\n $classes[] = 'dropdown';\n }\n\n $css_class = ' class=\"' . implode(' ', $classes) . '\"';\n\n}\n</code></pre>\n\n<hr>\n\n<p>Or, if you are into micro-optimizing (and you shouldn't be):</p>\n\n<pre><code>foreach ($menus_array as $menu_item) {\n\n $class = '';\n\n if ($menu_item[0] == $active_item) {\n //Could be = instead of .= but putting .= will mean that you\n //can add another assignment above this and not have to change\n //= to .= here.\n $class .= 'active ';\n }\n\n if ($menu_item[1]) {\n $class .= 'dropdown ';\n }\n\n $css_class = ' class=\"' . rtrim($class) . '\"';\n\n}\n</code></pre>\n\n<p>(The <code>rtrim</code> really isn't necessary, but I'm picky. If I were super worried about performance, I would omit the rtrim.)</p>\n\n<hr>\n\n<p>I would go with the array based one. Rendering HTML is never going to be your bottleneck, and it's the easier one for me to read.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T09:46:43.480", "Id": "14772", "ParentId": "14769", "Score": "1" } } ]
{ "AcceptedAnswerId": "14772", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T09:11:36.470", "Id": "14769", "Score": "1", "Tags": [ "php" ], "Title": "Showing a menu with buttons with dropdown submenus" }
14769
<p>I had previously asked <a href="https://stackoverflow.com/q/11851147/250725">this question</a> on SO. The answer pointed me towards using the task parallel library for multiple parallel downloads. I'm not actually utilizing this exact code, but it got me to rethink my design.</p> <p>The one open issue that wasn't really addressed (and I didn't ask it), cancelling the a local <code>WebClient</code>. It isn't as simple as just calling <code>WebClient.CancelASync();</code> since the scope of <code>WebClient</code> is long gone by the time you need to cancel.</p> <p>This isn't my code or even how I am approaching the problem, but just part of the test example I put together to see how this works. It seems to work, although it means having to wait for an event callback before the cancel is called. So I was wondering if there was another alternative. </p> <pre><code>private bool pendingCancel = false; private Queue&lt;Uri&gt; queue = LoadQueue(); public void ASyncDownload() { if (queue.Count == 0) return; var uri = queue.Dequeue(); WebClient client = new WebClient(); client.DownloadProgressChanged += (sender, e) =&gt; { if (pendingCancellation) { ((WebClient)sender).CancelAsync(); return; } //do something to report progress }; client.DownloadDataCompleted += (sender, e) =&gt; { if (!e.Cancelled || pendingCancel) { if (e.Error == null) { // do something with e.Results } else { // report error } } else { // report cancellation } }; client.DownloadDataAsync(uri); } </code></pre> <p>My thought process is for any long running downloads, waiting until the next item in the queue to exit would not be appropriate, so the idea would be to call <code>CancelASync()</code> on the <code>sender</code> of the <code>DownloadProgressChanged</code> event handler.</p> <p>Is this the best alternative short of putting a <code>webClient</code> field in the class? And are there dangers or possible unpredictable behavior that I have not found in my testing?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T11:52:41.120", "Id": "24020", "Score": "1", "body": "Why are you trying to avoid using a field? That's exactly what they're for: storing objects that are needed for more than just one method call." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T13:15:29.097", "Id": "24025", "Score": "0", "body": "@svick In the end, I'm not trying to avoid anything, but I see similar patterns in other code and I am trying to understand if it is possible to cancel this type of async operation" } ]
[ { "body": "<p>I am not able to comment on your post due to a lack of reputation, but when I did something similar to this, I used a <a href=\"https://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken(v=vs.100).aspx\" rel=\"nofollow noreferrer\"><code>CancellationToken</code></a>. It's been around for quite some time now (.NET 4.0), and is generally accepted in most .NET Async APIs. It should achieve what you're trying to do. The documentation for the concept is located <a href=\"https://msdn.microsoft.com/en-us/library/dd997364(v=vs.100).aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>You don't <em>have</em> to put a <code>WebClient</code> in your class (as a field) if you don't want to. Most of the interactions I've seen with web servers (in C#) behave very similar to the Entity Framework in that you generally send a request, which yields some form of <code>IEnumerable</code> that you have to deal with. So, you could wire up a service util for handling the common bits for a web client, and generate a unique one per request. I did something similar to that, and it worked well, but you need to be cautious of shared state in that scenario (construction really needs to be construction - not use of a singleton - if you're generating a unique client every time).</p>\n\n<p>I hope this helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-12T08:10:56.993", "Id": "157554", "ParentId": "14771", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T09:45:30.393", "Id": "14771", "Score": "2", "Tags": [ "c#", "asynchronous" ], "Title": "Cancelling Local WebClient ASync Operation" }
14771
<p>I am trying to write a simple (trivial?) "compare" program for Eclipse preferences files.</p> <p>Eclipse preferences files take more of less this form:</p> <blockquote> <pre><code># optional comment line /a/sequence/of/path/elements=string /another/sequence/of/path/elements=42 # ... (possibly repeated) </code></pre> </blockquote> <p>Let's call the path sequences "keys" and what follows the <code>=</code> sign "values".</p> <p>The rules of the program should be:</p> <ul> <li>Exit upon detecting an invalid # of arguments (must be 2)</li> <li>argument1 and argument2 are the files to compare</li> <li>Exit if any of the input files are empty</li> <li>One preference entry per line</li> <li>Lines with a path key will have a path value, guaranteed</li> </ul> <p>The output should be as follows:</p> <h3>Part 1</h3> <ul> <li><p>All lines from argument1 which have keys not present in argument2, like so:</p> <blockquote> <pre><code>/path 42 /path2 banana </code></pre> </blockquote></li> <li><p>Blank line</p></li> </ul> <h3>Part 2</h3> <ul> <li><p>All keys that are present in both argument1 and argument2, like so:</p> <blockquote> <pre><code>/shared (valueInArgument1, valueInArgument2) /shared2 (valueInArgument1, valueInArgument2) </code></pre> </blockquote></li> <li><p>Blank line</p></li> </ul> <h3>Part 3</h3> <ul> <li><p>All lines from <code>argument2</code> which have keys not present in <code>argument1</code>, like so:</p> <blockquote> <pre><code>/path3 24 /path4 ananab </code></pre> </blockquote></li> </ul> <p>Notice Part 1, Part 2, and Part 3 must all be sorted.</p> <p>I would like to get something:</p> <ul> <li>Pythonic</li> <li>Efficient (do as little work as possible computationally, use as little space as possible)</li> <li>Clear and readable from a logical point of view</li> <li>Correct (gets the right result even in edge cases)</li> <li>Instructive (uses data structures and algorithms properly)</li> </ul> <p>Here's my attempt:</p> <pre><code>#!/usr/bin/env /opt/local/bin/python2.7 import sys import os import re import pprint COMMAND_SYNTAX_ERROR = 2 EMPTY_PREFS_FILE_ERROR = 3 PREFS_REGEX_PATTERN = '^(.*?)=(.*)$' PREFS_REGEX = re.compile(PREFS_REGEX_PATTERN) def parse_prefs_line(line): regex_result = PREFS_REGEX.match(line) if not regex_result: return None, None return regex_result.group(1), regex_result.group(2) arguments = sys.argv n_arguments = len(arguments) if n_arguments != 3: print 'usage: eclipse_diff file1.epf file2.epf' sys.exit(COMMAND_SYNTAX_ERROR) file1, file2 = open(sys.argv[1]), open(sys.argv[2]) prefs1 = file1.readlines() file1.close() prefs2 = file2.readlines() file2.close() length1, length2 = len(prefs1), len(prefs2) if length1 == 0 or length2 == 0: print 'both files must contain at least one configuration line' sys.exit(EMPTY_PREFS_FILE_ERROR) prefs1.sort() prefs2.sort() onlyin1 = [] onlyin2 = [] inboth = [] index1 = 0 index2 = 0 stop1 = False stop2 = False pause1 = False pause2 = False lastkey1 = None lastkey2 = None while True: if not stop1 and not pause1: line1 = prefs1[index1] if not line1: stop1 = True else: line1_left, line1_right = parse_prefs_line(line1) if line1_left and line1_right: onlyin1.append((line1_left, line1_right)) lastkey1 = line1_left index1 += 1 if index1 == length1: stop1 = True if not stop2 and not pause2: line2 = prefs2[index2] if not line2: stop2 = True else: line2_left, line2_right = parse_prefs_line(line2) if line2_left and line2_right: onlyin2.append((line2_left, line2_right)) lastkey2 = line2_left index2 += 1 if index2 == length2: stop2 = True if lastkey1 and lastkey2: if lastkey1 == lastkey2: inboth.append( (lastkey1, (onlyin1.pop()[1], onlyin2.pop()[1] ))) lastkey1 = onlyin1[len(onlyin1)-1][0] if onlyin1 else None lastkey2 = onlyin2[len(onlyin2)-1][0] if onlyin2 else None if not stop1: if lastkey1 and not stop2 and lastkey1 &gt; lastkey2: pause1 = True else: pause1 = False if not stop2: if lastkey2 and not stop1 and lastkey2 &gt; lastkey1: pause2 = True else: pause2 = False if stop1 and stop2: break for pref in onlyin1: print pref[0], pref[1] print for pref in inboth: print pref[0], pref[1] print for pref in onlyin2: print pref[0], pref[1] </code></pre> <p>How can I improve this?</p> <p>To make my question specific: I would like for it to execute in less cycles.</p> <p>My other thought was to create a hash map of keys, add values to it, sort the keys and split the output based on how many values correspond to the key...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T03:52:44.607", "Id": "24014", "Score": "0", "body": "Where's the profiler output?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T03:53:13.997", "Id": "24015", "Score": "0", "body": "I don't know how to do that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T04:05:37.907", "Id": "24016", "Score": "0", "body": "You are still working on your algorithm. Once you get an algorithm you are happy with, then optimize it, not before. Your \"PS\" comment sounds like a good direction to me. Give that a try." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T04:08:31.977", "Id": "24017", "Score": "0", "body": "Actually no, I have decided against the hash map in the end and this is what I have got as my algorithm. I think this is superior to the hash map approach. I may be mistaken. Do you think differently? Why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T04:16:55.037", "Id": "24018", "Score": "0", "body": "@mhawke: a good pointer. I did not know about that... Still in Beta though, no wonder I did not have it at the top of my list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T05:06:18.977", "Id": "24019", "Score": "0", "body": "Haven't used it personally, but perhaps this would be relevant? http://docs.python.org/library/difflib.html" } ]
[ { "body": "<p>Don't optimize unless your profiler says so.</p>\n\n<p>You could start with the simplest code that works e.g., here's a straightforward translation of your requirements: </p>\n\n<pre><code>import sys\n\ndef get_entries(filename):\n    with open(filename) as file:\n        # extract 'key = value' entries\n        entries = (map(str.strip, line.partition('=')[::2]) for line in file)\n        #note: if keys are repeated the last value wins\n        # enforce non-empty values, skip comments\n        return {key: value for key, value in entries\n                if value and not key.startswith('#')}\n\nif len(sys.argv) != 3:\n    sys.exit(2) # wrong number of arguments\nd1, d2 = map(get_entries, sys.argv[1:])\nif not (d1 and d2):\n    sys.exit(1) # no entries in a file\n\ndef print_entries(keys, d, d2=None):\n    for k in sorted(keys):\n        value = d[k] if d2 is None else \"(%s, %s)\" % (d[k], d2[k])\n        print k, value\n    print\n\nprint_entries(d1.viewkeys() - d2.viewkeys(), d1)\nprint_entries(d1.viewkeys() &amp; d2.viewkeys(), d1, d2)\nprint_entries(d2.viewkeys() - d1.viewkeys(), d2)\n</code></pre>\n\n<p>You could compare results and the performance with your code.</p>\n\n<p>You could also compare it the <a href=\"http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/comm.c#n229\"><code>comm</code> command from coreutils</a>:</p>\n\n<pre><code>$ comm &lt;(sort file1) &lt;(sort file2)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T07:29:57.670", "Id": "14775", "ParentId": "14774", "Score": "5" } } ]
{ "AcceptedAnswerId": "14775", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T03:50:55.487", "Id": "14774", "Score": "4", "Tags": [ "python", "parsing", "eclipse" ], "Title": "\"Compare\" program for Eclipse preference files" }
14774
<p>This is a solution to the problem: <a href="http://webcache.googleusercontent.com/search?q=cache%3a-RiwllI4gAsJ%3auva.onlinejudge.org/index.php?option=onlinejudge&amp;page=show_problem&amp;problem=2146%20&amp;cd=1&amp;hl=da&amp;ct=clnk&amp;gl=dk" rel="nofollow">"The Broken Pedometer"</a> on the UVA online judge. (Note: I can not use anything beyond what is in g++ 4.6 <a href="http://www.ioi2012.org/competition/contest-environment/" rel="nofollow">which is what is used for the competition I'm training for.</a>)</p> <p>Algorithmic approach (pretty simple, but fast enough, not needed to understand to comment on the code):</p> <ul> <li><code>possible_led_removals</code> recursively attempts to remove one integer from all the strings in <code>leds</code> while maintaining a unique array of strings (<code>leds</code>):</li> <li>If removing an integer leads to duplicates in <code>leds</code>, return (base case)</li> <li>Otherwise, return the maximum amount of possible removals (depth) at the same index from the strings in <code>leds</code>, while maintaining <code>leds</code> to be an array of unique strings (recursion)</li> </ul> <p>My C++ is /very/ rough, and I mostly use C++ because of the STL. However, I'd like to improve my C++ to improve my contest performance, so any help, algorithmic as well as code-wise is much appreciated! Thanks!</p> <pre><code>#include&lt;iostream&gt; #include&lt;cstdlib&gt; #include&lt;vector&gt; #include&lt;sstream&gt; #include&lt;algorithm&gt; using namespace std; size_t n_leds, n_symbols; bool any_duplicates(vector&lt;string&gt; &amp;leds) { for(size_t i = 0; i &lt; (int)leds.size(); ++i) for(size_t j = i + 1; j &lt; (int)leds.size(); ++j) if(leds[i] == leds[j]) return true; return false; } int possible_led_removals(size_t erase_index, vector&lt;string&gt; leds, size_t depth) { for(vector&lt;string&gt;::iterator it = leds.begin(); it != leds.end(); ++it) { string::iterator string_it; string_it = (*it).begin() + erase_index; (*it).erase(string_it); } int max_depth = 0; if (any_duplicates(leds)) { return depth; } else { for(size_t i = 0; i &lt; (int)leds[0].length(); ++i) max_depth = max(possible_led_removals(i, leds, depth + 1), max_depth); } return max_depth; } int main() { size_t problems; cin &gt;&gt; problems; for(size_t i = 0; i &lt; problems; ++i) { cin &gt;&gt; n_leds &gt;&gt; n_symbols; vector&lt;string&gt; symbols; for(size_t j = 0; j &lt; n_symbols; j++) { ostringstream led; for(size_t k = 0; k &lt; n_leds; k++) { bool on; cin &gt;&gt; on; led &lt;&lt; on; } symbols.push_back(led.str()); } int max_removals = 0; for(int i = 0; i &lt; n_leds; ++i) max_removals = max(max_removals, possible_led_removals(i, symbols, 0)); cout &lt;&lt; n_leds - max_removals &lt;&lt; endl; } return 0; } </code></pre>
[]
[ { "body": "<p>Just some hints to improve your C++ code if not the algorithm logic:</p>\n\n<ul>\n<li>Use const references for passing big objects like vectors to functions. For example, replace <code>vector&lt;string&gt; leds</code> by <code>const vector&lt;string&gt;&amp; leds</code> in <code>any_duplicates</code>. Otherwise, it will perform a full copy of the vector and its elements. Here, const reference is right since the vector is not modified.</li>\n<li>You could add <code>std::ios_base::sync_with_stdio(false);</code> at the beginning of your code. Default thing for streams is to call C functions from <code>cstdio</code>. Putting that line allow streams not to use those functions and then to be faster.</li>\n<li>For readability, you could replace <code>(*it).stuff</code> by <code>it-&gt;stuff</code> everywhere.</li>\n<li><code>vector::size()</code> returns a <code>size_t</code> and that's what you use in your loops. No need to cast the result to an <code>int</code>.</li>\n<li>I may be wrong, but I don't see any functions from <code>cstdlib</code> used here. You could get rid of that header.</li>\n</ul>\n\n<p>You could also probably improve readability and performance by using features from C++11 (usable with the option <code>-std=c++0x</code> with gcc). I don't know if your contest allows it or not.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T14:46:11.663", "Id": "24028", "Score": "0", "body": "The problem I saw with using `const vector<string>& leds` as a parameter for `possible_led_removals` is that it modifies `leds`, thus passing by reference will alter a vector used later by any other function that recurses on the same vector." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T14:50:37.367", "Id": "24030", "Score": "0", "body": "Also, `size_t` is declared in `cstdlib`, isn't it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T14:51:43.780", "Id": "24031", "Score": "0", "body": "@Sirupsen It's declared in `cstddef` which is included by any header that uses `size_t`, so most of the C and C++ headers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T14:52:13.947", "Id": "24032", "Score": "0", "body": "Great! Thank you very much for your help. :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T14:43:40.750", "Id": "14782", "ParentId": "14777", "Score": "3" } }, { "body": "<h2>Notes on the code</h2>\n\n<pre><code>bool any_duplicates(vector&lt;string&gt; &amp;leds)\n{\n</code></pre>\n\n<p>if you're not planning to change the vector contents, this should be</p>\n\n<pre><code>bool any_duplicates(vector&lt;string&gt; const &amp;leds)\n</code></pre>\n\n<p>also observe this is an O(n<sup>2</sup>) search; it may not matter much for <code>N&lt;=100</code> as given, but simply sorting the values and doing a linear scan would be O(n log n).</p>\n\n<h2>Notes on data structures</h2>\n\n<p>Since you're given <code>P&lt;=15</code>, you could trivially encode each symbol as a bitmap in a <code>uint16_t</code>. This simplifies the LED deactivation (just mask out the bit) and speeds up the sorting and duplicate detection (it's an integer comparison).</p>\n\n<h2>Notes on algorithms</h2>\n\n<p>Since the number of symbols <em>may</em> greatly exceed the number of bits, it may be possible to cut the search space down faster by working the other way round.</p>\n\n<p>At least, if some of the bits (LEDs) have the same value in every symbol, you know they can <em>always</em> be removed and you don't need to check them. In the second linked example, the last two bits are always zero, so you can ignore them during your search.</p>\n\n<p>I also have a nagging feeling there could be a much smarter approach based on information theory, but if there is, it hasn't crystallized yet.</p>\n\n<hr>\n\n<h2>Footnotes</h2>\n\n<ul>\n<li><p><em>justification of O(n<sup>2</sup>)</em>:</p>\n\n<p>the outer loop</p>\n\n<pre><code>for(size_t i = 0; i &lt; (int)leds.size(); ++i)\n</code></pre>\n\n<p>is clearly linear, so we execute the inner loop <em>n</em> times:</p>\n\n<pre><code>for(size_t j = i + 1; j &lt; (int)leds.size(); ++j)\n if(leds[i] == leds[j]) //...\n</code></pre>\n\n<p>does <em>n-1</em> comparisons for each <em>n</em> in <em>[0..size)</em>. Let's write out the total number of steps for some small values of <em>n</em> to be clear:</p>\n\n<ul>\n<li>n=2: <em>i in [0,2)</em> gives two iterations over the outer loop; the first gives two iterations of the inner loop for <em>j in [0,2)</em> and the second gives a single iteration for <em>j in [1,2)</em>. So, we did <em>2 + 1 = 3</em> comparisons.</li>\n<li>n=3: now we do three top-level iterations, and the inner loop covers the ranges <em>j in [0,3), [1,3), [2,3)</em>. So, <em>3 + 2 + 1 = 6</em> comparisons.</li>\n<li>n=4: <em>4 + 3 + 2 + 1 = 10</em> comparisons</li>\n</ul>\n\n<p>this is just the <a href=\"http://en.wikipedia.org/wiki/Arithmetic_progression#Sum\" rel=\"nofollow\">sum of the arithmetic progression</a> <em>n + (n-1) + ... + 2 + 1</em></p>\n\n<p>Use the formula given in the link with <em>a<sub>1</sub>=1</em> and <em>a<sub>n</sub>=n</em> to get <em>(n/2)(n+1)</em> </p>\n\n<p>This gives the maximum number of comparisons performed, <em>(n/2)(n+1) = (n<sup>2</sup> + n)/2</em>, proportional to O(n<sup>2</sup>). Obviously it may return early, but I don't know how likely that is: this is the worst-case performance.</p></li>\n<li><p><em>bitmap encoding</em></p>\n\n<p>Taking one of the sample symbols from your link, <code>1 0 1 1 0 1 1</code>: since every character is one or zero I can trivially interpret this as a binary number:</p>\n\n<pre><code>column: 6 5 4 3 2 1 0\nvalue: 1 0 1 1 0 1 1\n= 2^6 + 2^4 + 2^3 + 2^1 + 2^0 = 91 (decimal)\n</code></pre>\n\n<p>and as you're guaranteed &lt;=15 LEDs, you need &lt;=15 bits to represent every possible value, so <code>uint16_t</code> (giving 16 bits) is big enough.</p></li>\n<li><p><em>bitmap manipulation</em></p>\n\n<p>Now, comparisons are clearly faster with this scheme, but so is disabling LEDs. For example, it was something like:</p>\n\n<pre><code>vector&lt;string&gt; disable_led(size_t index, vector&lt;string&gt; leds)\n{\n for(vector&lt;string&gt;::iterator it = leds.begin(); it != leds.end(); ++it) {\n string::iterator string_it;\n string_it = (*it).begin() + erase_index;\n (*it).erase(string_it);\n }\n return leds;\n}\n</code></pre>\n\n<p>while the integer-encoded version could be:</p>\n\n<pre><code>vector&lt;uint16_t&gt; disable_led(size_t index, vector&lt;uint16_t&gt; leds)\n{\n uint16_t mask = ~(1 &lt;&lt; (n_leds-index));\n for(auto it = leds.begin(); it != leds.end(); ++it) {\n *it &amp;= mask;\n }\n return leds;\n}\n</code></pre>\n\n<p>You could even avoid copying &amp; mutating the LED vector at all, just update the mask as you pass it down, using it in each comparison. That seems like more work in the inner loop, but there's good chance it's faster anyway</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:28:19.597", "Id": "24036", "Score": "0", "body": "Thanks for your notes. Couple of questions:\na) Is this really an O(n^2) search? Because of the recursion (although backtracking, so it depends on the input, of course) isn't the average-case much worse?\nb) Can you elaborate on the \"encode each symbol as a bitmap\" and \"just mask out the bit\"? \n\nThank you very much for your time!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T16:50:06.803", "Id": "24050", "Score": "0", "body": "The O(n^2) comment was just addressed to `any_duplicates`, not the whole thing" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:11:09.080", "Id": "14785", "ParentId": "14777", "Score": "3" } }, { "body": "<p>The others have made some good points, a few I'd like to add.</p>\n\n<p>Look at using std::bitset&lt;> to hold the on/off information. Then use the bitmap encoding/manipulation that @Useless has suggested.</p>\n\n<pre><code>for(size_t i = 0; i &lt; (int)leds[0].length(); ++i)\n max_depth = max(possible_led_removals(i, leds, depth + 1), max_depth);\n</code></pre>\n\n<p>This piece is, I think, the source of your serious speed issues. The problem is that you reach the same subset of working led segments by different approaches. i.e. you and remove 0 then 1, or you can remove 1 then 0, but you end up in the same place. You should rework you code so that it considers each subset only once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T18:36:56.320", "Id": "24054", "Score": "0", "body": "This is true. Do you have any ideas on how to avoid this, besides some sort of memorization?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T18:40:05.203", "Id": "24055", "Score": "0", "body": "@Sirupsen, simplest solution would be to do `for(size_t i = erase_index;...` That way you only consider one order of producing each possible subset." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T17:35:42.543", "Id": "14797", "ParentId": "14777", "Score": "3" } } ]
{ "AcceptedAnswerId": "14785", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T12:03:35.760", "Id": "14777", "Score": "2", "Tags": [ "c++", "algorithm" ], "Title": "\"The broken pedometer\" optimizations" }
14777
<p>I created a Matrix class. I tested it and it seems to work.</p> <ol> <li>Can someone tell me if this class is good?</li> <li>Can I improve it?</li> <li>Can I use more move semantics (where)? What do I have to modify?</li> <li>Are there some logic/programming errors?</li> </ol> <p></p> <pre><code>#ifndef MATRIX_H #define MATRIX_H #include &lt;iostream&gt; #include &lt;initializer_list&gt; #include &lt;stdexcept&gt; #include &lt;utility&gt; #include &lt;type_traits&gt; template &lt;typename T&gt; class Matrix { static_assert(std::is_arithmetic&lt;T&gt;::value,""); public: Matrix(size_t, size_t); Matrix(size_t, size_t, const T&amp;); Matrix(const Matrix&lt;T&gt;&amp;); virtual ~Matrix(); void set(const T&amp;); size_t get_row() const; size_t get_col() const; void print(std::ostream&amp;) const; Matrix&lt;T&gt;&amp; operator=(const Matrix&lt;T&gt;&amp;); T&amp; operator()(size_t, size_t); T operator()(size_t, size_t) const; bool operator==(const Matrix&lt;T&gt;&amp;) const; bool operator!=(const Matrix&lt;T&gt;&amp;) const; Matrix&lt;T&gt;&amp; operator+=(const Matrix&lt;T&gt;&amp;); Matrix&lt;T&gt;&amp; operator-=(const Matrix&lt;T&gt;&amp;); Matrix&lt;T&gt; operator+(const Matrix&lt;T&gt;&amp;) const; Matrix&lt;T&gt; operator-(const Matrix&lt;T&gt;&amp;) const; Matrix&lt;T&gt;&amp; operator*=(const T&amp; v); Matrix&lt;T&gt;&amp; operator*=(const Matrix&lt;T&gt;&amp;); Matrix&lt;T&gt; operator*(const Matrix&lt;T&gt;&amp;) const; private: size_t row; size_t col; size_t dim; T* data; void copy(const Matrix&lt;T&gt;&amp;); }; template &lt;typename T&gt; inline Matrix&lt;T&gt;::Matrix(size_t r, size_t c) : row(r), col(c), dim(r*c), data(new T[r*c]) {} template &lt;typename T&gt; inline Matrix&lt;T&gt;::Matrix(size_t r, size_t c, const T&amp; v) : row(r), col(c), dim(r*c), data(new T[r*c]) { set(v); } template &lt;typename T&gt; inline Matrix&lt;T&gt;::Matrix(const Matrix&lt;T&gt;&amp; m) { copy(m); } template &lt;typename T&gt; inline Matrix&lt;T&gt;::~Matrix() { delete [] data; } template &lt;typename T&gt; inline void Matrix&lt;T&gt;::set(const T&amp; v) { for(size_t i(0); i &lt; dim; i++) { data[i] = v; } } template &lt;typename T&gt; inline size_t Matrix&lt;T&gt;::get_row() const { return row; } template &lt;typename T&gt; inline size_t Matrix&lt;T&gt;::get_col() const { return col; } template &lt;typename T&gt; inline void Matrix&lt;T&gt;::print(std::ostream&amp; out) const { for(size_t i(0); i &lt; row; i++) { for(size_t j(0); j &lt; col; j++) { out &lt;&lt; data[col*i + j] &lt;&lt; ' '; } out &lt;&lt; std::endl; } } template &lt;typename T&gt; inline Matrix&lt;T&gt;&amp; Matrix&lt;T&gt;::operator=(const Matrix&lt;T&gt;&amp; m) { if(this != &amp;m) { delete [] data; copy(m); } return *this; } template &lt;typename T&gt; inline T&amp; Matrix&lt;T&gt;::operator()(size_t i, size_t j) { if( (i == 0) or (j == 0) or (i &gt; row) or (j &gt; col)) { throw std::out_of_range(""); } return data[col*(i-1) + (j-1)]; } template &lt;typename T&gt; inline T Matrix&lt;T&gt;::operator()(size_t i, size_t j) const { if( (i == 0) or (j == 0) or (i &gt; row) or (j &gt; col)) { throw std::out_of_range(""); } return data[col*(i-1) + (j-1)]; } template &lt;typename T&gt; inline bool Matrix&lt;T&gt;::operator==(const Matrix&lt;T&gt;&amp; m) const { if( (row != m.row) or (col != m.col) ) { return false; } for(size_t i(0); i &lt; row; i++) { if(data[i] != m.data[i]) { return false; } } return true; } template &lt;typename T&gt; inline bool Matrix&lt;T&gt;::operator!=(const Matrix&lt;T&gt;&amp; m) const { return !((*this) == m); } template &lt;typename T&gt; inline Matrix&lt;T&gt;&amp; Matrix&lt;T&gt;::operator+=(const Matrix&lt;T&gt;&amp; m) { if( (row != m.row) or (col != m.col) ) { throw std::range_error(""); } for(size_t i(0); i &lt; dim; i++) { data[i] += m.data[i]; } return *this; } template &lt;typename T&gt; inline Matrix&lt;T&gt;&amp; Matrix&lt;T&gt;::operator-=(const Matrix&lt;T&gt;&amp; m) { if( (row != m.row) or (col != m.col) ) { throw std::range_error(""); } for(size_t i(0); i &lt; dim; i++) { data[i] -= m.data[i]; } return *this; } template &lt;typename T&gt; inline Matrix&lt;T&gt; Matrix&lt;T&gt;::operator+(const Matrix&lt;T&gt;&amp; m) const { if( (row != m.row) or (col != m.col) ) { throw std::range_error(""); } Matrix&lt;T&gt; tmp(*this); for(size_t i(0); i &lt; dim; i++) { tmp.data[i] += m.data[i]; } return std::move(tmp); } template &lt;typename T&gt; inline Matrix&lt;T&gt; Matrix&lt;T&gt;::operator-(const Matrix&lt;T&gt;&amp; m) const { if( (row != m.row) or (col != m.col) ) { throw std::range_error(""); } Matrix&lt;T&gt; tmp(*this); for(size_t i(0); i &lt; dim; i++) { tmp.data[i] -= m.data[i]; } return std::move(tmp); } template &lt;typename T&gt; inline Matrix&lt;T&gt;&amp; Matrix&lt;T&gt;::operator*=(const T&amp; v) { for(size_t i(0); i &lt; dim; i++) { data[i] *= v; } return *this; } template &lt;typename T&gt; inline Matrix&lt;T&gt;&amp; Matrix&lt;T&gt;::operator*=(const Matrix&lt;T&gt;&amp; m) { if( col != m.row ) { throw std::range_error(""); } Matrix&lt;T&gt; tmp(*this); col = m.col; delete [] data; data = new T[row*col]; for(size_t i(0); i &lt; row; i++) { for(size_t j(0); j &lt; m.col; j++) { for(size_t k(0); k &lt; tmp.col; k++ ) { data[col*i + j] += tmp.data[tmp.col*i + k] * m.data[m.col*k + j]; } } } return *this; } template &lt;typename T&gt; inline Matrix&lt;T&gt; Matrix&lt;T&gt;::operator*(const Matrix&lt;T&gt;&amp; m) const { if( col != m.row ) { throw std::range_error(""); } Matrix&lt;T&gt; tmp(*this); return std::move(tmp *= m); } template &lt;typename T&gt; inline void Matrix&lt;T&gt;::copy(const Matrix&lt;T&gt;&amp; m) { row = m.row; col = m.col; dim = m.dim; data = new T[dim]; for(size_t i(0); i &lt; dim; i++) { data[i] = m.data[i]; } } template &lt;typename T&gt; inline Matrix&lt;T&gt; operator*(const T&amp; v, const Matrix&lt;T&gt;&amp; m) { Matrix&lt;T&gt; tmp(m); tmp *= v; return std::move(tmp); } template &lt;typename T&gt; inline Matrix&lt;T&gt; operator*(const Matrix&lt;T&gt;&amp; m, const T&amp; v) { return std::move(v * m); } template &lt;typename T&gt; inline std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Matrix&lt;T&gt;&amp; m) { m.print(out); return out; } #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:15:23.540", "Id": "24033", "Score": "0", "body": "i would rename get_row() to get_row_size(). I would expect a method called `get_row` to take an index and return a row vector if this index is between 0 and the row size" } ]
[ { "body": "<p>I would make several improvements.</p>\n\n<p>I really don't like the fact that the interface has no names on parameters. You can skip all the names you want on the definitions, but when I look at a declaration I want to know what the parameters are.</p>\n\n<p>Still on the interface part, I'd rename <code>get_row</code> and <code>get_col</code> to <code>rows</code> and <code>columns</code>: they don't get you a row or a column, but the total number of rows or columns. <code>set</code> I would probably name <code>fill</code>, but then I'd remember there's a <code>std::fill</code> algorithm already in the <code>&lt;algorithm&gt;</code> header. That would lead me to think about providing an iterator-based interface: it brings the ability to use all the standard algorithms. I'll come back to this point later.</p>\n\n<p>Then, I see no reason to provide a virtual destructor. Why would <code>Matrix</code> be a polymorphic base class? If you use it polymorphically you lose the ability to properly pass it by value, and that makes the overloaded operators add confusion and opportunities for slicing.</p>\n\n<p>Unless you are using the Visual Studio compiler (which has this known issue), there is no need to move local variables in return statements like <code>return std::move(tmp);</code>, or even to move temporaries like <code>return v * m;</code>. The compiler does that automatically. Making the move explicit causes confusion, at least to those that are already acquainted with the C++11 features.</p>\n\n<p>The biggest change I'd make would be to follow what I call <a href=\"http://rmartinho.github.com/cxx11/2012/08/15/rule-of-zero.html\" rel=\"nofollow\">the rule of zero</a>. I'd use an existing solution for handling memory ownership. In this case, a <code>std::vector</code> member. That means I don't need to write a copy constructor, nor a copy assignment operator, nor a destructor: I get all those for free <em>and</em> a move constructor and a move assignment operator. Less code and more features.</p>\n\n<p>And now that I have a <code>std::vector</code> member, I can use it to easily provide an iterator based interface: just return iterators from the vector, and everything works.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:24:54.120", "Id": "24034", "Score": "0", "body": "how about `assign` for `set`/`fill`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:40:49.703", "Id": "24039", "Score": "0", "body": "Thank you for the advices! I will change my T* pointer in a std::vector<T>. I don't get very well how to provide iterators (also because I didn't studied the topic very well)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:49:28.847", "Id": "24042", "Score": "0", "body": "@R.M. obviously feel free to disregard the parts about iterators right until you start understanding them. If you decide to get on with and have trouble I'll be happy to help you with it on Stack Overflow or giving advice here :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T16:00:38.113", "Id": "24045", "Score": "0", "body": "@R.MartinhoFernandes Fernandes Tomorrow I will post my code modification and maybe I can better study iterators. Thank you for the advices! ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T17:54:35.930", "Id": "24053", "Score": "0", "body": "I totally agree in the real world I would use std::vector<T> but this is a perfect learning exercise to show how to implement copy construction assignment and move semantics for a class you write. It is simple but complex enough to have a few got-ya's in it." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:17:20.303", "Id": "14786", "ParentId": "14784", "Score": "5" } }, { "body": "<p>One general comment is that, instead of catching dimensional mis-matches in assignments and operations between matrices at runtime, you can add two more template parameters for the number of rows and columns respectively. Then you can catch these mis-matches at compile time. I have done this in two matrix implementations in the past and it works quite well.</p>\n\n<pre><code>template &lt;typename T, unsigned int ROWS, unsigned int COLS&gt;\nclass Matrix { .... };\n</code></pre>\n\n<p>Of course, this means that different size matrices are different types. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:38:23.280", "Id": "24038", "Score": "0", "body": "I thought this was a very good idea while I arrived at matrix multiplication. If I multiply a 3x2 matrix with a 2x7 matrix, I have to create a different 3x7 matrix to store the result... So I thought it was better to let matrices change dimension." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:43:22.083", "Id": "24040", "Score": "0", "body": "@R.M. When i designed my matrices, I thought it better to make sure at *compile time* that such a multiplication could only be assigned to a 3x7 matrix. I found too many bugs in code using dynamically sized matrices..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:49:20.987", "Id": "24041", "Score": "0", "body": "I will think about it, but I think is quite annoying calculating the dimension of the result. If I decide to use non-type templates, do you think that I have to store the number of rows and columns anyway?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:54:42.747", "Id": "24043", "Score": "0", "body": "@R.M. If you have C++11, then you can use `auto` for the return type. If not, it can be a pain but at least the compiler will tell you you got the wrong size. As for storing the dimensions, it depends. If you were to store the data as a vector of vectors, then you should use their `size()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:58:24.230", "Id": "24044", "Score": "0", "body": "I think I will stay to store data in a std::vector<T>: it's more efficient in allocation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T16:03:31.240", "Id": "24046", "Score": "0", "body": "@R.M. in that case, you should store the number of rows and/or the number of columns separately." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T16:06:04.470", "Id": "24047", "Score": "0", "body": "Ok, thank you. It would be better to use an std::array instead of a std::vector in this case?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:23:03.557", "Id": "14787", "ParentId": "14784", "Score": "1" } } ]
{ "AcceptedAnswerId": "14786", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:00:59.603", "Id": "14784", "Score": "3", "Tags": [ "c++", "optimization", "matrix" ], "Title": "Templated Matrix class" }
14784
<p>I've created the below script and would appreciate any feedback. </p> <pre><code># svn directory ^/tags/release/ # 1/ # 2/ # 3/ # 4/ # usage: svnnextrelease fixes email formatting # generated line: svn cp ^/trunk ^/tags/release/# -m'fixes email formatting' function svnnextrelease(){ NextVersion=$(svn ls ^/tags/release | tail -n 1 | while read tag; do expr $(echo "${tag%?}") + 1; done) # svn ls ^/tags/release, listing the directories # tail -n 1, give me the last (latest) directory # while loop reads result # expr $(echo "${tag%?}") + 1, echo statment removes the "/" so 4/ becomes 4. expr then increments it. # echo $NextVersion; 5 svn cp ^/trunk ^/tags/release/$NextVersion -m'$@' } </code></pre>
[]
[ { "body": "<p>Here is a small improvement.</p>\n\n<pre><code>svnnextrelease() {\n v=$(svn ls ^/tags/release | tail -n 1)\n svn cp ^/trunk ^/tags/release/$((${v%/} + 1 )) -m \"$@\"\n}\n</code></pre>\n\n<ul>\n<li>You can use $(( )) as a replacement for expr in bash. (depends on your taste.)</li>\n<li>bash can cheaply get rid of / for you. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T05:05:38.903", "Id": "14811", "ParentId": "14789", "Score": "1" } } ]
{ "AcceptedAnswerId": "14811", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:38:00.943", "Id": "14789", "Score": "3", "Tags": [ "bash", "svn" ], "Title": "Bash function to create the next SVN release tag" }
14789
<p>I am never to sure when it comes to <code>ifstream</code> and reading lines. I am often confused with the <code>good()</code>, <code>bad()</code>, <code>eof()</code> and so on.</p> <p>Could anyone tell me if I am doing it right?</p> <pre><code>int parseLine(std::ifstream &amp; _file) { while( std::getline( _file, line, '\n' ).good() &amp;&amp; !_file.eof() ) { // some treatment } return 0; } </code></pre>
[]
[ { "body": "<p>Too complicated. Just say:</p>\n\n<pre><code>for (std::string line; std::getline(_file, line); )\n{\n // process \"line\"\n}\n</code></pre>\n\n<p>The function <code>std::getline</code>, like most iostreams operations, returns a reference to the stream object itself, which can be evaluated in a boolean context to tell you whether it is still good, i.e. whether the extraction operation succeeded.</p>\n\n<p>Also, the function shouldn't be called \"parseLine\", but \"parseAllLines\" or \"parseStream\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T08:29:59.763", "Id": "24100", "Score": "1", "body": "I like it, easy and super clear" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T16:34:08.423", "Id": "14792", "ParentId": "14790", "Score": "11" } }, { "body": "<p>I prefer:</p>\n\n<pre><code>void parseLine(std::ifstream&amp; file)\n{ \n std::string line;\n while(std::getline(file, line))\n {\n // some treatment\n }\n}\n</code></pre>\n\n<p>Comments on your code:</p>\n\n<pre><code>int parseLine(std::ifstream &amp; _file)\n // ^^^ be careful with identifiers that start with _\n</code></pre>\n\n<p>Do you know all the rules? They are non trivial so best to just avoid '_' as a leading character.</p>\n\n<p>This while loop does not buy you anything.</p>\n\n<pre><code>while( std::getline( _file, line, '\\n' ).good() &amp;&amp; !_file.eof() )\n</code></pre>\n\n<p>The result of std::getline() is a reference to a stream. When used in a boolean context it will be converted to a bool automatically (using the cast operator). This conversion will call good() so there is no point in calling it manually.</p>\n\n<p>If the file is good() then eof() will not fail.</p>\n\n<p>If you always return the same value</p>\n\n<pre><code>return 0;\n</code></pre>\n\n<p>Then why have a return value.</p>\n\n<p>One thing about code it should be obvious what the code is doing with the need for extra comments. Comments mean the code is complex and needs additional explanation. But to make the code easy to read you should also use identifiers that convey some meaning.</p>\n\n<pre><code>void parseLine() // looks like it will read one line.\n</code></pre>\n\n<p>The term <code>parseLine()</code> is actually misleading here. As you don't parse a line. You parse the whole file.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T21:03:56.723", "Id": "24075", "Score": "0", "body": "Yes I do know the rules you are referring to :) my habit is to name _ variable the input variables and variable _ the output one. I pay great attention not to use capital letters there :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T03:16:26.333", "Id": "24079", "Score": "2", "body": "@gdii break your habit. I don't know anyone that wouldn't frown on that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T08:28:48.347", "Id": "24099", "Score": "0", "body": "@Dave And I can’t see why. Using underscores to prepend variable names is used in other conventions to signal class attributes. Is it bad to distinguish output parameters from input parameters?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T13:19:03.300", "Id": "24104", "Score": "0", "body": "@qdii For the most part output params are dated. That's what return values are for. That's not a 100% rule, but I only find myself making an output param _maybe_ once a year. You're solving a problem with that notation that doesn't exist. Even if output params were common, functions should be simple enough (and split apart if they aren't) and named well enough so that it's immediately evident what each param is for." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T17:33:35.823", "Id": "14796", "ParentId": "14790", "Score": "6" } }, { "body": "<p>At least IMO, the best way to read all the lines from a file is to start with a small proxy class:</p>\n\n<pre><code>class line { \n std::string data;\npublic:\n operator std::string() { return data; }\n friend std::istream &amp;operator&gt;&gt;(std::istream &amp;is, line &amp;d) { \n return std::getline(is, d.data);\n }\n};\n</code></pre>\n\n<p>Then read your lines with an <code>istream_iterator</code>, such as:</p>\n\n<pre><code>std::vector&lt;std::string&gt; lines((std::istream_iterator&lt;line&gt;(infile)),\n std::istream_iterator&lt;line&gt;());\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>std::transform(std::istream_iterator&lt;line&gt;(infile),\n std::istream_iterator&lt;line&gt;(),\n some_output_iterator,\n some_function);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T08:14:42.403", "Id": "24096", "Score": "0", "body": "+! Not bad - I've always missed a \"getline\"-type istream iterator!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T08:15:41.670", "Id": "24097", "Score": "0", "body": "By the way, what's the point of the `data` member?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T08:17:46.647", "Id": "24098", "Score": "1", "body": "@KerrekSB: It temporarily holds the line you just read, until the `line` gets converted to a `string`, which returns it. Rereading it, I've left out an important point. Will edit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T08:34:47.823", "Id": "24101", "Score": "0", "body": "By the way, your vector is temporary... is that intentional?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T08:35:25.827", "Id": "24102", "Score": "0", "body": "@KerrekSB: No, not particularly." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T04:56:21.400", "Id": "14823", "ParentId": "14790", "Score": "5" } } ]
{ "AcceptedAnswerId": "14792", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T15:40:30.407", "Id": "14790", "Score": "3", "Tags": [ "c++", "parsing" ], "Title": "Is this the right way to read every line?" }
14790
<p>I've noticed a tendency towards two styles of conditionally executing methods:</p> <ol> <li><p>Conditional before the call</p> <pre><code>def foo(thing) puts thing end if thing foo(thing) end </code></pre></li> <li><p>Conditional within the call</p> <pre><code>def foo(thing) return unless thing puts thing end foo(thing) </code></pre></li> </ol> <p>Pros of 1:</p> <ul> <li>Method is concise and easier to read</li> <li>Method can assume input is valid</li> <li>Obvious what's going on in calling code</li> </ul> <p>Pros of 2:</p> <ul> <li>Caller doesn't need to check condition every time the method is invoked</li> <li>Calling code is cleaner and easier to read</li> <li>Conditional is centralised in one location and not duplicated (DRY!)</li> </ul> <p>Anecdotally, I've noticed that most people tend to lean towards the first style. Lately I've found my self leaning towards the second style, for the pros I've given above.</p> <p>Thoughts? Any other advantages/disadvantages I've missed? Any other styles?</p>
[]
[ { "body": "<p>I think that one of the pros you listed for style 2 - \"Conditional is centralized in one location and not duplicated\" is sufficient all by itself to tip the scale to style 2.</p>\n\n<p>Non-duplication of code is a very powerful idea, particularly in a system under development. There is always the possibility that something will change. Duplicated code is very fragile, because of the possibility of overlooking one or more instances. Even if you don't overlook an instance, changing multiple instances of duplicated code is always harder than changing one single instance of non-duplicated code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T20:49:39.623", "Id": "24072", "Score": "0", "body": "Er, did you mean the opposite here: \"Even if you don't overlook an instance, changing multiple instances of duplicated code is always easier than changing one single instance of non-duplicated code.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T20:50:26.167", "Id": "24073", "Score": "0", "body": "And yes, that's one of the main reasons I'm leaning towards doing it this way. Somehow it feels a bit odd though. I thought it might be a code smell, but I wasn't sure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T20:53:35.660", "Id": "24074", "Score": "0", "body": "Fixed the reversed logic. Duh." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T17:47:56.260", "Id": "14798", "ParentId": "14791", "Score": "10" } }, { "body": "<p><strong>Option 2 is the proper direction</strong>, with some reservations. Option 2 is cleaner, implements defensive programming, and always implement the desired logic (dry).</p>\n\n<p>The reservations have to do with the actual concrete implementation. A few critical questions: Is \"if thing\" always required or is it dependent on where/when you need to check it (conditional)? With that, if the answer was conditional...at what level is that condition applicable (globally, per type of thing, per situation)?</p>\n\n<p>Even after getting all those questions answered, it is still better to implement those conditional variances into the foo() method or it's overload(s),...option 2. The rare case is where the conditional applicability is too random.</p>\n\n<p>Just a tip, follow readability. It usually steers you in the right direction.</p>\n\n<p>Also, you had noted as one of the pros for option 1 is that it is concise and easier to read. I think if you were to start to utilize the foo() method hundreds or thousands of times, you would most likely scratch that pro.</p>\n\n<p>Hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T17:41:09.833", "Id": "14836", "ParentId": "14791", "Score": "5" } }, { "body": "<p>The two options are not really two options as they are not mutually exclusive.</p>\n\n<p>You should prefer two for things that are tied closely with foo and need to be checked everytime that foo is done, you should use one where it is not always applicable to foo, but it is under these circumstances.</p>\n\n<p>IOW if all code paths include a check for x immediately before calling foo, and foo would break or take an incorrect action if x was incorrect, then put the check in foo, if on the ther hand, it is only checked 4 out of 5 times, then obviously it doesn't belong in foo.</p>\n\n<p>An additional consideration is whether foo is being called to return a result or to take an action. If to return a result, then you may be just changing one check at the call site for another, in which case it depends upon the check -- which makes more sense.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T20:30:47.047", "Id": "24695", "Score": "0", "body": "Thanks - you are right that they are not exclusive!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T20:37:33.200", "Id": "14837", "ParentId": "14791", "Score": "1" } } ]
{ "AcceptedAnswerId": "14798", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T16:33:27.203", "Id": "14791", "Score": "4", "Tags": [ "ruby" ], "Title": "Placement of Conditionals" }
14791
<p>I'm having trouble thinking of a good name for the following extension method:</p> <pre><code>public static IEnumerable&lt;T&gt; TrimOrExpand&lt;T&gt;(this T[] items, int desiredCount) { var ratio = (double)items.Length / desiredCount; for (int i = 0; i &lt; desiredCount; i++) yield return items[Convert.ToInt32(i * ratio)]; } </code></pre> <p>The thing I don't like about this method name is that "Trim" may communicate to the user that it's cutting off the last x records of the array, when actually it is excluding items at a regular interval throughout the array. Likewise it will also "Expand" the array by repeating items if you specify a count that is larger than <code>items.Length</code>.</p> <p>Is there a better technical term for what I'm trying to do? Or is <code>TrimOrExpand</code> obvious enough to understand what it does?</p>
[]
[ { "body": "<p>I think if you look at the objects within the IEnumerable as a statistical numeric value than you could use the term <a href=\"http://en.wikipedia.org/wiki/Normalization_%28statistics%29\" rel=\"nofollow\">Normalize</a>. In this case you are \"normalizing\" your values (objects) to a desired count.</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; NormalizeObjects&lt;T&gt;(this T[] items, int desiredCount)\n</code></pre>\n\n<p>If you dislike the term Objects you could replace it with Items or even Records depending on what your use case is. </p>\n\n<p>If the only thing you dislike about your current name is \"Trim\" then you could replace that term with the opposite of Expand, which I would argue is Contract.</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; ExpandOrContract&lt;T&gt;(this T[] items, int desiredCount)\n</code></pre>\n\n<p>I think either of the above are decent options based on what your method is currently doing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T19:50:47.927", "Id": "14803", "ParentId": "14800", "Score": "1" } }, { "body": "<p>Wow. That's an interesting method. I've never seen anything do quite what it does. Kudos. Though for naming, I might call it <code>ContractOrExpand</code> or <code>InterpolateOrExtrapolate</code> or something like that. The <code>Trim</code> does seem to evoke thoughts of <code>string.Trim()</code> which is totally different. And even SQL's <code>TRIM()</code>, for that matter. I feel that that bit of wording implies stuff will be chopped off at the front or back, while your method cuts stuff out at regular intervals (if need be). So, take that for what it's worth.</p>\n\n<p>On another note, you should be able to replace <code>Convert.ToInt32(i * ratio)</code> with <code>(int)(i * ratio)</code> and get the same results without the overhead of a method call. Measure if this could be performance-critical.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T19:56:05.497", "Id": "24067", "Score": "2", "body": "That's what I thought about `Convert.ToInt32()` at first, but I found out from [MSDN](http://msdn.microsoft.com/en-us/library/ffdk7eyz(v=vs.100).aspx) that it actually rounds the integer with MidpointRounding.ToEven, which I think is more desirable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T19:59:14.983", "Id": "24069", "Score": "0", "body": "Except, I tried this: `var r = new[] { \"this\", \"is\", \"a\", \"test\" }.TrimOrExpand(19);` and wound up with an `IndexOutOfRangeException` when I went through the enumeration." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T20:06:04.590", "Id": "24070", "Score": "1", "body": "Ahh.. yes `Convert.ToInt32()` can round up on the last element of the array. That's a problem. So I guess casting to int is more preferable. +1, especially for helping me test my code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T19:52:01.973", "Id": "14804", "ParentId": "14800", "Score": "1" } } ]
{ "AcceptedAnswerId": "14804", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T19:13:13.047", "Id": "14800", "Score": "2", "Tags": [ "c#", "extension-methods" ], "Title": "Filtering or repeating elements as needed" }
14800
<p>A prospective employer asked me for a code sample, but unfortunately this is the best project I've done, most of my other programs were very short (~100 lines). Should I send this in/try to refactor it? Or would it be best to send a shorter sample, or quickly write a new project?</p> <pre><code>#!/usr/bin/python import curses import letters # Letter scores and distributions import libsquares # Locations of bonus squares import random import re from optparse import OptionParser # Command-line options parser = OptionParser() parser.add_option("-c", "--challenge", action="store_true", dest="challenge", default=False, help="Enable challenges (disabled by default)") parser.add_option("-d", "--dictionary", dest="dict", default="twl", help="Choose dictionary (pick \"twl\" or \"sowpods\")") (options, args) = parser.parse_args() # Choose your dictionary if options.dict == "sowpods": dictionary = open('sowpods.txt', 'r') # SOWPODS dictionary - International else: dictionary = open('TWL06.txt', 'r') #TWL dictionary - American # -------------------------------------------- # Defines a "player" class class Player: def __init__(player, name): player.name = name player.score = 0 player.rack = [] player.index = -1 # Defines a class for a square on the board class Square: def __init__(square, x, y, multiplier): square.x = x square.y = y # Note that the multiplier gets set to 1 when a tile is placed # on the board square.multiplier = multiplier square.letter = "" square.age = -1 # Defines a class for a tile that hasn't yet been placed on the board class Tile: def __init__(tile, x, y, letter): tile.x = x tile.y = y tile.letter = letter # Defines a class for a turn. A turn object gives you the player, the # tiles used, the squares used on the board, the score of the move, # and its validity. class Turn: def __init__(turn, player, lettersUsed, squaresUsed, addedScore, validity): turn.player = player # The object "player." turn.lettersUsed = lettersUsed turn.squaresUsed = squaresUsed turn.addedScore = addedScore # Validity of a turn can be 0, 1, or 2. 0 means invalid. 1 # means valid. 2 means if you challenge it, you won't lose # your turn, but the word won't be taken off the table either. turn.validity = validity # ------------------------------------------- # Redraws the rack, which should happen every time a letter is placed. def redrawRack(rack, stdscr): for i in range(7): stdscr.delch(19, 15 + i) for i in range(len(rack)): stdscr.addch(19, 15 + i, rack[i]) # Visually shuffle the rack. def shuffleRack(rack, stdscr): random.shuffle(rack) redrawRack(rack, stdscr) # Display score def displayScore(players, numPlayers, stdscr): for i in range(70): stdscr.delch(2, 18) for i in range(numPlayers): stdscr.addstr(2, 18 + 9*i, str(players[i].score)) # Returns "1" if all words are proper Scrabble words, returns 0 if # they are not. def verifyWords(words): # First, prune word list so that no word appears more than once. # This is so the "index" function works correctly. prunedList = [] for word in words: if word in prunedList: pass else: prunedList.append(word) # Each number in the list "check" is 0 or 1, and if it's 0, the # corresponding word is invalid, and if it's 1, the corresponding # word is valid. Each word starts "invalid" and becomes valid # once it is found in the dictionary. check = [0] * len(prunedList) dictionary.seek(0) # Go to beginning of file for line in dictionary: for word in prunedList: expression = "^" + word + "\n" + "$" object = re.compile(expression) if object.match(line) != None: check[prunedList.index(word)] = 1 if check == [1] * len(prunedList): return 1 else: return 0 # Given a tile and the direction of a word that it's a part of, find # the coordinates of the first letter of the word. Also, the last # letter of the word. Note that seek only finds coordinates in one # direction. def seek(x0, y0, direction, squares): if direction == "horiz": xLeft = x0 xRight = x0 while xLeft &gt; 0 and squares[(xLeft-1, y0)].letter != "": xLeft = xLeft - 1 while xRight &lt; 14 and squares[(xRight+1, y0)].letter != "": xRight = xRight + 1 return (xLeft, xRight) elif direction == "vert": yUp = y0 yDown = y0 while yDown &lt; 14 and squares[(x0, yDown+1)].letter != "": yDown = yDown + 1 while yUp &gt; 0 and squares[(x0, yUp-1)].letter != "": yUp = yUp - 1 return (yUp, yDown) else: raise NameError('Unspecified direction') # Given a board configuration, return the score. The board # configuration specifies the age of every tile, and it returns the # score associated with all tiles of age 0. (age 0 means it was # placed on the square on that particular turn). Also it finds all # words generated by a bunch of new tiles. def findAndScore(squares): score = 0 wordList = [] # First find which tiles are new newTiles = [] for tuple in squares.keys(): if squares[tuple].age == 0: newTiles.append(squares[tuple]) # Since squares must form a word, we can take two squares and see # which coordinate they differ by, and that will give us the # direction of the word. We can count the parallel word, and then # count all the perpendicular words. If there is one square, the # direction can be horizontal. if len(newTiles) == 1: # Check to see what direction it's in, that is, where the old # tiles are. We want to find the start and end of a proposed # word both horizontally and vertically, and if the start # equals the end, it's not a word. horizRange = seek(newTiles[0].x, newTiles[0].y, "horiz", squares) vertRange = seek(newTiles[0].x, newTiles[0].y, "vert", squares) if horizRange[0] != horizRange[1]: direction = "horiz" elif vertRange[0] != vertRange[1]: direction = "vert" else: return 3 elif len(newTiles) &gt; 1: if newTiles[0].x - newTiles[1].x == 0: direction = "vert" elif newTiles[0].y - newTiles[1].y == 0: direction = "horiz" else: raise NameError('Two squares do not form a line') else: raise NameError('len(newTiles) &lt; 1') # Now we count the parallel word (we can only count this once, we # can't count it once for each letter, which is why we have to # count it separately). Make sure to check that tiles form one # continuous word. # To find the start and end of the word, we use seek: wordRange = seek(newTiles[0].x, newTiles[0].y, direction, squares) word = "" wordScore = 0 if direction == "horiz": # Check that tiles form one continuous word for tile in newTiles: if tile.x in range(wordRange[0], wordRange[1]+1): pass else: return 3 y = newTiles[0].y wordBonus = 1 # Multiply by this at the end - DW, TW for x in range(wordRange[0], wordRange[1] + 1): # Find the word word = word + squares[(x, y)].letter # Score the word - count letters first, then once the word # is formed, multiply the DW and TW scores in. letterBonus = 1 # Accounts for DL, TL bonuses letterValue = letters.score[squares[(x, y)].letter] if squares[(x, y)].age == 0: bonus = squares[(x, y)].multiplier if bonus == "DW": wordBonus = 2*wordBonus elif bonus == "TW": wordBonus = 3*wordBonus elif bonus == "DL": letterBonus = 2*letterBonus elif bonus == "TL": letterBonus = 3*letterBonus else: pass wordScore = wordScore + letterValue*letterBonus wordScore = wordScore*wordBonus elif direction == "vert": # Check that tiles form one continuous word for tile in newTiles: if tile.y in range(wordRange[0], wordRange[1]+1): pass else: return 3 x = newTiles[0].x wordBonus = 1 # Multiply by this at the end - DW, TW for y in range(wordRange[0], wordRange[1] + 1): # Find the word word = word + squares[(x, y)].letter # Score the word letterBonus = 1 letterValue = letters.score[squares[(x, y)].letter] if squares[(x, y)].age == 0: bonus = squares[(x, y)].multiplier if bonus == "DW": wordBonus = 2*wordBonus elif bonus == "TW": wordBonus = 3*wordBonus elif bonus == "DL": letterBonus = 2*letterBonus elif bonus == "TL": letterBonus = 3*letterBonus else: pass wordScore = wordScore + letterValue*letterBonus wordScore = wordScore*wordBonus else: raise NameError('Wrong direction') wordList.append(word) # Add parallel word to list of words score = score + wordScore # Now count perpendicular words in the exact same way! for tile in newTiles: word = "" wordScore = 0 if direction == "horiz": wordRange = seek(tile.x, tile.y, "vert", squares) x = tile.x wordBonus = 1 for y in range(wordRange[0], wordRange[1] + 1): # Find the word word = word + squares[(x, y)].letter # Score the word letterBonus = 1 letterValue = letters.score[squares[(x, y)].letter] if squares[(x, y)].age == 0: bonus = squares[(x, y)].multiplier if bonus == "DW": wordBonus = 2*wordBonus elif bonus == "TW": wordBonus = 3*wordBonus elif bonus == "DL": letterBonus = 2*letterBonus elif bonus == "TL": letterBonus = 3*letterBonus else: pass wordScore = wordScore + letterValue*letterBonus wordScore = wordScore*wordBonus elif direction == "vert": wordRange = seek(tile.x, tile.y, "horiz", squares) y = tile.y wordBonus = 1 for x in range(wordRange[0], wordRange[1] + 1): # Find the word word = word + squares[(x, y)].letter # Score the word letterBonus = 1 letterValue = letters.score[squares[(x, y)].letter] if squares[(x, y)].age == 0: bonus = squares[(x, y)].multiplier if bonus == "DW": wordBonus = 2*wordBonus elif bonus == "TW": wordBonus = 3*wordBonus elif bonus == "DL": letterBonus = 2*letterBonus elif bonus == "TL": letterBonus = 3*letterBonus else: pass wordScore = wordScore + letterValue*letterBonus wordScore = wordScore*wordBonus else: raise NameError('Wrong direction') if wordRange[0] != wordRange[1]: wordList.append(word) # Add perpendicular word to word list score = score + wordScore # Bingos if len(newTiles) == 7: score = score + 50 # Now we have counted all the tiles and found all the words! return [wordList, score] # Removes a turn. def removeTurn(turn, players, numPlayers, squares, stdscr): # Reset score turn.player.score = turn.player.score - turn.addedScore displayScore(players, numPlayers, stdscr) # Reset squares for square in turn.squaresUsed: square.letter = "" if (square.x, square.y) in libsquares.bonuses.keys(): color = libsquares.colors[square.multiplier] stdscr.addch(square.y, square.x, " ", curses.color_pair(color)) else: stdscr.addch(square.y, square.x, ".", curses.color_pair(1)) # Reset racks for letter in turn.lettersUsed: turn.player.rack.append(letter) redrawRack(turn.player.rack, stdscr) # Subtract from age of tiles for tuple in squares.keys(): if squares[tuple].age &gt; -1: squares[tuple].age = squares[tuple].age - 1 # Play the tiles. Tiles are written as a tile object. def playTiles(player, tiles, players, numPlayers, squares, stdscr): lettersUsed = [] squaresUsed = [] # See which letters and squares are being used for tile in tiles: lettersUsed.append(tile.letter) squaresUsed.append(squares[(tile.x, tile.y)]) # Check that at least one letter has been used if len(tiles) &lt; 1: return 3 # Check that letters are not on top of other letters for tile in tiles: if squares[(tile.x, tile.y)].letter != "": return 3 # Check that tiles are in a line if len(tiles) == 1: direction = "horiz" else: # If x coordinates are the same if tiles[0].x - tiles[1].x == 0: direction = "vert" # If y coordinates are the same elif tiles[0].y - tiles[1].y == 0: direction = "horiz" else: return 3 if direction == "horiz": # Make sure y coordinates are the same for tile in tiles: if tile.y != tiles[0].y: return 3 elif direction == "vert": # Make sure x coordinates are the same for tile in tiles: if tile.x != tiles[0].x: return 3 else: raise NameError('Wrong direction') # Check that tiles form one connected word (done in # "findAndScore") # Check to see if it's the first move. firstMove = 1 for tuple in squares.keys(): if squares[tuple].age &gt; -1: firstMove = 0 # Check that tiles link to at least one old tile, unless it's the # first move. link = 0 for tile in tiles: if tile.y + 1 &lt;= 14: if squares[(tile.x, tile.y+1)].age &gt; -1: link = 1 if tile.y - 1 &gt;= 0: if squares[(tile.x, tile.y-1)].age &gt; -1: link = 1 if tile.x + 1 &lt;= 14: if squares[(tile.x+1, tile.y)].age &gt; -1: link = 1 if tile.x - 1 &gt;= 0: if squares[(tile.x-1, tile.y)].age &gt; -1: link = 1 if link == 0 and firstMove == 0: return 3 # If it's the first move, check to see that the tiles go through # the center. if firstMove == 1: goThroughCenter = 0 for tile in tiles: if tile.x == 7 and tile.y == 7: goThroughCenter = 1 if goThroughCenter == 0: return 3 # Comment to debug # Play word (age 0) and age other tiles for tuple in squares.keys(): if squares[tuple].age &gt; -1: squares[tuple].age = squares[tuple].age + 1 for tile in tiles: squares[(tile.x, tile.y)].letter = tile.letter squares[(tile.x, tile.y)].age = 0 # Score word wordsAndScore = findAndScore(squares) wordList = wordsAndScore[0] addedScore = wordsAndScore[1] player.score = player.score + addedScore # Display score displayScore(players, numPlayers, stdscr) # Create a turn object and check validity if verifyWords(wordList) == 1: validity = 1 elif verifyWords(wordList) == 0: validity = 0 else: raise NameError('verifyWords returns neither 1 nor 0') newturn = Turn(player, lettersUsed, squaresUsed, addedScore, validity) # Remove turn if word verification is on and the word is wrong if validity == 0 and options.challenge == False: removeTurn(newturn, players, numPlayers, squares, stdscr) return 4 else: return newturn # A player takes a turn. Return a turn object and the "turnCounter" # (something indicating who is going next). def oneTurn(previousTurn, player, squares, stdscr, bag, players, numPlayers): # Announce whose turn it is stdscr.addnstr(17, 3, player.name + "'s turn", 70) # Give player a rack while len(player.rack) &lt; 7 and len(bag) &gt; 0: tile = random.choice(bag) player.rack.append(tile) bag.remove(tile) tiles = [] # Tiles the player will place on the board this turn # Display rack redrawRack(player.rack, stdscr) # Graphics stuff while 1: c = stdscr.getch() coords = stdscr.getyx() x = coords[1]; y = coords[0] # Arrow keys move the cursor (or hjkl) if c == curses.KEY_LEFT or c == 104: if x == 0: pass else: stdscr.move(y, x-1) elif c == curses.KEY_RIGHT or c == 108: if x == 79: pass else: stdscr.move(y, x+1) elif c == curses.KEY_UP or c == 107: if y == 0: pass else: stdscr.move(y-1, x) elif c == curses.KEY_DOWN or c == 106: if y == 23: pass else: stdscr.move(y+1, x) # yubn moves diagonally (nethack-style) elif c == 121: if x == 0 or y == 0: pass else: stdscr.move(y-1, x-1) elif c == 117: if x == 79 or y == 0: pass else: stdscr.move(y-1, x+1) elif c == 98: if x == 0 or y == 23: pass else: stdscr.move(y+1, x-1) elif c == 110: if x == 79 or y == 23: pass else: stdscr.move(y+1, x+1) elif c == 8 or c == 127: # Backspace - remove tile from board # Ensure that cursor is over a tile, and if so, find the # tile ourTile = 0 for tile in tiles: if tile.x == x and tile.y == y: ourTile = tile if ourTile != 0: # Repaint square on board if (x, y) in libsquares.bonuses.keys(): color = libsquares.colors[squares[(x, y)].multiplier] stdscr.addch(y, x, " ", curses.color_pair(color)) else: stdscr.addch(y, x, ".", curses.color_pair(1)) # Remove tile from tile list tiles.remove(ourTile) # Add tile to rack player.rack.append(ourTile.letter) redrawRack(player.rack, stdscr) stdscr.move(y, x) elif c == 32 or c == 115: # Space or "s" - shuffle tiles shuffleRack(player.rack, stdscr) stdscr.move(y, x) # Once a player presses Enter, that's like inputting a command. # Deal with commands accordingly. elif c == 10: # New line - submit data # Submit word if x &lt; 15 and y &lt; 15: a = playTiles(player, tiles, players, numPlayers, squares, stdscr) if a == 3: # User has made an error turnObject = previousTurn turnCounter = player # Remove stuff from the board for tile in tiles: if (tile.x, tile.y) in libsquares.bonuses.keys(): color = libsquares.colors[squares[(tile.x, tile.y)].multiplier] stdscr.addch(tile.y, tile.x, " ", \ curses.color_pair(color)) else: stdscr.addch(tile.y, tile.x, ".", \ curses.color_pair(1)) player.rack.append(tile.letter) tiles = [] redrawRack(player.rack, stdscr) elif a == 4: # User has made an invalid word (we need # a separate case because if this has happened the rack # has already been removed) turnObject = previousTurn turnCounter = player tiles = [] else: turnObject = a if player.index &lt; numPlayers - 1: turnCounter = players[player.index + 1] elif player.index == numPlayers - 1: turnCounter = players[0] else: raise NameError('Unknown player index') break elif y == 21: # On the shuffle/recall/pass line # Shuffle rack if x &gt;= 2 and x &lt;= 8: shuffleRack(player.rack, stdscr) stdscr.move(21, 2) # Recall tiles elif x &gt;= 11 and x &lt;= 16: for tile in tiles: if (tile.x, tile.y) in libsquares.bonuses.keys(): color = libsquares.colors[squares[(tile.x, \ tile.y)].multiplier] stdscr.addch(tile.y, tile.x, " ", \ curses.color_pair(color)) else: stdscr.addch(tile.y, tile.x, ".", \ curses.color_pair(1)) player.rack.append(tile.letter) tiles = [] redrawRack(player.rack, stdscr) stdscr.move(21, 11) # Exchange tiles elif x &gt;= 19 and x &lt;= 31: if len(bag) &gt;= 7: # Skip your turn if player.index == numPlayers - 1: turnCounter = players[0] else: turnCounter = players[player.index + 1] turnObject = Turn(player, [], [], 0, 2) stdscr.addstr(21, 34, "Exchange tiles:") stdscr.addstr(22, 34, "(press Enter when done or Esc to cancel)") exchange = [] while 1: c = stdscr.getch() if c == 10: # New line - submit exchanged tiles # Now add tiles from the bag while len(player.rack) &lt; 7: tile = random.choice(bag) player.rack.append(tile) bag.remove(tile) for tile in exchange: bag.append(tile) # Now erase the exchange messages from # the screen for i in range(45): stdscr.addch(21, 34 + i, " ") stdscr.addch(22, 34 + i, " ") break elif c == 8 or c == 127: # Backspace - delete a tile if len(exchange) &gt; 0: stdscr.delch(21, 50 + len(exchange) - 1) tile = exchange.pop() player.rack.append(tile) elif c == 27: # Esc (Escape) - don't exchange turnCounter = player turnObject = previousTurn for tile in exchange: player.rack.append(tile) exchange = [] for i in range(45): stdscr.addch(21, 34 + i, " ") stdscr.addch(22, 34 + i, " ") break else: if player.rack.count(chr(c)) &gt; 0: stdscr.addch(21, 50 + len(exchange), chr(c)) exchange.append(chr(c)) player.rack.remove(chr(c)) redrawRack(player.rack, stdscr) break else: stdscr.addstr(21, 34, "Less than 7 tiles left in bag") stdscr.move(21, 19) # Undo the last turn (so that it is once again the # previous player's turn) elif y == 5 and x &gt;= 20 and x &lt;= 23: removeTurn(previousTurn, players, numPlayers, squares, stdscr) turnCounter = previousTurn.player turnObject = Turn(previousTurn.player, [], [], 0, 2) stdscr.move(5, 20) break # Challenge the last turn elif y == 7 and x &gt;= 20 and x &lt;= 28: if previousTurn.validity == 0: # Player uses his turn to invalidate the other's move, # then takes another turn removeTurn(previousTurn, players, numPlayers, squares, stdscr) turnCounter = player turnObject = Turn(player, [], [], 0, 2) elif previousTurn.validity == 1: # Player doesn't get a turn if the challenged word # is valid if player.index == numPlayers - 1: turnCounter = players[0] else: turnCounter = players[player.index + 1] turnObject = Turn(player, [], [], 0, 2) elif previousTurn.validity == 2: # Then just go on as usual, nobody loses his turn. turnCounter = player turnObject = Turn(player, [], [], 0, 2) else: raise NameError('Validity not 0, 1, or 2') stdscr.move(7, 20) break # Quit the game elif y == 9 and x &gt;= 20 and x &lt;= 23: turnObject = previousTurn turnCounter = 0 stdscr.move(9, 20) break elif c == 113 and (x &gt;= 15 or y &gt;= 15): # the letter "q" turnObject = previousTurn turnCounter = 0 stdscr.move(9, 20) break else: # If on the board, assume he is adding tiles if x &lt; 15 and y &lt; 15: # Make sure tile is in rack and you are adding to a # blank space </code></pre>
[]
[ { "body": "<p>I have little experience with python, so I can't offer critique on the finer points of your code, just the big picture. That said, several things stick out to me. </p>\n\n<p>First, you have some large chunks which are duplicated two, three, or even four times (see lines 198-215). Scour through the code and extract these into their own functions. </p>\n\n<p>Second, several of your functions are <em>massively</em> too long: <code>findAndScore</code>(161 lines), <code>playTiles</code>(97 lines), <code>oneTurn</code>(228 lines). <code>findAndScore</code>, once you get rid of the previously mentioned duplication, could easily be broken into two functions: the finding and the scoring. <code>oneTurn</code> is too long simply because it contains all of the input handling. The section within the block starting at line 435 absolutely should be its own function, if not more since it clocks in at 144 lines.</p>\n\n<p>Finally, and this is more observation than critique, your classes do nothing but operate as organized data structures. This isn't necessarily a wrong approach, but it would look good if you were to refactor your code to be a bit more object oriented, especially since this is intended as a code sample.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T22:18:14.530", "Id": "14806", "ParentId": "14801", "Score": "11" } }, { "body": "<pre><code>#!/usr/bin/python\n\nimport curses\nimport letters # Letter scores and distributions\nimport libsquares # Locations of bonus squares\nimport random\nimport re\nfrom optparse import OptionParser\n\n# Command-line options\nparser = OptionParser()\nparser.add_option(\"-c\", \"--challenge\", action=\"store_true\", dest=\"challenge\",\n default=False, help=\"Enable challenges (disabled by default)\")\nparser.add_option(\"-d\", \"--dictionary\", dest=\"dict\", default=\"twl\",\n help=\"Choose dictionary (pick \\\"twl\\\" or \\\"sowpods\\\")\")\n(options, args) = parser.parse_args()\n</code></pre>\n\n<p>I'd rather see this kind of thing done in a main function rather then at the global level.</p>\n\n<pre><code># Choose your dictionary\nif options.dict == \"sowpods\":\n dictionary = open('sowpods.txt', 'r') # SOWPODS dictionary - International\nelse:\n dictionary = open('TWL06.txt', 'r') #TWL dictionary - American\n</code></pre>\n\n<p>I'm a little bothered by the fact that you simply adopt the other dictionary in an else clause rather then showing an error for an invalid dictionary.</p>\n\n<pre><code># --------------------------------------------\n# Defines a \"player\" class\nclass Player:\n def __init__(player, name):\n player.name = name\n player.score = 0\n player.rack = []\n player.index = -1\n</code></pre>\n\n<p>By convention, the first parameter to methods should be named self. This will work, but it may confused other python coders.</p>\n\n<pre><code># Defines a class for a square on the board\nclass Square:\n def __init__(square, x, y, multiplier):\n square.x = x\n square.y = y\n # Note that the multiplier gets set to 1 when a tile is placed\n # on the board\n square.multiplier = multiplier\n square.letter = \"\"\n square.age = -1\n\n# Defines a class for a tile that hasn't yet been placed on the board\nclass Tile:\n def __init__(tile, x, y, letter):\n tile.x = x\n tile.y = y\n tile.letter = letter\n\n# Defines a class for a turn. A turn object gives you the player, the\n# tiles used, the squares used on the board, the score of the move,\n# and its validity.\nclass Turn:\n def __init__(turn, player, lettersUsed, squaresUsed, addedScore, validity):\n</code></pre>\n\n<p>The python style guide recommends using lowercase_wdith_underscorse for parameter names</p>\n\n<pre><code> turn.player = player # The object \"player.\"\n turn.lettersUsed = lettersUsed\n turn.squaresUsed = squaresUsed\n turn.addedScore = addedScore\n # Validity of a turn can be 0, 1, or 2. 0 means invalid. 1\n # means valid. 2 means if you challenge it, you won't lose\n # your turn, but the word won't be taken off the table either.\n</code></pre>\n\n<p>Rather then using magic numbers, use some global constants</p>\n\n<pre><code> turn.validity = validity\n\n# -------------------------------------------\n# Redraws the rack, which should happen every time a letter is placed.\ndef redrawRack(rack, stdscr):\n for i in range(7):\n stdscr.delch(19, 15 + i)\n for i in range(len(rack)):\n</code></pre>\n\n<p>Use <code>for i, letter in enumerate(rack):</code></p>\n\n<pre><code> stdscr.addch(19, 15 + i, rack[i])\n\n# Visually shuffle the rack.\ndef shuffleRack(rack, stdscr):\n random.shuffle(rack)\n redrawRack(rack, stdscr)\n\n# Display score\ndef displayScore(players, numPlayers, stdscr):\n for i in range(70):\n stdscr.delch(2, 18)\n</code></pre>\n\n<p>Deleting the same character repeatedly seems like a bad idea</p>\n\n<pre><code> for i in range(numPlayers):\n stdscr.addstr(2, 18 + 9*i, str(players[i].score))\n\n# Returns \"1\" if all words are proper Scrabble words, returns 0 if\n# they are not.\n</code></pre>\n\n<p>Don't use 1 and 0, use True and False</p>\n\n<pre><code>def verifyWords(words):\n # First, prune word list so that no word appears more than once.\n # This is so the \"index\" function works correctly.\n prunedList = []\n for word in words:\n if word in prunedList: pass\n else: prunedList.append(word)\n</code></pre>\n\n<p>Instead of this use <code>pruned = set(words)</code> the set will take remove all the duplicates.</p>\n\n<pre><code> # Each number in the list \"check\" is 0 or 1, and if it's 0, the\n # corresponding word is invalid, and if it's 1, the corresponding\n # word is valid. Each word starts \"invalid\" and becomes valid\n # once it is found in the dictionary.\n check = [0] * len(prunedList)\n\n dictionary.seek(0) # Go to beginning of file\n\n for line in dictionary:\n for word in prunedList:\n expression = \"^\" + word + \"\\n\" + \"$\"\n object = re.compile(expression)\n if object.match(line) != None:\n</code></pre>\n\n<p>That's rather a waste of a regular expression. All you really need to check is 'word == line[:-1]`. </p>\n\n<pre><code> check[prunedList.index(word)] = 1\n</code></pre>\n\n<p>If you had used <code>for index, word in enumerate(prunedList)</code> above, you'd already have the index for this word.</p>\n\n<p>Actually, the better approach would be the read the dictionary into a large set. Then you can easily check whether a word is in that dictionary</p>\n\n<pre><code> if check == [1] * len(prunedList): return 1\n else: return 0\n</code></pre>\n\n<p>Use <code>return all(check)</code></p>\n\n<pre><code># Given a tile and the direction of a word that it's a part of, find\n# the coordinates of the first letter of the word. Also, the last\n# letter of the word. Note that seek only finds coordinates in one\n# direction.\ndef seek(x0, y0, direction, squares):\n if direction == \"horiz\":\n</code></pre>\n\n<p>I'm not a fan of string parameters like this.</p>\n\n<pre><code> xLeft = x0\n xRight = x0\n while xLeft &gt; 0 and squares[(xLeft-1, y0)].letter != \"\":\n xLeft = xLeft - 1\n while xRight &lt; 14 and squares[(xRight+1, y0)].letter != \"\":\n xRight = xRight + 1\n return (xLeft, xRight)\n\n elif direction == \"vert\":\n yUp = y0\n yDown = y0\n while yDown &lt; 14 and squares[(x0, yDown+1)].letter != \"\":\n yDown = yDown + 1\n while yUp &gt; 0 and squares[(x0, yUp-1)].letter != \"\":\n yUp = yUp - 1\n return (yUp, yDown)\n</code></pre>\n\n<p>I notice that the two halves of this function are very similiar. I'd look for a way to simplify them and combine them.</p>\n\n<pre><code> else: raise NameError('Unspecified direction')\n</code></pre>\n\n<p>That's really not what the python NameError usually means, so I wouldn't reuse that class.</p>\n\n<p>More general comments:</p>\n\n<ol>\n<li>You program is complex enough it should really split across multiple files</li>\n<li>You would do better to have more functionality in classes</li>\n<li>It would be a good idea to separate functions which update the UI from those that do logic.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T23:08:17.690", "Id": "14808", "ParentId": "14801", "Score": "10" } }, { "body": "<p><em>This started out as a comment but it quickly became too long:</em></p>\n\n<h3> Here are a few tips, in no particular order </h3>\n\n<ul>\n<li><p>For you reading pleasure, <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">The python style guide</a>.</p></li>\n<li><p>You use comments <em>a lot</em>. As a general rule, you should write code that is clear enough that you only have to use comments sparingly. Use descriptive variable names and write clear code. (For example, I shouldn't have to read through your code to make an educated guess as to the purpose of <code>stdscr</code>, or <code>c</code>). Additionally, you should include docstrings immediately after your function/class/method definitions.</p></li>\n<li><p>You repeat yourself a few times in the above code. If you find yourself writing the same/similar code over and over again, put it in a loop, or put it in a separate function.</p></li>\n<li><p>I'm not sure if your using Python 2.x or Python 3. If you're using 2.x, it's recommended that you use new-style classes that inherit from <code>object</code>: <code>class Player(object):</code> for compatability reasons. (If you're using Python 3, classes implicitly inherit from object).</p></li>\n<li><p><code>oneTurn()</code> is ridiculously long. You should break it up into separate functions. </p></li>\n<li><p>As <a href=\"https://codereview.stackexchange.com/a/14806/10285\">Danny Kirchmeier said</a>, you're classes are just containers. I would consider one of two things. 1) Used <code>namedtuples</code> to eliminate the overhead of using classes for these. 2) Restructure your code so your classes <em>do</em> have some functionality. </p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T20:59:47.207", "Id": "14822", "ParentId": "14801", "Score": "5" } } ]
{ "AcceptedAnswerId": "14806", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T19:40:13.973", "Id": "14801", "Score": "4", "Tags": [ "python", "interview-questions" ], "Title": "Is this code too messy to send to an employer as a code sample?" }
14801
<p>I would really appreciate any feedback on the back-end of my mobile application. I tried to keep an MVC pattern, where I considered the app to be my view. Perhaps an REST framework would have been good to use, but for now I am not attempting cross domain requests.</p> <p><strong>Controller</strong></p> <p>The Group Controller, that receives JSON requests and mediates all activities involved in managing a group.</p> <p>A couple notes:</p> <ol> <li><p>I have not yet added a validation step to incoming data. I plan on creating a validation class to help me with that. </p></li> <li><p>I was planing on putting said validation in the filter method.</p></li> <li><p>I still need to add some methods for <code>UPDATE</code> and <code>DELETE</code>ing groups, but this should be enough to get a feel for it.</p></li> </ol> <p></p> <pre><code>&lt;?php require_once("../model/group_model.php"); require_once("../helper_validation.php"); header('Content-type: application/json'); //controller session_start(); $group_array = array('msg' =&gt; 'Oops, we messed up. Try again soon.', 'success' =&gt; 0, 'group_action' =&gt; -1, 'session_logged in' =&gt; $_SESSION['logged_in']); if (isset($_POST['group_action']) &amp;&amp; ($_SESSION['logged_in'] === 1) &amp;&amp; isset($_SESSION['user_id'])){ capture(); } else{ echo die(json_encode($group_array)); } function capture() { $group_array['group_action'] = (int)$_POST['group_action']; direct($group_array['group_action']); } //directs action depending on registration state function direct($i) { switch ($i) { case 0: $new_group = new create_group; $new_group-&gt;create_new_group(); break; case 1: $search = new search_group; $search-&gt;initial_search_group(); break; case 2: $join = new join_group; $join-&gt;start_join_group($join-&gt;join_array); break; case 3: $search = new search_group; $search-&gt;my_search_group(); break; case 4: $join = new join_group; $join-&gt;start_unjoin_group($join-&gt;join_array); break; case 5: $search = new search_group; $search-&gt;show_one(); break; default: echo die(json_encode($group_array)); } } class create_group { public $create_group_array = array(); public function __construct() { $this-&gt;create_group_array['group_name'] = $this-&gt;filter($_POST['group_name']); $this-&gt;create_group_array['description'] = $this-&gt;filter($_POST['description']); $this-&gt;create_group_array['location_name'] = $this-&gt;filter($_POST['location']); $this-&gt;create_group_array['privacy'] = (int)$this-&gt;filter($_POST['privacy']); $this-&gt;create_group_array['lat'] = $this-&gt;filter($_POST['lat']); $this-&gt;create_group_array['lng'] = $this-&gt;filter($_POST['lng']); $this-&gt;create_group_array['state'] = $this-&gt;filter($_POST['state']); $this-&gt;create_group_array['user_id'] = (int)$this-&gt;filter($_SESSION['user_id']); $this-&gt;create_group_array['created_by_name'] = $this-&gt;filter($_SESSION['username']); if($_POST['password']!==""){ $this-&gt;create_group_array['password'] = hash('sha256', $this-&gt;filter($_POST['password'].SALT)); } } public function create_new_group() { //need to add validation with regex $this-&gt;create_group_array['action'] = 0; $create = new create_group_model($this-&gt;create_group_array); $data = $create-&gt;insert_new_group($create-&gt;input); ///after group is created, join it if($data['success']===1) { $join = new join_group; $join-&gt;start_join_group(array( 'user_id' =&gt; $this-&gt;create_group_array['user_id'], 'group_id'=&gt; (int)$data['results'][0], 'privacy' =&gt; $this-&gt;create_group_array['privacy'], 'password'=&gt; @$this-&gt;create_group_array['password'], )); } echo die(json_encode($data)); } public function filter($var) { $var = trim($var); return $var; } } class search_group{ public $search_group_array = array(); public function __construct() { //$this-&gt;search_group_array['keyword'] = $this-&gt;filter($_POST['keyword']); @$this-&gt;search_group_array['lat'] = $this-&gt;filter($_POST['lat']); @$this-&gt;search_group_array['lng'] = $this-&gt;filter($_POST['lng']); $this-&gt;search_group_array['user_id'] = (int)$this-&gt;filter($_SESSION['user_id']); @$this-&gt;search_group_array['group_id'] = (int)$this-&gt;filter($_POST['group_id']); } public function filter($var) { $var = trim($var); return $var; } //show local groups that i am not a part of public function initial_search_group() { $this-&gt;search_group_array['action'] = 1; $search_c = new search_group_model($this-&gt;search_group_array); $data = $search_c-&gt;default_list_groups(); echo json_encode($data); } ///show my groups public function my_search_group() { $this-&gt;search_group_array['action'] = 3; $search_c = new search_group_model($this-&gt;search_group_array); $data = $search_c-&gt;my_list_groups($search_c-&gt;input['user_id']); echo json_encode($data); } //show one group profile public function show_one() { $this-&gt;search_group_array['action'] = 5; $this-&gt;search_group_array['privacy'] = (int)$this-&gt;filter($_POST['privacy']); $show = new search_group_model($this-&gt;search_group_array); $data = $show-&gt;show_one($show-&gt;input['user_id'],$show-&gt;input['group_id'],(int)$show-&gt;input['privacy']); echo json_encode($data); } } class join_group { public $join_array = array(); public function __construct() { $this-&gt;join_array['user_id'] = (int)$this-&gt;filter($_SESSION['user_id' ]); @$this-&gt;join_array['group_id'] = (int)$this-&gt;filter($_POST['group_id']); $this-&gt;join_array['action'] = (int)$_POST['group_action']; @$this-&gt;join_array['privacy'] = (int)$this-&gt;filter($_POST['privacy']); if((int)$this-&gt;join_array['privacy'] !==0 ){ $this-&gt;join_array['password'] = hash('sha256', $this-&gt;filter($_POST['password'].SALT)); } } public function filter($var) { $var = trim($var); return $var; } //join group, only send info to client if they requested it with corresponding action 2/4 public function start_join_group($group) { $join_c = new join_group_model($group); $data = $join_c-&gt;join_group(); if(@$group['action']===2) { echo json_encode($data); } } public function start_unjoin_group($group) { $join_c = new join_group_model($group); $data = $join_c-&gt;unjoin_group(); if(@$group['action']===4){ echo json_encode($data); } } } ?&gt; </code></pre> <p><strong>Model</strong></p> <p>The group Model:</p> <pre><code>&lt;?php require_once("database.php"); class model { ///data is returned to the controller public $data = array( 'success'=&gt;0, 'msg' =&gt;'There was a small problem, try again soon.', 'data_type' =&gt; 'group', 'action' =&gt; '', 'results'=&gt; array(), ); //anything that will be put into the DB will be held in input public $input = array(); public $exclude =array(); public function __construct($a) { Global $db; $db-&gt;escape($a); $this-&gt;input = $db-&gt;escape($a); @$this-&gt;data['action'] = $a['action']; } //move insert and data return up here } class create_group_model extends model { public function insert_new_group($a) { Global $db; $b = $db-&gt;insert_array('group', $a, 'action'); if ($b['mysql_affected_rows']===1) { $this-&gt;data['success'] = 1; $this-&gt;data['msg'] = 'Congrats, you created a new group.'; array_push($this-&gt;data['results'], $b['mysql_insert_id']); return $this-&gt;data; } else { $this-&gt;data['success'] = 0; $this-&gt;data['msg'] = 'No group created, try again soon.'; return $this-&gt;data; } } } class search_group_model extends model { public function default_list_groups() { $this-&gt;list_groups($this-&gt;input['lat'], $this-&gt;input['lng'], 'group', 10, 30, $this-&gt;input['user_id'], 'all' ); $this-&gt;data['msg'] = 'Updated'; return $this-&gt;data; } public function custom_list_groups() {//add custom settings $this-&gt;list_groups($this-&gt;input['lat'], $this-&gt;input['lng'], 'group', 10, 10); } public function my_list_groups($id){ Global $db; //fix distance 10000 here, so it doesnt take into account distance $b = $db-&gt;def_g_list($this-&gt;input['lat'], $this-&gt;input['lng'], 'group', 10000, 30, (int)$id, 'mine'); if ($b !== 0) { $this-&gt;data['success'] = 1; while ($row = mysql_fetch_array($b, MYSQL_ASSOC)) { array_push($this-&gt;data['results'], $row); } $this-&gt;data['msg'] = 0; return ($this-&gt;data); } else { $this-&gt;data['msg'] = 'There was a small problem, try again soon.'; $this-&gt;data['success'] = 0; return ($this-&gt;data); } } public function show_one($user_id, $group_id, $privacy) { Global $db; (bool)$confirm = FALSE; if($privacy === 0){ $confirm = TRUE; }else { $confirm = FALSE; $privacy = 1; } if(!$confirm){ $s = 'group_id'; $f = 'user_group_rel'; $w = sprintf("user_id =%d AND group_id=%d",$user_id, $group_id); $b = $db-&gt;exists($s,$f,$w); if(mysql_num_rows($b) ===1 &amp;&amp; !is_num($b)) { $confirm=true; } } if($confirm){ $s = 'group_id,group_name,location_name,description, user_id,lat,lng,created_by_name,state'; $f = 'group'; $w = sprintf("group_id=%d AND privacy=%d",(int)$group_id, (int)$privacy); $b = $db-&gt;exists($s,$f,$w); if(mysql_num_rows($b) ===1 &amp;&amp; !is_int($b)) { $this-&gt;data['success'] = 1; $this-&gt;data['msg'] = 0; while ($row = mysql_fetch_array($b, MYSQL_ASSOC)) { array_push($this-&gt;data['results'], $row); } $this-&gt;data['results'][0]['people']= $this-&gt;group_mems($user_id, $group_id); $this-&gt;data['results'][0]['total_people']= $this-&gt;group_mems_count($group_id); return ($this-&gt;data); } } $this-&gt;data['msg'] = 'There was a small problem, try again soon.'; $this-&gt;data['success'] = 0; echo 'still going'; return ($this-&gt;data); } public function group_mems($me, $group_id) { Global $db; $result = array(); $q = sprintf(" SELECT t1.group_id, t2.user_id, t2.username, t2.first_name, t2.last_name, t2.user_id = %d as me FROM user_group_rel t1 LEFT JOIN users t2 ON t1.user_id = t2.user_id WHERE group_id = %d and status = 1 ORDER BY me desc", (int)$me, (int)$group_id); $b = $db-&gt;query($q); if ($b !== 0 and is_resource($b)) { while ($row = mysql_fetch_array($b, MYSQL_ASSOC)) { array_push($result, $row); } return $result; } else { return 'err'; } } public function group_mems_count($group_id) { Global $db; $result = array(); $q = sprintf(" SELECT count(t1.user_id) as people FROM user_group_rel t1 WHERE group_id = %d and t1.status = 1", (int)$group_id); $b = $db-&gt;query($q); if ($b !== 0 and is_resource($b)) { while ($row = mysql_fetch_array($b, MYSQL_ASSOC)) { array_push($result, $row); } return $result[0]['people']; } else { return 'err'; } } private function list_groups($lat, $lng, $table, $distance, $limit, $id, $whos) { Global $db; $b = $db-&gt;def_g_list($lat, $lng, $table, $distance, $limit, (int)$id, $whos); if ($b !== 0) { $this-&gt;data['success'] = 1; while ($row = mysql_fetch_array($b, MYSQL_ASSOC)) { array_push($this-&gt;data['results'], $row); } return ($this-&gt;data); } else { $this-&gt;data['msg'] = 'There was a small problem, try again soon.'; $this-&gt;data['success'] = 0; return ($this-&gt;data); } } } class join_group_model extends model { public function join_group() { Global $db; $pass = 0; if(array_key_exists('password', $this-&gt;input) &amp;&amp; strlen($this-&gt;input['password'])&gt;20) { $pass = $db-&gt;pass_check('group', $this-&gt;input['group_id'],$this-&gt;input['password'] ); } else { $pass = $db-&gt;pass_check('group', $this-&gt;input['group_id'],'NULL' ); } if($pass !==0) { array_push($this-&gt;exclude, 'password', 'action'); $b = $db-&gt;insert_array('user_group_rel',$this-&gt;input, $this-&gt;exclude); //echo print_r($b); if ($b !== 0) { $this-&gt;data['success'] = 1; $this-&gt;data['results'] = $this-&gt;input['group_id']; $this-&gt;data['msg'] = ' you joined a new group. '; return ($this-&gt;data); } else { $this-&gt;data['msg'] = 'There was a small problem, try again soon.'; $this-&gt;data['success'] = 0; return ($this-&gt;data); } } } public function unjoin_group() { Global $db; $b = $db-&gt;delete('user_group_rel', (int)$this-&gt;input['user_id'], (int)$this-&gt;input['group_id']); if ($b !== 0) { $this-&gt;data['success'] = 1; $this-&gt;data['results'] = $this-&gt;input['group_id']; $this-&gt;data['msg'] = ' you left that group. '; return ($this-&gt;data); } else { $this-&gt;data['msg'] = 'There was a small problem, try again soon.'; $this-&gt;data['success'] = 0; return ($this-&gt;data); } } } </code></pre> <p><strong>Database</strong></p> <p>Application wide database methods. Probably the most glaring mistake here is not using PDO statements.</p> <pre><code>&lt;?php require_once('../config/config.php'); class MySQLDatabase { private $connection; public $last_query; private $magic_quotes_active; private $real_escape_string_exists; function __construct() { $this-&gt;open_connection(); $this-&gt;magic_quotes_active = get_magic_quotes_gpc(); $this-&gt;real_escape_string_exists = function_exists( "mysql_real_escape_string" ); } public function open_connection() { $this-&gt;connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS); if (!$this-&gt;connection) { die("Database connection failed: " . mysql_error()); } else { $db_select = mysql_select_db(DB_NAME, $this-&gt;connection); if (!$db_select) { die("Database selection failed: " . mysql_error()); } } } public function close_connection() { if(isset($this-&gt;connection)) { mysql_close($this-&gt;connection); unset($this-&gt;connection); } } public function query($sql) { $this-&gt;last_query = $sql; $result = mysql_query($sql, $this-&gt;connection); $this-&gt;confirm_query($result); return $result; } public function escape($q) { if(is_array($q)) foreach($q as $k =&gt; $v) $q[$k] = $this-&gt;escape($v); //recursive else if(is_string($q)) { $q = mysql_real_escape_string($q); } return $q; } private function confirm_query($result) { if (!$result) { $output = "Database query failed: " . mysql_error() . "&lt;br /&gt;&lt;br /&gt;"; die( $output ); } } public function exists($s,$f, $w) { //rewrite bottom 2 functions rid of this function $q = sprintf("SELECT %s FROM %s WHERE %s LIMIT 1",$s,$f, $w); //echo $q; $result = $this-&gt;query($q); if (mysql_num_rows($result)===0) { return 0; } else if (mysql_num_rows($result)===1) { return $result; } else{ return 0; } } public function pass_check($t, $id, $p) { if ($p==='NULL'){ $q = sprintf("SELECT * FROM %s WHERE %s_id = %s AND password is NULL", $t,$t,$id); } else{ $q = sprintf("SELECT * FROM %s WHERE %s_id = %s AND password = '%s'", $t,$t,$id,$p); } $result = $this-&gt;query($q); if (mysql_num_rows($result)===0) { return (int)0; } else if (mysql_num_rows($result)&gt;0) { return $result; } } public function insert_array($table, $data, $exclude = array()) { $fields = $values = array(); if( !is_array($exclude) ) $exclude = array($exclude); foreach( array_keys($data) as $key ) { if( !in_array($key, $exclude) ) { $fields[] = "`$key`"; $values[] = "'" .$data[$key] . "'"; } } $fields = implode(",", $fields); $values = implode(",", $values); if( mysql_query("INSERT INTO `$table` ($fields) VALUES ($values)") ) { return array( "mysql_error" =&gt; false, "mysql_insert_id" =&gt; mysql_insert_id(), "mysql_affected_rows" =&gt; mysql_affected_rows(), "mysql_info" =&gt; mysql_info() ); } else { echo print_r(array( "mysql_error" =&gt; mysql_error() )); return 0; } } public function def_g_list($lat, $lng, $table, $dist, $limit, $id, $whos='all') { //either refactor to make this function more flexible or get rid of table variable $where = ''; if(is_int($id) &amp;&amp; $id&gt;0 &amp;&amp; $id &lt; 100000 &amp;&amp; $whos == 'all'){ //subquery used to display only groups the user is NOT IN- probably a better way to do this $where = sprintf(" t2.group_id NOT IN ( SELECT user_group_rel.group_id FROM user_group_rel WHERE user_group_rel.user_id =%d)", (int)$id); } else if (is_int($id) &amp;&amp; $id&gt;0 &amp;&amp; $id &lt; 100000 &amp;&amp; $whos == 'mine') { $where = 't3.user_id = ' . (int)$id; } else { echo 'fuckin fail'; return 0; } $d_formula = $this-&gt;distance_formula($lat, $lng, 't1'); //sorry for this query $q = sprintf(" SELECT t1.group_id, t1.group_name, t1.location_name, t1.description, t1.lat, t1.lng, t1.privacy,t2.people, %s FROM %s AS t1 JOIN (SELECT group_id, count(group_id) as people FROM user_group_rel GROUP BY group_id) t2 ON t1.group_id = t2.group_id JOIN (SELECT user_group_rel.group_id, user_group_rel.user_id FROM user_group_rel ) t3 ON t1.group_id = t3.group_id WHERE %s GROUP BY t1.group_id HAVING distance &lt; %s ORDER BY distance LIMIT %s", $d_formula, $table, $where,$dist, $limit ); $result = $this-&gt;query($q); if (mysql_num_rows($result)===0) { return 0; } else if (mysql_num_rows($result)&gt;0) { return $result; } } function delete($table,$uid,$cid) { $q = sprintf(' DELETE FROM `disruptly`.`%s` WHERE `%s`.`user_id` = %d AND `%s`.`group_id` = %d ',$table, $table, $uid,$table, $cid ); //echo $q; $result = $this-&gt;query($q); if ($result===0) { return 0; } else if ($result===1) { return $result; } } public function distance_formula($lat, $lng, $table) { //get rid of the round after'SELECT *,' for more accurate results $q = sprintf("round(3956 * 2 * ASIN(SQRT( POWER(SIN((%s -abs(%s.lat)) * pi()/180 / 2),2) + COS(%s * pi()/180 ) * COS(abs(%s.lat) * pi()/180) * POWER(SIN((%s - %s.lng) * pi()/180 / 2), 2) )),2) as distance ", $lat, $table, $lat, $table, $lng, $table); return $q; } } $database = new MySQLDatabase(); $db =&amp; $database; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T08:41:55.507", "Id": "24139", "Score": "0", "body": "It looks pretty good to me. Like you said, i'd convert to PDO for my database." } ]
[ { "body": "<p>If you want to apply the MVC pattern then you should learn the main <strong>OO</strong> principles (<strong>SOLID</strong> is a great word for this). The actual state of your code smells. <strong>Global</strong> variables half OO and half <strong>procedural</strong> style and you are creating <strong>GOD objects</strong> whish is really bad.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T10:54:08.873", "Id": "14846", "ParentId": "14809", "Score": "1" } }, { "body": "<p>Try to avoid the <code>include/require_once</code> functions. These are much slower than their counterparts, for obvious reasons. This may not be as noticeable when only importing a few files, but it is still good practice not to use them as you should always know if you have already included a file.</p>\n\n<p>This code looks like it is generating errors that are probably preventing it from even working. If you are starting sessions, then you should almost always have the <code>session_start()</code> call as the first function to avoid headers being sent to the page prematurely. The only exception I can think of, off the top of my head, is when you have persistent classes and need to include those class files before calling the session to maintain persistence.</p>\n\n<p>An \"array\" suffix is typically unnecessary. I'm not going to say to remove it, just pointing it out. This is purely a stylistic choice.</p>\n\n<p>Before using a session variable it is usually advisable to ensure that variable has been set by using the <code>isset()</code> function on it. Otherwise you will get NULL pointers and perhaps silent warnings about the array index being out of bounds or something.</p>\n\n<p>I believe you are recreating a boolean with your <code>$_SESSION[ 'logged_in' ]</code> variable. It stands to reason that there are only two possible states for this variable, TRUE or FALSE. I'm assuming you are using 1 and 0 or -1. Either way, the TRUE/FALSE pair are better and do not require any sort of type conversion, meaning you can do something like this.</p>\n\n<pre><code>if( $_SESSION[ 'logged_in' ] ) {\n //user logged in\n}\nif( ! $_SESSION[ 'logged_in' ] ) {//more appropriately \"else\" in this context\n //user not logged in\n}\n</code></pre>\n\n<p>How are you accessing the <code>$group_array</code> outside of its scope? This smells like a global, which are EXTREMELY BAD. If you need to access a variable inside a function, then it should be passed in as a parameter and then returned to be added on to it. Or you could use referencing, but I tend to stay away from those for legibility reasons. Of course there are other methods, such as using session variables, cookies, post and get. The situation will determine which method you use. Just remember, globals are bad. From this point forward, pretend you have never heard of the word. In no context could I ever see globals being necessary or good. They are old and full of security issues.</p>\n\n<p>You should also try to avoid <code>die()</code> as it is a very inelegant way of escaping a sequence. Typically this is seen a lot when an error occurs and the proper way would be to log that error then redirect the user to an error page that informs the user that an error has occurred. In this context perhaps it is ok as it is \"creating\" a JSON document, but in other cases this may not be the case. Also, echo is unnecessary, <code>die()</code> automagically prints the output of whatever parameters it receives.</p>\n\n<p>If your PHP version is >= 5.2 you can use <code>filter_input()</code> on your POST data to filter and sanitize it.</p>\n\n<pre><code>$action = filter_input( INPUT_POST, 'group_action', FILTER_SANITIZE_NUMBER_INT );\n</code></pre>\n\n<p>Your <code>direct()</code> function is a little confusing. The biggest problem I have here is your switch statement. They do not always need to be passed integers, you can pass it strings as well, and I believe this would be much easier to follow if it did use strings. Another issue I am having is all of this repetition. This is somewhat related to SOLID, what Peter Kiss mentioned in his answer. \"Don't Repeat Yourself\" (DRY) Principle. As the name implies, you code should not repeat, but be reused for maximum efficiency. The SOLID Principles are similar and very useful to remember when learning OOP. Here, and later, you are violating the DRY Principle. You create the same objects in a couple of these cases, only the methods change. There's got to be some way around this. With a numerical switch it would be easier, but you would lose legibility; With a string value you would need to do some fancy work with arrays or REGEX. Additionally, when creating a new object, you should do so using the proper syntax, <code>new object();</code>, note the parenthesis. Below is how you could rewrite this with the numerical switch, but I still think it would be better to use a string.</p>\n\n<pre><code>if( $i == 1 ) {\n $obj = new create_group();\n} else if( $i &gt; 1 ) {\n if( $i &lt; 3 ) {\n $obj = new search_group();\n } else {\n $obj = new join_group();\n }\n}\n</code></pre>\n\n<p>The way you are currently assigning your associative indices to your arrays is very tedious and inefficient. You use the proper way later in your code, but not consistently. Its only when you are redefining indices or adding to a preexisting array that you need to define each element separately. Unless you had a lot of indices you wished to add or redefine, then it would be better to create a new array and merge the two after you are done.</p>\n\n<pre><code>$this-&gt;create_group_array = array(\n 'group_name' =&gt; $this-&gt;filter( $_POST[ 'group_name' ] ),\n 'description' =&gt; $this-&gt;filter( $_POST[ 'description' ] ),\n //etc...\n);\n//OR for preexisting arrays\n$temp = array(\n 'group_name' =&gt; 'new group name',\n //more changes or additions\n);\n$this-&gt;create_group_array = array_merge(\n $this-&gt;create_group_array,\n $temp\n);\n</code></pre>\n\n<p>DON'T use error suppression! This is a sign of bad code. Maybe in production code where you are debugging this would be fine, but in live code, these should be removed.</p>\n\n<p>I'm going to stop here. There's a lot of code, and a lot of the same issues. I skimmed some of the rest, but nothing else really caught my eye. The biggest thing I see is that there is no need for these classes, at least not as they are. They are just glorified data repositories. You could more easily accomplish this with normal functions, not to mention the amount of processing you would save due to the code reuse this would open up. For instance, you have a <code>filter()</code> method in each of the classes I looked at. How many other \"shared\" resources would there be? Classes are good, but only if they follow proper OOP principles, otherwise they just add overhead and hinder development.</p>\n\n<p>In the future, I would suggest splitting up large posts, there is just entirely too much here. If you had posted just a few (no more than four) classes, then not as many people would be intimidated by this post and would be more likely to help.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T17:45:02.020", "Id": "24181", "Score": "0", "body": "+1. And \"If you had posted just a few (no more than four) classes, then not as many people would be intimidated by this post and would be more likely to help.\" For the past four days I've been eyeing this question. Luckily someone answered it. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-07T01:49:28.183", "Id": "24974", "Score": "0", "body": "Thank you very much for your reply. It was both informative and helpful. If you had any further thoughts on the model, it would be greatly appreciated, but you've already said more than enough to take me a long way in the right direction." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T17:29:09.533", "Id": "14909", "ParentId": "14809", "Score": "1" } } ]
{ "AcceptedAnswerId": "14909", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T23:48:57.010", "Id": "14809", "Score": "1", "Tags": [ "php", "object-oriented", "mvc", "json" ], "Title": "PHP backend for an HTML5/JS mobile app" }
14809
<p>This is a function that checks that when users register into the site, they only create one single account per email. The little twist is that <strong>all emails in the DB are hashed with unique salts</strong> (=<em>Input2</em>). Because <strong>hashing the new mail input with all unique salts</strong> (=<em>STEP 2</em>) will be horribly slow, I keep a <strong>"diggest" version of emails</strong> (=<em>Input3</em>) in my DB. The diggest emails are a shorter and useless version of the emails. For example, John@gmail.com becomes jo@gm.com. The goal of that is diggest version is to <strong>reduce the number of emails to check in the DB</strong> (=<em>STEP 1</em>).</p> <p>This function works pretty well but I'm afraid it will became very slow when DB becomes bigger.</p> <p>Here is the code of the portion relevant to the problem:</p> <pre><code>$Requete1 = mysql_query("SELECT Input2 as email_test, Salt as salt FROM utilisateurs WHERE Input3='$email_diggest'"); //Step 1 if(mysql_num_rows($Requete1) == 0) { echo "No problem baby"; } //Step 2 while($row = mysql_fetch_assoc($Requete1)) { $email_test = $row['email_test']; $salt = $row['salt']; $hash_email = base64_encode(pbkdf2($Email, $salt, 100000, 32)); if($email_test == $hash_email) { echo "An account already exist with that email"; }else { echo "No problem baby"; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T09:11:42.413", "Id": "24085", "Score": "1", "body": "Why would you hash the email? If you need the email in plain text, just keep the email in plain text. Emails aren't particularly sensitive information." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T09:13:35.840", "Id": "24086", "Score": "0", "body": "You can see why here: http://programmers.stackexchange.com/questions/161301/registration-email-hash-and-verifying-only-one-account-per-email" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T09:26:15.413", "Id": "24087", "Score": "0", "body": "I have to agree with the side that was responding that you've gone a step too far. A compromised email address (*not* email address *and* password) is by no means the end of the world. Nevertheless, later I'll write a full response if no one beats me to it." } ]
[ { "body": "<p>I have to agree with Corbin, while I would be annoyed if my email address got leaked, I would not be overly concerned. Spam filters are pretty decent now, and without a password all they can do is spam me. Or, if I have a gmail account, WoW hackers can find more loopholes that allows them to spam FROM my address. I don't even play WoW anymore, I wish they'd just leave me alone -.- Anyways...</p>\n\n<p>This looks like sample code, so there's not much I can help with. I would suggest that you be sure to escape early whenever possible. For instance, in the first if statement. This ensures there is no wasted processes parsing code that ins't necessary. Also, not sure how much of a difference this would make, but I believe your email comparison should be absolute, not loose.</p>\n\n<pre><code>if( $email_test === $hash_email ) {\n</code></pre>\n\n<p>Only other thing I can think of is using <code>extract()</code> to get those array indices. But there's a couple of problems with that. First, its not always well liked by the community. Second, it dumps the entire array index list into the function's local variable scope, which is sometimes unnecessary and may lead to security issues. I only bring this up because if these are the only two fields in this table then there shouldn't be any issues here. As for speed, I'm not sure, you'd have to profile it.</p>\n\n<p>The biggest thing here is premature optimization. Yes, its nice to plan ahead, but ask yourself this: How likely is it that your database will ever reach a size where this will become an issue? Every developer dreams that their creation will be the next biggest thing and will have millions of viewers, but the likelihood is slim. Plus, with regular maintenance and periodic deletion of inactive accounts will help ensure that the size, even in these extreme cases, is less likely to become a factor.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T09:26:31.047", "Id": "24144", "Score": "0", "body": "You sir, have just made a very good point." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T21:55:47.993", "Id": "14878", "ParentId": "14814", "Score": "1" } } ]
{ "AcceptedAnswerId": "14878", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T09:10:31.523", "Id": "14814", "Score": "2", "Tags": [ "php", "performance", "sql", "email" ], "Title": "Single-account-per-email verification" }
14814
<p>This is part of the code from a spectral subtraction algorithm. I'm trying to optimize it for Android.</p> <p><strong>Matlab code:</strong></p> <pre><code>function Seg=segment(signal,W,SP,Window) % SEGMENT chops a signal to overlapping windowed segments % A= SEGMENT(X,W,SP,WIN) returns a matrix which its columns are segmented % and windowed frames of the input one dimentional signal, X. W is the % number of samples per window, default value W=256. SP is the shift % percentage, default value SP=0.4. WIN is the window that is multiplied by % each segment and its length should be W. the default window is hamming % window. % 06-Sep-04 % Esfandiar Zavarehei if nargin&lt;3 SP=.4; end if nargin&lt;2 W=256; end if nargin&lt;4 Window=hamming(W); end Window=Window(:); %make it a column vector L=length(signal); SP=fix(W.*SP); N=fix((L-W)/SP +1); %number of segments Index=(repmat(1:W,N,1)+repmat((0:(N-1))'*SP,1,W))'; hw=repmat(Window,1,N); Seg=signal(Index).*hw; </code></pre> <p><strong>Java code:</strong></p> <pre><code>public class MatrixAndSegments { public int numberOfSegments; public double[][] res; public MatrixAndSegments(int numberOfSegments,double[][] res) { this.numberOfSegments = numberOfSegments; this.res = res; } } public MatrixAndSegments segment (double[] signal_in,int samplesPerWindow, double shiftPercentage, double[] window) { //default shiftPercentage = 0.4 //default samplesPerWindow = 256 //W //default window = hanning int L = signal_in.length; shiftPercentage = fix(samplesPerWindow * shiftPercentage); //SP int numberOfSegments = fix ( (L - samplesPerWindow)/ shiftPercentage + 1); //N double[][] reprowMatrix = reprowtrans(samplesPerWindow,numberOfSegments); double[][] repcolMatrix = repcoltrans(numberOfSegments, shiftPercentage,samplesPerWindow ); //Index=(repmat(1:W,N,1)+repmat((0:(N-1))'*SP,1,W))'; double[][] index = new double[samplesPerWindow+1][numberOfSegments+1]; for (int x = 1; x &lt; samplesPerWindow+1; x++ ) { for (int y = 1 ; y &lt; numberOfSegments + 1; y++) //numberOfSegments was 3 { index[x][y] = reprowMatrix[x][y] + repcolMatrix[x][y]; } } //hamming window double[] hammingWindow = this.HammingWindow(samplesPerWindow); double[][] HW = repvector(hammingWindow, numberOfSegments); double[][] seg = new double[samplesPerWindow][numberOfSegments]; for (int y = 1 ; y &lt; numberOfSegments + 1; y++) { for (int x = 1; x &lt; samplesPerWindow+1; x++) { seg[x-1][y-1] = signal_in[ (int)index[x][y]-1 ] * HW[x-1][y-1]; } } MatrixAndSegments Matrixseg = new MatrixAndSegments(numberOfSegments,seg); return Matrixseg; } public int fix(double val) { if (val &lt; 0) { return (int) Math.ceil(val); } return (int) Math.floor(val); } public double[][] repvector(double[] vec, int replications) { double[][] result = new double[vec.length][replications]; for (int x = 0; x &lt; vec.length; x++) { for (int y = 0; y &lt; replications; y++) { result[x][y] = vec[x]; } } return result; } public double[][] reprowtrans(int end, int replications) { double[][] result = new double[end +1][replications+1]; for (int x = 1; x &lt;= end; x++) { for (int y = 1; y &lt;= replications; y++) { result[x][y] = x ; } } return result; } public double[][] repcoltrans(int end, double multiplier, int replications) { double[][] result = new double[replications+1][end+1]; for (int x = 1; x &lt;= replications; x++) { for (int y = 1; y &lt;= end ; y++) { result[x][y] = (y-1)*multiplier; } } return result; } public double[] HammingWindow(int size) { double[] window = new double[size]; for (int i = 0; i &lt; size; i++) { window[i] = 0.54-0.46 * (Math.cos(2.0 * Math.PI * i / (size-1))); } return window; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T13:09:12.063", "Id": "24377", "Score": "0", "body": "you could start by flattening your `double[][]` to `double[]`. If every little bit counts, there's some RAM and speed you can gain by it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T13:25:13.740", "Id": "24433", "Score": "0", "body": "does it need optimization for android? have you profiled the code?" } ]
[ { "body": "<p>I don't have a clue about spectral subtraction, so just some minor, general notes about code:</p>\n\n<ol>\n<li><blockquote>\n<pre><code>public int fix(double val) {\n if (val &lt; 0) {\n return (int) Math.ceil(val);\n }\n return (int) Math.floor(val);\n}\n</code></pre>\n</blockquote>\n\n<p>It should be called <a href=\"https://en.wikipedia.org/wiki/Floor_and_ceiling_functions#Truncation\"><code>truncate</code></a>.</p></li>\n<li><p>A few variables could be renamed to follow the Java code conventions. </p>\n\n<ul>\n<li>Variables, parameters:\n<ul>\n<li><code>signal_in</code> to <code>inputSignal</code> or signal</li>\n<li><code>HW</code> to <code>hw</code></li>\n<li><code>seg</code> maybe to <code>segments</code> or <code>segment</code> (?)</li>\n<li><code>Matrixseg</code> to <code>matrixSeg</code></li>\n</ul></li>\n<li>Methods:\n<ul>\n<li><code>HammingWindow</code> to <code>calculateHammingWindow</code></li>\n</ul></li>\n</ul>\n\n<p>(<em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em> and <a href=\"http://docs.oracle.com/javase/specs/\">The Java Language Specification, Java SE 7 Edition, 6.1 Declarations</a>).</p></li>\n<li><p>This comments looks unnecessary:</p>\n\n<blockquote>\n<pre><code>// hamming window\ndouble[] hammingWindow = this.HammingWindow(samplesPerWindow);\n</code></pre>\n</blockquote>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p>\n\n<p>The <code>this.</code> prefix also unnecessary.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T14:35:20.433", "Id": "76022", "Score": "1", "body": "`hw` could have a better name. I don't know why he have `hammingWindows` and then `HW`, when it's looks like the same thing but does not represent the same data (`double[]` vs `double[][]`). Maybe switch the two name so that the one who is used more often would have a complete name ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T06:31:06.070", "Id": "43904", "ParentId": "14815", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T10:21:23.987", "Id": "14815", "Score": "7", "Tags": [ "java", "optimization", "android", "mathematics", "matrix" ], "Title": "Optimizing code from spectral subtraction algorithm" }
14815
<p>I have the two functions that calculate whether or not a given coordinate (x, y) is a diagonal or anti-diagonal of another coordinate that is a power of 2. In other words if (x+/-k, y+/-k) == (cx, cy) where cx or cy is a power of 2, then the binary representation of (x+/-k, y+/-k) follows known patterns.</p> <ul> <li>In case of minor diagonals, the binary representation of the product contains at most two 1s.</li> <li>In case of major diagonals, the binary representation could contain any number of 1s (could be none) and has to end with at least one 0.</li> </ul> <p>These functions are called on very large numbers that have around 5,000,000 bits and have become the most expensive call path. They end up taking 60% of the algorithm time and desperately need to be optimized.</p> <p>Here are the functions.</p> <pre><code>/// &lt;summary&gt; /// A look up array of bit counts for the numbers 0 to 255 inclusive. /// Declared static for performance. /// &lt;/summary&gt; public static readonly byte [] BitCountLookupArray = new byte [] { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, }; /// &lt;summary&gt; /// Checks to see if this cell lies on a minor diagonal of a power of 2. /// The condition is met if the binary representation of the product contains /// at most two 1s. /// &lt;/summary&gt; public bool IsDiagonalMinorToPowerOfTwo () { int sum = 0; // this.X and this.Y are BigInteger types. byte [] bytes = (this.X + this.Y).ToByteArray(); for (int i=0; i &lt; bytes.Length; i++) { sum += BitCountLookupArray [bytes [i]]; if (sum &gt; 2) { return (false); } } return (true); } /// &lt;summary&gt; /// Checks to see if this cell lies on a major diagonal of a power of 2. /// The binary representation could contain any number of consecutive 1s /// (could be none) and has to end with at least one 0. /// ^[0]*[1]*[0]+$ denotes the regular expression of the binary pattern /// we are looking for. /// &lt;/summary&gt; public bool IsDiagonalMajorToPowerOfTwo () { byte [] bytes = null; bool moreOnesPossible = true; System.Numerics.BigInteger number = 0; number = System.Numerics.BigInteger.Abs(this.X - this.Y); if ((number == 0) || (number == 1)) { // 00000000 &amp;&amp; 00000001 return (true); } else { // The last bit should always be 0. //if (number.IsEven) { bytes = number.ToByteArray(); for (int b=0; b &lt; bytes.Length; b++) { if (moreOnesPossible) { switch (bytes [b]) { case 001: // 00000001 case 003: // 00000011 case 007: // 00000111 case 015: // 00001111 case 031: // 00011111 case 063: // 00111111 case 127: // 01111111 case 255: // 11111111 { // So far so good. // Carry on testing subsequent bytes. break; } case 128: // 10000000 case 064: // 01000000 case 032: // 00100000 case 016: // 00010000 case 008: // 00001000 case 004: // 00000100 case 002: // 00000010 case 192: // 11000000 case 096: // 01100000 case 048: // 00110000 case 024: // 00011000 case 012: // 00001100 case 006: // 00000110 case 224: // 11100000 case 112: // 01110000 case 056: // 00111000 case 028: // 00011100 case 014: // 00001110 case 240: // 11110000 case 120: // 01111000 case 060: // 00111100 case 030: // 00011110 case 248: // 11111000 case 124: // 01111100 case 062: // 00111110 case 252: // 11111100 case 126: // 01111110 case 254: // 11111110 { moreOnesPossible = false; break; } default: { return (false); } } } else { if (bytes [b] &gt; 0) { return (false); } } } } //else { //return (false); } } return (true); } </code></pre> <p>I've done all I can to optimize these functions and am now at a loss for ideas. By the way, I've also cached the <code>byte []</code> for the BigInteger which is not reflected here.</p> <p><strong>NOTE:</strong> I'm not even sure if these binary patterns can be detected using some other more efficient algorithm. For those interested in context, I wrote these functions based on joriki's answer <a href="https://math.stackexchange.com/a/179144/31055">here</a>.</p>
[]
[ { "body": "<p>The patterns I see are probably better produced by bit-shifting than by hard-coding:</p>\n\n<pre><code> ...\n bytes = number.ToByteArray();\n foreach (byte b in bytes)\n {\n byte temp = 0;\n if (moreOnesPossible)\n {\n while(temp != 255 &amp;&amp; moreOnesPossible)\n {\n temp = (temp &lt;&lt; 1) + 1;\n if(b == temp)\n continue;\n\n byte shift = 0;\n do{\n if(bytes[b] == (temp &lt;&lt; ++shift))\n {\n moreOnesPossible = false;\n break;\n }\n } while(temp &lt;&lt; shift &lt; 128)\n }\n }\n else\n {\n if (bytes [b] &gt; 0)\n return (false);\n }\n }\n ...\n</code></pre>\n\n<p>For the absolute best performance speed, I'd recommend a Dictionary of all possible values and whether they are the pattern you're looking for or not. The Dictionary has to be hard-coded or generated as a one-time cost, but once it is you get constant access time making the whole thing not only linear-time and very fast, but rather elegant:</p>\n\n<pre><code> ...\n bytes = number.ToByteArray();\n foreach (byte b in bytes)\n {\n if (moreOnesPossible)\n {\n if(!validPatterns[b])\n {\n moreOnesPossible = false;\n continue;\n } \n }\n else\n {\n if (b &gt; 0)\n return (false);\n }\n }\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T21:55:04.077", "Id": "14818", "ParentId": "14817", "Score": "3" } } ]
{ "AcceptedAnswerId": "14818", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T21:21:43.360", "Id": "14817", "Score": "4", "Tags": [ "c#", "performance", ".net" ], "Title": "Optimizing function that searches for binary patterns" }
14817
<p>Fairly new to jquery, can i improve this code please?</p> <h2>HTML</h2> <pre><code>&lt;a href="#" class="dialog" id="login"&gt;login&lt;/a&gt; </code></pre> <h2>Javascript</h2> <pre><code>function Dialog() { // Event handler for a dialog click. $('a.dialog').click(function () { var dialog = $("#" + this.id + "_dialog"); // Bind the hide functions here, as the elements have now been loaded into the DOM. $("#overlay, #close").click(function () { HideDialog(dialog) }); window.onresize = function () { CentreBoxInViewport(dialog); }; SetupDialog(dialog); return false; }); // Event handler for an image click. $('div.status &gt; a').click(function () { // Get the object for the lightbox. var dialog = $("#lightbox"); // Get the path to the image. var path = this.getAttribute("href"); // Bind the hide functions here, as the elements have now been loaded into the DOM. $("#overlay, #close").click(function () { HideDialog(dialog) }); window.onresize = function () { CentreBoxInViewport(dialog); }; SetupLightBox(path, dialog); return false; }); } function SetupLightBox(path, dialog) { // Create a new image. var image = new Image(); // The onload function must come before we set the image's src, see link for explanation. // http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called. // Anonymous function set to onload event, to make sure we only proceed if the image has been loaded. image.onload = function () { $('#image').attr('src', path) CentreBoxInViewport(dialog); ShowOverlay(dialog); }; // Set the src, and show the image. image.src = path; } function SetupDialog(dialog) { CentreBoxInViewport(dialog); ShowOverlay(dialog); } function ShowDialog(dialog) { dialog.fadeTo(200, 1); } function HideDialog(dialog) { dialog.fadeTo(200, 0, function () { dialog.hide(); HideOverlay(); }); } function ShowOverlay(dialog) { $('#overlay').fadeTo(200, 0.5, function () { ShowDialog(dialog) }); } function HideOverlay() { $('#overlay').fadeTo(200, 0, function () { $('#overlay').hide(); }); } function CentreBoxInViewport(dialog) { // Get the dimensions of the viewport. var height = $(window).height() var width = $(window).width(); // Calculate the position of the lightbox. var boxtop = (height / 2) - dialog.height() / 2; var boxleft = (width / 2) - dialog.width() / 2; // Position the box. dialog.css({ top: boxtop, left: boxleft }); } </code></pre>
[]
[ { "body": "<ul>\n<li><p>In JavaScript it is custom to give functions names that start with a lowercase letter so that they are not confused with objects.</p></li>\n<li><p>Personally I'd avoid \"hardcoding\" the connection of the id of the link with the id of the dialog. (<code>login</code> -> <code>login_dialog</code>). Instead you could use the <code>href</code> of the link to refer to dialog. Example: </p>\n\n<p><code>&lt;a href=\"#login_dialog\" class=\"dialog\"&gt;login&lt;/a&gt;</code></p>\n\n<p><code>var dialog = $(this.href.replace(/.*(?=#[^\\s]*$)/, ''));</code></p></li>\n</ul>\n\n<p>(The <code>replace</code> is necessary due to bugs in IE &lt; 8)</p>\n\n<ul>\n<li>You are repeatedly assigning the click and resize event handler on each click, so that each time a dialog is shown a additional handler is added, but never removed.</li>\n</ul>\n\n<p>(There is more, however I don't have time right now. Maybe I'll come back later)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T10:58:38.603", "Id": "14847", "ParentId": "14826", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T09:01:07.163", "Id": "14826", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Can I improve my jquery dialog code, critisicm welcome" }
14826
<p>Here's the exercise:</p> <blockquote> <p>Given a string of X's and O's and a maximum number of swaps, determine the longest possible sequence of X's after swaps.</p> </blockquote> <p>Here's my solution using itertools.</p> <pre><code>import itertools as iter def swaps_gen(s): '''This generator yields all the possible outcome of applying one swap to the input string''' X_positions = [i[0] for i in enumerate(s) if i[1] == "X"] O_positions = [i[0] for i in enumerate(s) if i[1] == "O"] for x in X_positions: tmp_x = X_positions[:] tmp_o = O_positions[:] tmp_x.remove(x) tmp_o.append(x) for o in O_positions: ttmp_x = tmp_x[:] ttmp_o = tmp_o[:] ttmp_o.remove(o) ttmp_x.append(o) s = [] for i in ttmp_x: s.insert(i, "X") for i in ttmp_o: s.insert(i, "O") yield "".join(s) def flatten(l): '''flatten one level. [[a], [b, c]] --&gt; [a, b, c]''' return iter.chain.from_iterable(l) def max_x_after_swap(s, n): '''repeat the generate swap_gen n times. I used a set() to avoid duplicates. Then returns the highest number of consecutive "X"s it finds.''' outcomes = [s] while n &gt; 0: outcomes = set(flatten([list(swaps_gen(x)) for x in outcomes])) n -= 1 return max(map(nbr_of_consecutive_x, outcomes)) def nbr_of_consecutive_x(s): '''return the number of consecutive "X" ''' return max([len(list(v)) for k, v in iter.groupby(s) if k == "X"]) def main(): input = "XXOXOXOXO" swaps_nbr = 2 print(max_x_after_swap(input, swaps_nbr)) main() </code></pre> <p>Any criticism is welcome. It'd be great if you could point out any anti-pattern I may present, or show me better (by <em>better</em> I mean <em>more pythonic</em>) way to do things. I am more interested in improving my Python style than improving my algorithm.</p> <p>I used Python3.1 to run the above.</p>
[]
[ { "body": "<pre><code>import itertools as iter\n</code></pre>\n\n<p>I dislike abbrevations like this. Itertools is widely used within the python community, and it only hinders code readability by using <code>iter</code> instead of <code>itertools</code></p>\n\n<pre><code>def swaps_gen(s):\n '''This generator yields all the possible outcome of applying one swap\n to the input string'''\n X_positions = [i[0] for i in enumerate(s) if i[1] == \"X\"]\n O_positions = [i[0] for i in enumerate(s) if i[1] == \"O\"]\n</code></pre>\n\n<p>PEP 8 recommends lowercase_with_underscores for local variable names. Your comprehensions would be more clearly written as</p>\n\n<pre><code>X_positions = [index for index, value in enumerate(s) if value == 'X']\n</code></pre>\n\n<p>Because you do it twice, I'd consider writing a function</p>\n\n<pre><code> for x in X_positions:\n tmp_x = X_positions[:]\n tmp_o = O_positions[:]\n</code></pre>\n\n<p>I despise uses of tmp in variable names. All variables are temporary.</p>\n\n<pre><code> tmp_x.remove(x)\n tmp_o.append(x)\n</code></pre>\n\n<p>That's going to be expensive. The remove has to move the whole list back to make it fit.</p>\n\n<pre><code> for o in O_positions:\n ttmp_x = tmp_x[:]\n ttmp_o = tmp_o[:]\n</code></pre>\n\n<p>Especially egregious is using tmp again with an extra t.</p>\n\n<pre><code> ttmp_o.remove(o)\n ttmp_x.append(o)\n\n s = []\n</code></pre>\n\n<p>I wouldn't reuse s from before</p>\n\n<pre><code> for i in ttmp_x: s.insert(i, \"X\")\n for i in ttmp_o: s.insert(i, \"O\")\n</code></pre>\n\n<p>Inserts may be expensive. It won't be so bad here because your inserts will be in mostly sorted order. But the one unsorted element in each list will cost you somewhat.</p>\n\n<pre><code> yield \"\".join(s)\n</code></pre>\n\n<p>Your whole approach here is a bit awkward. I'd suggest something like</p>\n\n<pre><code>for x_index in x_positions:\n for y_index in y_positions:\n swapped_list = list(s) # copy string into list, so I can modify it\n swapped_list[x_index], swapped_list[y_index] = swapped_list[y_index],swapped_list[x_index] # swap elements\n yield ''.join(swapped_list) # back to list\n</code></pre>\n\n<p>Shorter and probably more efficient.</p>\n\n<pre><code>def flatten(l):\n '''flatten one level. [[a], [b, c]] --&gt; [a, b, c]'''\n return iter.chain.from_iterable(l) \n\ndef max_x_after_swap(s, n):\n '''repeat the generate swap_gen n times.\n I used a set() to avoid duplicates.\n Then returns the highest number of consecutive \"X\"s it finds.'''\n</code></pre>\n\n<p>PEP 257 recommends using \"\"\" not ''' for docstrings. Also, the closing ''' should be on a line by itself</p>\n\n<pre><code> outcomes = [s]\n</code></pre>\n\n<p>I'd make this a set, just for consistency with the next line</p>\n\n<pre><code> while n &gt; 0:\n</code></pre>\n\n<p>Why a while loop instead of a for loop?</p>\n\n<pre><code> outcomes = set(flatten([list(swaps_gen(x)) for x in outcomes]))\n</code></pre>\n\n<p>I'd use <code>outcomes = set(flatten(map(swaps_gen, outcomes)))</code> There is no reason to use list here, as the generator will flatten just fine.</p>\n\n<pre><code> n -= 1\n return max(map(nbr_of_consecutive_x, outcomes))\n\ndef nbr_of_consecutive_x(s):\n</code></pre>\n\n<p>I dislike abbreviation like nbr, I'd call this <code>count_of_consecutive_x</code></p>\n\n<pre><code> '''return the number of consecutive \"X\" '''\n return max([len(list(v)) for k, v in iter.groupby(s) if k == \"X\"])\n</code></pre>\n\n<p>You don't need the [], because max will take a generator expression just fine</p>\n\n<pre><code>def main():\n input = \"XXOXOXOXO\"\n swaps_nbr = 2\n print(max_x_after_swap(input, swaps_nbr))\n\nmain()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T14:41:29.917", "Id": "14830", "ParentId": "14827", "Score": "3" } } ]
{ "AcceptedAnswerId": "14830", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T10:01:52.837", "Id": "14827", "Score": "0", "Tags": [ "python" ], "Title": "Criticize my first attempt at using the itertools module" }
14827
<p>I wrote a program to take a list of letters and from every permutation of them and check that against the dictionary and print out valid words. The constraints are that there is a control letter which means that letter must be in the word, and you can't repeat any letters.</p> <p>Everything works, but the running time is way too long. I'm hoping to get some feedback on how to cut down my running time in O-notation. Also, if you know the running times of the built in function, that would be great. Also, comment if my code style is not what it should be for Python.</p> <pre><code>import itertools from multiprocessing import Process, Manager dictionary_file = '/usr/share/dict/words' letter_list = ['t','b','a','n','e','a','c','r','o'] control_letter = 'e' manager = Manager() word_list = manager.list() def new_combination(i, dictionary): comb_list = itertools.permutations(letter_list,i) for item in comb_list: item = ''.join(item) if(item in dictionary): word_list.append(item) return def make_dictionary(): my_list = [] dicts = open(dictionary_file).readlines() for word in dicts: if control_letter in word: if(len(word) &gt;3 and len(word)&lt;10): word = word.strip('\n') my_list.append(word) return my_list def main(): dictionary = make_dictionary() all_processes = [] for j in range(9,10): new_combo = Process(target = new_combination, args = (j,dictionary,)) new_combo.start() all_processes.append(new_combo) while(all_processes): for proc in all_processes: if not proc.is_alive(): proc.join() all_processes = [proc for proc in all_processes if proc.is_alive()] if(len(all_processes) == 0): all_processes = None print list(set(word_list)) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-08T14:32:15.810", "Id": "99399", "Score": "0", "body": "This is a good question, thank you for taking the time to form it so that we can help show you the proper coding styles and techniques. We all look forward to seeing more of your posts!" } ]
[ { "body": "<pre><code>import itertools\nfrom multiprocessing import Process, Manager\n\ndictionary_file = '/usr/share/dict/words'\nletter_list = ['t','b','a','n','e','a','c','r','o']\ncontrol_letter = 'e'\n</code></pre>\n\n<p>By convention, global constant should be named in ALL_CAPS</p>\n\n<pre><code>manager = Manager()\nword_list = manager.list()\n\ndef new_combination(i, dictionary):\n comb_list = itertools.permutations(letter_list,i)\n for item in comb_list:\n item = ''.join(item)\n if(item in dictionary):\n</code></pre>\n\n<p>You don't need the parens. Also, dictionary in your code is a list. Checking whether an item is in a list is rather slow, use a set for fast checking.</p>\n\n<pre><code> word_list.append(item)\n</code></pre>\n\n<p>Having a bunch of different processes constantly adding onto a single list, performance will be decreased. You are probably better off adding onto a seperate list and then using extend to combine them at the end.</p>\n\n<pre><code> return\n</code></pre>\n\n<p>There is no point in an empty return at the end of a function </p>\n\n<pre><code>def make_dictionary():\n</code></pre>\n\n<p>I'd call this <code>read_dictionary</code>, since you aren't really making the dictionary</p>\n\n<pre><code> my_list = []\n</code></pre>\n\n<p>Name variables for what they are for, not their types</p>\n\n<pre><code> dicts = open(dictionary_file).readlines()\n for word in dicts:\n</code></pre>\n\n<p>Actually, you could just do <code>for word in open(dictionary_file)</code> for the same effect</p>\n\n<pre><code> if control_letter in word:\n if(len(word) &gt;3 and len(word)&lt;10):\n word = word.strip('\\n')\n</code></pre>\n\n<p>I recommend stripping before checking lengths, just to make it easier to follow what's going on</p>\n\n<pre><code> my_list.append(word)\n return my_list\n\ndef main():\n dictionary = make_dictionary()\n all_processes = []\n for j in range(9,10):\n new_combo = Process(target = new_combination, args = (j,dictionary,))\n</code></pre>\n\n<p>You don't need that last comma</p>\n\n<pre><code> new_combo.start()\n all_processes.append(new_combo)\n while(all_processes):\n</code></pre>\n\n<p>Parens unneeded</p>\n\n<pre><code> for proc in all_processes:\n if not proc.is_alive():\n proc.join()\n all_processes = [proc for proc in all_processes if proc.is_alive()]\n</code></pre>\n\n<p>What happens if a process finishes between the last two lines? You'll never call proc.join() on it.</p>\n\n<pre><code> if(len(all_processes) == 0):\n all_processes = None\n</code></pre>\n\n<p>an empty list is already considered false, so there is no point in this.</p>\n\n<p>Actually, there is no reason for most of this loop. All you need is </p>\n\n<pre><code>for process in all_processes:\n process.join()\n</code></pre>\n\n<p>It'll take care of waiting for all the processes to finish. It'll also be faster since it won't busy loop. </p>\n\n<pre><code> print list(set(word_list))\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>I've given a few suggestions for speed along the way. But what you should really do is invert the problem. Don't look at every combination of letters to see if its a word. Look at each word in the dictionary and see if you can form it out of your letters. That should be faster because there are many fewer words in the dictionary then possible combination of letters.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T15:02:26.773", "Id": "14831", "ParentId": "14828", "Score": "5" } } ]
{ "AcceptedAnswerId": "14831", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T11:48:10.010", "Id": "14828", "Score": "6", "Tags": [ "python", "combinatorics" ], "Title": "Generating words based on a list of letters" }
14828
<p>I was looking for a PHP class to handle all database operations (MySQL) and came across the following class. Someone please help me telling if this uses Prepared Statements correctly to make my web app safe from SQL injection.</p> <pre><code>class db extends PDO { private $error; private $sql; private $bind; private $errorCallbackFunction; private $errorMsgFormat; public function __construct($dsn, $user="", $passwd="") { $options = array( PDO::ATTR_PERSISTENT =&gt; true, PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION ); try { parent::__construct($dsn, $user, $passwd, $options); } catch (PDOException $e) { $this-&gt;error = $e-&gt;getMessage(); } } private function debug() { if(!empty($this-&gt;errorCallbackFunction)) { $error = array("Error" =&gt; $this-&gt;error); if(!empty($this-&gt;sql)) $error["SQL Statement"] = $this-&gt;sql; if(!empty($this-&gt;bind)) $error["Bind Parameters"] = trim(print_r($this-&gt;bind, true)); $backtrace = debug_backtrace(); if(!empty($backtrace)) { foreach($backtrace as $info) { if($info["file"] != __FILE__) $error["Backtrace"] = $info["file"] . " at line " . $info["line"]; } } $msg = ""; if($this-&gt;errorMsgFormat == "html") { if(!empty($error["Bind Parameters"])) $error["Bind Parameters"] = "&lt;pre&gt;" . $error["Bind Parameters"] . "&lt;/pre&gt;"; $css = trim(file_get_contents(dirname(__FILE__) . "/error.css")); $msg .= '&lt;style type="text/css"&gt;' . "\n" . $css . "\n&lt;/style&gt;"; $msg .= "\n" . '&lt;div class="db-error"&gt;' . "\n\t&lt;h3&gt;SQL Error&lt;/h3&gt;"; foreach($error as $key =&gt; $val) $msg .= "\n\t&lt;label&gt;" . $key . ":&lt;/label&gt;" . $val; $msg .= "\n\t&lt;/div&gt;\n&lt;/div&gt;"; } elseif($this-&gt;errorMsgFormat == "text") { $msg .= "SQL Error\n" . str_repeat("-", 50); foreach($error as $key =&gt; $val) $msg .= "\n\n$key:\n$val"; } $func = $this-&gt;errorCallbackFunction; $func($msg); } } public function delete($table, $where, $bind="") { $sql = "DELETE FROM " . $table . " WHERE " . $where . ";"; $this-&gt;run($sql, $bind); } private function filter($table, $info) { $driver = $this-&gt;getAttribute(PDO::ATTR_DRIVER_NAME); if($driver == 'sqlite') { $sql = "PRAGMA table_info('" . $table . "');"; $key = "name"; } elseif($driver == 'mysql') { $sql = "DESCRIBE " . $table . ";"; $key = "Field"; } else { $sql = "SELECT column_name FROM information_schema.columns WHERE table_name = '" . $table . "';"; $key = "column_name"; } if(false !== ($list = $this-&gt;run($sql))) { $fields = array(); foreach($list as $record) $fields[] = $record[$key]; return array_values(array_intersect($fields, array_keys($info))); } return array(); } private function cleanup($bind) { if(!is_array($bind)) { if(!empty($bind)) $bind = array($bind); else $bind = array(); } return $bind; } public function insert($table, $info) { $fields = $this-&gt;filter($table, $info); $sql = "INSERT INTO " . $table . " (" . implode($fields, ", ") . ") VALUES (:" . implode($fields, ", :") . ");"; $bind = array(); foreach($fields as $field) $bind[":$field"] = $info[$field]; return $this-&gt;run($sql, $bind); } public function run($sql, $bind="") { $this-&gt;sql = trim($sql); $this-&gt;bind = $this-&gt;cleanup($bind); $this-&gt;error = ""; try { $pdostmt = $this-&gt;prepare($this-&gt;sql); if($pdostmt-&gt;execute($this-&gt;bind) !== false) { if(preg_match("/^(" . implode("|", array("select", "describe", "pragma")) . ") /i", $this-&gt;sql)) return $pdostmt-&gt;fetchAll(PDO::FETCH_ASSOC); elseif(preg_match("/^(" . implode("|", array("delete", "insert", "update")) . ") /i", $this-&gt;sql)) return $pdostmt-&gt;rowCount(); } } catch (PDOException $e) { $this-&gt;error = $e-&gt;getMessage(); $this-&gt;debug(); return false; } } public function select($table, $where="", $bind="", $fields="*") { $sql = "SELECT " . $fields . " FROM " . $table; if(!empty($where)) $sql .= " WHERE " . $where; $sql .= ";"; return $this-&gt;run($sql, $bind); } public function setErrorCallbackFunction($errorCallbackFunction, $errorMsgFormat="html") { //Variable functions for won't work with language constructs such as echo and print, so these are replaced with print_r. if(in_array(strtolower($errorCallbackFunction), array("echo", "print"))) $errorCallbackFunction = "print_r"; if(function_exists($errorCallbackFunction)) { $this-&gt;errorCallbackFunction = $errorCallbackFunction; if(!in_array(strtolower($errorMsgFormat), array("html", "text"))) $errorMsgFormat = "html"; $this-&gt;errorMsgFormat = $errorMsgFormat; } } public function update($table, $info, $where, $bind="") { $fields = $this-&gt;filter($table, $info); $fieldSize = sizeof($fields); $sql = "UPDATE " . $table . " SET "; for($f = 0; $f &lt; $fieldSize; ++$f) { if($f &gt; 0) $sql .= ", "; $sql .= $fields[$f] . " = :update_" . $fields[$f]; } $sql .= " WHERE " . $where . ";"; $bind = $this-&gt;cleanup($bind); foreach($fields as $field) $bind[":update_$field"] = $info[$field]; return $this-&gt;run($sql, $bind); } } </code></pre> <p>And, using the class as follows:</p> <p><strong>Using Select:</strong></p> <pre><code>$search = "J"; $bind = array( ":search" =&gt; "%$search" ); $results = $db-&gt;select("mytable", "FName LIKE :search", $bind); </code></pre> <p><strong>Using Update:</strong></p> <pre><code>$update = array( "Age" =&gt; 24 ); $fname = "Jane"; $lname = "Doe"; $bind = array( ":fname" =&gt; $fname, ":lname" =&gt; $lname ); $db-&gt;update("mytable", $update, "FName = :fname AND LName = :lname", $bind); </code></pre> <p><strong>Using Insert:</strong></p> <pre><code>$insert = array( "FName" =&gt; "John", "LName" =&gt; "Doe", "Age" =&gt; 26, "Gender" =&gt; "male" ); $db-&gt;insert("mytable", $insert); </code></pre> <p>Or if you have some another class that you'd like to recommend, I'd be really glad!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T14:16:17.630", "Id": "24207", "Score": "0", "body": "I am using this as well...i was wondering the same thing.... but I know that the PDO class has a $pdo->quote function that you can use to escape stuff... but the class is good as it uses prepare() function" } ]
[ { "body": "<p>Seams to me safe but it's not easy to use. You can create somthing similar to the insert logic for the update (your are naming twice your parameters). In you constructor there is no reason to use that try-catch block and this is true for your debug mathod it is unnecessary with the try-catch block in the run method. Try to have some solution to avoid the usage of the cleanup method becouse it makes to code messy.</p>\n\n<p><strong>Do not use PDO::ATTR_PERSISTENT => true!</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T11:02:23.990", "Id": "14849", "ParentId": "14832", "Score": "2" } } ]
{ "AcceptedAnswerId": "14849", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T16:00:27.277", "Id": "14832", "Score": "2", "Tags": [ "php", "mysql", "security" ], "Title": "Database class for handling operations" }
14832
<p>I created script that generates maze or some kind of dungeons that looks like this: <a href="http://s13.postimage.org/4uify3jxj/blocks.jpg" rel="nofollow">http://s13.postimage.org/4uify3jxj/blocks.jpg</a></p> <p>I have problem with optimize, because when I've tried to add blockade to not overwrite existing blocks, script is executing most of times more than 60s.</p> <p>So... any ideas how can I optimize this?</p> <pre><code>&lt;?php class dungeon_block { public $left='EMPTY', $right='EMPTY', $top='EMPTY', $bottom='EMPTY', $visited=false, $action='NONE'; public $x, $y; public function __construct($x, $y) { $this-&gt;x = $x; $this-&gt;y = $y; } } function rollDirection() { $direction = rand(0,3); $dir = ''; switch($direction) { case 0: $dir = 'LEFT'; break; case 1: $dir = 'RIGHT'; break; case 2: $dir = 'TOP'; break; case 3: $dir = 'BOTTOM'; break; } return $dir; } ?&gt; &lt;div class='dungeon'&gt; &lt;?php $count = rand(1,10); $count = 20; $index = 0; $blocks = array(); $blocks[$index] = new dungeon_block(0,0); $blocks[$index]-&gt;left = "BLOCKED"; $blocks[$index]-&gt;top = "BLOCKED"; $xy = array(array()); $dirOK = false; $width = 25; $height = 25; $x; $y; echo "&lt;div class='dungeon_block' style='top: ".$blocks[$index]-&gt;y."; left: ".$blocks[$index]-&gt;x."' id='block-".$index."'&gt;S&lt;/div&gt;"; $xy[0][0] = true; while($count &gt;=1 ) { while($dirOK == false) { $dir = strtolower(rollDirection()); if($blocks[$index]-&gt;$dir == 'EMPTY') { $x = $blocks[$index]-&gt;x; $y = $blocks[$index]-&gt;y; $br = ''; $left='EMPTY'; $right='EMPTY'; $top='EMPTY'; $bottom='EMPTY'; switch($dir) { case 'left': $x -= $width; $right = 'BLOCKED';break; case 'right': $x += $width; $left = 'BLOCKED';break; case 'top': $y -= $height; $bottom = 'BLOCKED';break; case 'bottom': $y += $height; $top = 'BLOCKED'; $br = '&lt;br /&gt;'; break; } $i = 1; if($x &lt; 0 || $y &lt; 0) { if($i &gt; 5) $dirOK = true; $i++; continue; } $i = 1; if(array_key_exists($x, $xy)) { if(array_key_exists($y, $xy[$x])) { if($i &gt; 15) $dirOK = true; $i++; continue; } } $dirOK = true; } } $index++; echo "&lt;div style='top: ".(int)$y."px; left: ".(int)$x."px;' class='dungeon_block' id='block-".$index."' &gt;". $dir[0] ."&lt;/div&gt;"; $blocks[$index] = new dungeon_block($x, $y); $blocks[$index]-&gt;left = $left; $blocks[$index]-&gt;right = $right; $blocks[$index]-&gt;bottom = $bottom; $blocks[$index]-&gt;top = $top; $xy[$x][$y] = true; $dirOK = false; $count--; } ?&gt; &lt;/div&gt; </code></pre> <p>Edited code:</p> <pre><code>&lt;?php function rollDirection() { $direction = rand(0,3); $directions = array( 'left', 'right', 'top', 'bottom' ); return $directions[$direction]; } function drawBlock($b) { echo "&lt;div class='dungeon_block' style='top: ". $b['y'] ."px; left: ". $b['x']."px;' id='block-". $b['index'] ."'&gt;".$b['text']."&lt;/div&gt;"; } ?&gt; &lt;div class='dungeon'&gt; &lt;?php $count = 10; $length = 25; $blocks = array(); $blocks[0] = array( 'text' =&gt; 'S', // for tests 'index' =&gt; 0, 'x' =&gt; 0, 'y' =&gt; 0 ); drawBlock($blocks[0]); // set start block for($i=0; $i &lt; $count; $i++) // draw others { $x = $blocks[$i]['x']; // get x from the previous block $y = $blocks[$i]['y']; // get y from the previous block $dir = rollDirection(); switch($dir) { case 'left': $x -= $length; break; case 'right': $x += $length; break; case 'top': $y -= $length; break; case 'bottom': $y += $length; break; } $x = (int)$x; $y = (int)$y; // check if x or y are less than 0 - that is forbidden // if so, repeat roll for that block if($x &lt; 0 || $y &lt; 0) { $i--; continue; } $blocks[$i+1] = array( 'text' =&gt; $i.$dir[0], // for tests 'index' =&gt; $i, 'x' =&gt; $x, 'y' =&gt; $y ); drawBlock($blocks[$i+1]); } ?&gt; &lt;/div&gt; </code></pre> <p>I have to think out this problems too: a) Blocks cannot overwrite themselves. (For example x=0 y=0 and 15 blocks laters, again x=0 y=0, so first blocks won't be visible). I have written this function:</p> <pre><code>function checkIsSpotFree($x, $y, $blocks, $length) // checks if spots is free and returns nearset free direction, if exist { $neighbours = array( 'left' =&gt; array('free' =&gt; true, 'x' =&gt; $x -= $length, 'y' =&gt; $y ), 'right' =&gt; array('free' =&gt; true, 'x' =&gt; $x += $length, 'y' =&gt; $y ), 'top' =&gt; array('free' =&gt; true, 'x' =&gt; $x, 'y' =&gt; $y -= $length ), 'bottom' =&gt; array('free' =&gt; true, 'x' =&gt; $x, 'y' =&gt; $y += $length ), 'center' =&gt; array('free' =&gt; true, 'x' =&gt; $x, 'y' =&gt; $y ) ); foreach($blocks as $block) { if($neighbours['left']['x'] == $block['x'] &amp;&amp; $neighbours['left']['y'] == $block['y']) $neighbours['left']['free'] = false; if($neighbours['right']['x'] == $block['x'] &amp;&amp; $neighbours['right']['y'] == $block['y']) $neighbours['right']['free'] = false; if($neighbours['top']['x'] == $block['x'] &amp;&amp; $neighbours['top']['y'] == $block['y']) $neighbours['top']['free'] = false; if($neighbours['bottom']['x'] == $block['x'] &amp;&amp; $neighbours['bottom']['y'] == $block['y']) $neighbours['bottom']['free'] = false; if($neighbours['center']['x'] == $block['x'] &amp;&amp; $neighbours['center']['y'] == $block['y']) $neighbours['center']['free'] = false; } $free_spot = null; // declare nav to next free spot, default null foreach($neighbours as $d) { if($d['free'] == true &amp;&amp; $d['x'] &gt;= 0 &amp;&amp; $d['y'] &gt;= 0) { $free_spot = $d; break; } } return $free_spot; } </code></pre> <p>but there is still problem. If will be this situation ("B" refers to block, "X" proposal position):</p> <pre><code>X -&gt; BX -&gt; BBX -&gt; BBB X -&gt; BBB B X -&gt; BBB B BX -&gt; BBB B BBX -&gt; BBB B X BBB -&gt; BBB BXB BBB -&gt; BBB BXB BBB X = ? </code></pre> <p>There is no possible direction for new block, because it is surrounded by existings blocks. Than script runs into wall and endless loop. Any ideas how can I resolve this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T17:04:11.147", "Id": "25610", "Score": "1", "body": "The first part of your question (\"how do I optimize this\") was on-topic. The rest of the question (\"how to I add this functionality\") was off-topic. Questions can be re-opened if they are thoroughly edited." } ]
[ { "body": "<p>Begin your optimizations by not having classes for the sake of having a class. For instance, <code>dungeon_block</code> is not a class. You made it one, but nothing about it says that it is one. Its just a glorified data repository. OOP does not just mean instantiating a class, there's more to it. Intercommunication, encapsulation, and extendability to name a few. Maybe if this were refactored for the map and held multiple blocks, then I could <em>almost</em> see using a class. But even then it wouldn't follow all OOP logic and would just be a style choice. As it stands you'd be better off with an associative array, which is what I will show you in the following review.</p>\n\n<p>Note: Once you've got this working, you might consider implementing some sort of cache, so that these maps don't have to be regenerated. This will greatly assist in load times. A good method might be to store these maps as JSON on some kind of database. Or maybe just directly as JSON files. I suggest JSON because it can be directly decompiled and recompiled with little effort by maintaining its structure, as well as providing JS support.</p>\n\n<p>A better way to determine direction might be to use an array instead of a switch. I say \"might\" because I have not profiled it, I'll leave that to you. Either way, here is another way.</p>\n\n<pre><code>$directions = array(\n 'LEFT',\n 'RIGHT',\n 'TOP',\n 'BOTTOM'\n);\n\nreturn $directions[ $direction ];\n</code></pre>\n\n<p>Consider breaking up the rest of this code into functions, even if you don't end up reusing them. It will make your code much easier to maintain and so much easier to read. To help get you started, the first chunk could be a function called, <code>init()</code>, and could be used to initiate the map. I'll leave you to figure out the implementation and how to break up the rest.</p>\n\n<p>What is the purpose of defining <code>$count</code> to a random number if you are then not going to do anything with it? Its not much of an inefficiency, but it still is one. Also, why count? Count usually means a dynamically retrieved length or amount, not a static number that has been hardcoded in. For such instances I would expect to see a constant named <code>MAX_XXX</code>, where <code>XXX</code> is what is being counted.</p>\n\n<pre><code>$count = rand(1,10);\n$count = 20;\n</code></pre>\n\n<p>Since we aren't using a class anymore, or rather, I won't because I'm not going to redo all this code into a class for you, a better way to go about setting up the blocks would be to just use arrays. If you begin by setting up a template array, you can then change specific characteristics on each iteration. For instance:</p>\n\n<pre><code>$block = array(\n 'left' =&gt; 'EMPTY',\n 'right' =&gt; 'EMPTY',\n 'top' =&gt; 'EMPTY',\n 'bottom' =&gt; 'EMPTY',\n 'visited' =&gt; FALSE,\n 'action' =&gt; 'NONE',\n 'x' =&gt; 0,\n 'y' =&gt; 0\n);\n\n//for demonstration purposes\n$blocks = array();\nfor( $i = 0; $i &lt; $count ; $i++ ) {\n $blocks[] = $block;\n if( Perform checks to determine if changes are necessary ) {\n //make changes\n $blocks[ $i ][ XXX ] = YYY;\n }\n}\n</code></pre>\n\n<p>Why are you reinventing a for loop? Your while loop essentially does the same exact thing, only more messily. I think at one point the while loop was faster, which is why it was sometimes preferred, but I don't think that is the case anymore. Either way, the VERY slight speed benefit is not worth the loss in legibility. Code for legibility before speed. Often times there is no difference between legible code and efficient code.</p>\n\n<pre><code>$i = 0;\nwhile( $i &lt; 100 ) { $i++ }\n//compared to\nfor( $i = 0; $i &lt; 100 ; $i++ ) { }\n</code></pre>\n\n<p>A single array declaration is fine for <code>$xy</code>. No need to do so twice.</p>\n\n<pre><code>$xy = array();\n</code></pre>\n\n<p>When comparing variables to their boolean value, it is not necessary to explicitly do so unless specifically checking that variables type as well.</p>\n\n<pre><code>$dirOK = \"FALSE\";\nwhile( ! $dirOK ) {//TRUE because \"FALSE\" == FALSE\nwhile( $dirOK == FALSE ) {//TRUE because \"FALSE\" == FALSE\nwhile( $dirOK === FALSE ) {//FALSE because \"FALSE\" !== FALSE\n</code></pre>\n\n<p>If you need the directions in lowercase, why did you capitalize them? Don't use functions that you don't need.</p>\n\n<pre><code>$dir = strtolower(rollDirection());\n</code></pre>\n\n<p>Not that it will be an issue if you lose the class, but always avoid variable variables. These are hard to debug for and are generally considered bad smell. There are a few exceptions, but this is definitely not one of them.</p>\n\n<pre><code>$blocks[$index]-&gt;$dir \n</code></pre>\n\n<p>What is the point of <code>$br</code>? You define it as empty, then redefine it as the HTML break tag later, but you never use it anywhere that I can see.</p>\n\n<p>With the set up I showed you above, the default direction values will not be necessary, instead, in the switch statement you should just directly modify the block.</p>\n\n<pre><code>case 'left':\n $blocks[ $index ] [ 'x' ] -= $width;\n $blocks[ $index ] [ 'right' ] = 'BLOCKED';\nbreak;\n//etc...\n</code></pre>\n\n<p>I'm confused... What exactly is the purpose in incrementing <code>$i</code> in these two statements? It doesn't do anything. Every time this loop iterates <code>$i</code> is reset to 1, then it is used to perform a check that is always FALSE, before being incremented and restarting the process over again. The incremented version is never used.</p>\n\n<pre><code>$i = 1;\nif($x &lt; 0 || $y &lt; 0) {\n if($i &gt; 5) $dirOK = true;\n $i++;\n continue;\n}\n$i = 1;\nif(array_key_exists($x, $xy)) {\n if(array_key_exists($y, $xy[$x])) {\n if($i &gt; 15) $dirOK = true;\n $i++;\n continue;\n }\n}\n</code></pre>\n\n<p>Additionally, always use braces <code>{}</code> on your statements. It helps with legibility and ensures that there are no issues with your code. Even PHP agrees that neglecting these braces is bad because it CAN cause issues in the code. Besides, a better way would just be to set <code>$dirOK</code>'s value to the return value of that expression.</p>\n\n<pre><code>$dirOK = $i &gt; 5;\n</code></pre>\n\n<p>I'm having a lot of trouble following this code. I'm sure there's more I could help you with, such as the repetition I'm seeing. Not that I could explain it coherently enough right now. Make some of these suggested improvements and leave me a comment and I'll take another look. If you do decide to upload a revised version, DON'T delete the previous code, add it below the existing code.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>First of all, much better. I don't feel quite so lost anymore :)</p>\n\n<p>Here's something I missed yesterday: The magic number, \"3\", in <code>$direction</code> should be converted to use the count of <code>$directions</code>. Or, as I'll point out later, you might want to pass a maximum \"roll\" as a parameter.</p>\n\n<pre><code>$numDirections = count( $directions );\n$direction = rand( 0, $numDirections );\n</code></pre>\n\n<p>You missed the first function I mentioned yesterday. Here's how I'd write it, you can rewrite it without <code>compact()</code> if you wish. Not everyone seems to like <code>compact()</code> or its counterpart <code>extract()</code> because they are hard to debug and read, but I think you can get away with it here.</p>\n\n<pre><code>function setBlock( $text, $index, $x, $y ) {\n $block = compact( 'text', 'index', 'x', 'y' );\n\n drawBlock( $block );\n\n return $block;\n}\n</code></pre>\n\n<p>Now, the above function is the beginning of that repetition I mentioned yesterday. You manually set the first block before the loop, then you set each other block inside the loop. I understand why you are doing it, I just don't think it's necessary. If its something you think feasible, great, if not let me know why and I'll see if there is something else I can come up with. Now, a question first: Why are you jumping the x and y coordinates 25 at a time? Wouldn't these only move one at a time depending on the direction of travel? I'm going to assume so for now, if nothing else you might be able to apply this somewhere else. So first thing, let's refactor this loop a little. The incremental <code>$i</code> seems unnecessary when we already have two other incrementals to play with. I demonstrated using <code>$i</code> yesterday because I did not want to introduce the following until your code was updated.</p>\n\n<pre><code>for( $x = 0, $y = 0; $y &lt; $MAX_Y; $x++ ) {\n $blocks[] = setBlock( $text, $index, $x, $y );\n\n if( $x == $MAX_X ) {\n $y++;\n $x = 0;\n }\n}\n</code></pre>\n\n<p><code>$MAX_X</code> and <code>$MAX_Y</code> are probably just <code>$count</code> or <code>$width</code> and <code>$height</code>, but I wasn't sure, so I just assigned them descriptive names so you can determine what they should be.</p>\n\n<p>Now, the above loop is just for demonstration, it doesn't do everything for you. You will still have to check direction and all that other fun stuff. Speaking of, I mentioned earlier that I would show you why you might wish to pass a maximum roll as a parameter to <code>rollDirection()</code>. This is because you have already demonstrated that you do not want your x and y coordinates to go negative. So, if you adjust how those directions are set up in the array you can then adjust the maximum random number generated so that it excludes that index. <code>if( $x - $length &lt; 0 )</code>, and the same for the y axis. This will reduce the amount of \"rerolls\" you have to do, which might actually be where most of your lag is coming from.</p>\n\n<p>Typecasting the x and y coordinates seems pointless. They start off as integers and the only thing you ever do to them is add or subtract other known integers. So long as the variables you add to it are always integers so will be the outcome.</p>\n\n<pre><code>$x = (int)$x;\n$y = (int)$y;\n//In this case this is the same as $x = $x &amp;&amp; $y = $y\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T23:25:45.333", "Id": "24141", "Score": "0", "body": "First of all - thanks you for the most helpful answer. I have edited code and edited questions with new code. However I feel like I have to explain something first. The $i=1; before each loop was some kind of security mechanism that prevent endless loop - if it runs more than x, force break. With updated code maze is being generating, but there still left this critical problems: maze will be regenerating each user start a new one, it has to be saved in database to easily restored and with positions of user and blocks cant overwrite themselves, like it is right now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T15:23:24.410", "Id": "24176", "Score": "0", "body": "@Aylard: I updated my answer. To the best of my knowledge, the `$i` was not doing anything. It kept resetting on each iteration so those if statements that used them were never true." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T20:49:14.793", "Id": "24194", "Score": "0", "body": "thanks for update yours reply! I see I forgot to explain some things. I have to have set of generated blocks, so I can later easily re-create exact same maze. `$width`,`$height`,`$length` are the same in value of 25, because of CSS style. Each block has 15width+10padding, so 25. `$x` and `$y` are margins of blocks as you can see in `drawBlock()` function. `$x = (int)$x;` is so, because some times `$x` was `NULL` which in CSS caused some troubles. However I agree with you for `$directions[rand(0, count($directions)];`, thanks! I've updated question with some other problems." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T13:14:44.980", "Id": "24335", "Score": "0", "body": "@Aylard: I'm not sure I understand this latest problem. It sounds like you are trying to shift the screen with the player's movements? If, as it appears, you want to do this one row at a time, that will be a bit difficult. Either way, you can push part or all of the current map array into a JSON object and save it on the server, or in a local variable, until needed again. This will allow you to reuse the coordinates. However, I don't think thats a good idea as it will require a lot of new \"memory\" variables for saving position on each map and order. It will start getting confusing and bulky." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T20:40:15.320", "Id": "14871", "ParentId": "14833", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T17:09:50.497", "Id": "14833", "Score": "0", "Tags": [ "php", "html", "php5" ], "Title": "Optimizing blocks-maze generation script php" }
14833
<p>I have written an implementation of the observer pattern that allows messages to be passed to listeners in what would normally be the <code>notify()</code> method. For example a subscriber sub-class might look like the pseudo-code below, where <code>Message</code> is a simple class that can be subclassed and made to contain value objects or other data.</p> <pre><code>class MySubscriber extends Subscriber { @Override public void notify( Message m ) { if( m.getClass == MyMessage ) { MyMessage myMessage = ( MyMessage ) m; if( myMessage.name == MyMessage.START ) { // -- Finally do something here } } if( m.getClass == MyOtherMessage ) { MyOtherMessage myOtherMessage = ( MyOtherMessage ) m; if( myOtherMessage.name == MyOtherMessage.INIT_SOMETHING ) { // -- Finally do something else here } } } } </code></pre> <p>Using conditionals like this to determine the message type seems a bit redundant and can get tedious in cases where a subscriber is listening for many message types. However, it is pretty explicit, easy to read and the implementation is quite simple. Is there a cleaner approach to achieve a similar result?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T19:54:09.030", "Id": "24132", "Score": "0", "body": "You have some double checks: checking for type and the value of a string. I'd suggest using an enum and forget about the type checking, since everything appears to be a message instance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T20:09:34.700", "Id": "24134", "Score": "0", "body": "The parameter m could be a Message sub-class such as MyMessage or MyOtherMessage each with their own constants as is the case in the example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T06:37:16.257", "Id": "24143", "Score": "0", "body": "Yes, but that doesn't matter because the subclasses behave like Message instance. So, when you extract the constants in an enum class, you'd just had to speak against the Message type and could ignore the inheriting types." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T15:04:55.770", "Id": "24175", "Score": "0", "body": "@Florian Salihovic - In some cases the message sub-classes might contain value objects or other properties not on the parent class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-01T07:09:12.193", "Id": "154198", "Score": "0", "body": "@200_success why off-topic?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-01T08:09:35.233", "Id": "154203", "Score": "0", "body": "@dit _For example a subscriber sub-class might look like the pseudo-code below, …_ Pseudocode / stub code is off-topic, as explained in the off-topic notice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-01T08:17:53.577", "Id": "154205", "Score": "0", "body": "@200_success I see. but I think pseudo-code make the question more readable and perhaps language-independent. I'm sure this Question will be also closed on stackoverflow. Perhaps we need something like pseudo-codereview or algorithm-review forum." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-01T08:30:06.580", "Id": "154207", "Score": "0", "body": "@dit Whiteboard-type questions should be allowable on [programmers.se]." } ]
[ { "body": "<p>Personally I prefer <a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\" rel=\"nofollow\">polymorphism instead of conditions</a> in such cases, as it helps to keep big conditions in a clean fashion - each condition in it's own class. As an example, in .NET they have generic event-handlers (subscribers) and following class system takes place (or something along these lines):</p>\n\n<pre><code>abstract class EventArgs { ... } // your abstract data class, Message if you will\nclass MyEventArgs : EventArgs { } // and it's implementation\n\nabstract class EventHandler&lt;T&gt; // an abstract Subscriber\n{ \n public abstract Notify(T args); // Subscriber::notify() in your example\n} \n\nclass MyEventHandler : EventHandler&lt;MyEventArgs&gt; // an implementation of a subscriber for one specific case, which would be MyEventArgs\n{\n public Notify(MyEventArgs args) { ... }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T18:10:24.713", "Id": "24108", "Score": "0", "body": "I like this approach. It is definitely more elegant and should be doable in Java." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T18:16:54.813", "Id": "24109", "Score": "0", "body": "Absolutely doable. Btw, you might also enjoy browsing through other [types of refactoring](http://refactoring.com/catalog/)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T17:30:28.033", "Id": "14835", "ParentId": "14834", "Score": "3" } }, { "body": "<p>Just a couple of thoughts as it's hard to tell without more background:</p>\n\n<ul>\n<li><p>Do you really want to use the <code>==</code> operator here, perhaps you should\nbe using <code>instanceof</code>.</p></li>\n<li><p>If the Subscriber needs to handle various types of messages why not\ninclude those types explicitly in theinterface? I think it makes it\nclear what the code sending the message intends, rather than\nfunneling all messages through a single method. This may allow for compile time type checking.</p></li>\n<li><p>Consider making a separate subscriber interface for each type of\nsubscriber.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T18:27:45.780", "Id": "24131", "Score": "0", "body": "instanceof is a good tip. My goal is to write an abstract and reusable observer/listener like pattern and to avoid writing methods specifically for each message type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T20:46:37.200", "Id": "24137", "Score": "0", "body": "If you're having many types of messages perhaps your message interface isn't sufficient (not a complete interface). IMHO an interface should encapsulate all that is needed for two components to interact, otherwise you are forcing the message subscriber to think beyond the interface." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T17:20:28.183", "Id": "14864", "ParentId": "14834", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T17:13:45.627", "Id": "14834", "Score": "2", "Tags": [ "java", "callback" ], "Title": "Allowing messages to be passed to listeners" }
14834
<p>I was hoping I could get some of you to look over a program I wrote. I am just beginning to learn about Python (for the last month or so). Therefore, I may not be aware of techniques that would make this program better. Currently I'm studying Python 2.7. Any advice or suggestions you could provide would be appreciated. Thanks again.</p> <pre><code>##Flash Card Program # Import required modules import random import sys import os import math # variables right_answer_total = float(0) wrong_answer_total = float(0) percentage = 100 * (float(right_answer_total) / float(answer_total)) if (right_answer_total &gt; 0 and answer_total &gt; 0) else 0 # dictionary containing the information for the questions &amp; answers word_drills = {'class': 'Tell Python to make a new kind of thing.', 'object': 'Two meanings: the most basic kind of thing, and any instance of some thing.', 'instance': 'What you get when you tell Python to create a class.', 'def': 'How you define a function inside a class.', 'self': 'Inside the functions in a class, self is a variable for the instance/object being accessed.', 'inheritance': 'The concept that one class can inherit traits from another class, much like you and your parents.', 'composition': 'The concept that a class can be composed of other classes as parts, much like how a car has wheels.', 'attribute': 'A property classes have that are from composition and are usually variables.', 'is-a': 'A phrase to say that something inherits from another, as in a Salmon *** Fish', 'has-a': 'A phrase to say that something is composed of other things or has a trait, as in a Salmon *** mouth.'} # Main portion of the program def start(): # For loop that creates a list named keys. It grabs 3 random keys from the dictionary word_drills keys = [x for x in random.sample(word_drills, 3)] # User is presented with a question. A value from the previous randomly selected keys is selected as the 'question' correctanswer = word_drills[random.choice(keys)] print "Question: ", correctanswer # Set the variables key1, key2, &amp; key3 to the 3 keys in the list 'keys' key1, key2, key3 = keys[0], keys[1], keys[2] # User is presented with 3 choices. print "\n\n(a)%s (b)%s (c)%s" % (key1, key2, key3) a, b, c = word_drills[key1], word_drills[key2], word_drills[key3] selection = raw_input("&gt; ") print selection if selection == "a": if a == correctanswer: print "That's correct!" answered_correctly() else: print "I'm sorry, that is incorrect..." not_answered_correctly() elif selection == "b": if b == correctanswer: print "That's correct!" answered_correctly() else: print "I'm sorry, that is incorrect..." not_answered_correctly() elif selection == "c": if c == correctanswer: print "That's correct!" answered_correctly() else: print "I'm sorry, that is incorrect..." not_answered_correctly() else: print "That is not a valid selection." exit(0) # Function when user is correct def answered_correctly(): global right_answer_total global answer_total global percentage right_answer_total += 1 answer_total = float(right_answer_total + wrong_answer_total) percentage = 100 * (float(right_answer_total) / float(answer_total)) stat_tracking() # Function when user is incorrect def not_answered_correctly(): global wrong_answer_total global answer_total global percentage wrong_answer_total += 1 answer_total = float(right_answer_total + wrong_answer_total) percentage = 100 * (float(right_answer_total) / float(answer_total)) stat_tracking() # Stat tracking def stat_tracking(): os.system('cls' if os.name=='nt' else 'clear') print "-" * 37 print "| Stat Tracking |" print "-" * 37 print "| Correct | Incorrect | Percentage |" print "-" * 37 print "| %d | %d | %d %% |" % (right_answer_total, wrong_answer_total, percentage) print "-" * 37 print "\n\n\n" start() stat_tracking() </code></pre>
[]
[ { "body": "<p>Here's a step by step Pythonization walk-trough.</p>\n\n<h2>Trivial simplifications</h2>\n\n<p>Before:</p>\n\n<pre><code>answer_total = float(right_answer_total + wrong_answer_total)\npercentage = 100 * (float(right_answer_total) / float(answer_total)) \n</code></pre>\n\n<p>After:</p>\n\n<pre><code>percentage = 100 * right_answer_total / float(right_answer_total + wrong_answer_total)\n</code></pre>\n\n<p>Reasoning: a single division argument (either numerator or denominator) is sufficient to be of a float type so that the float division was performed.</p>\n\n<hr>\n\n<p>Before:</p>\n\n<pre><code>keys = [x for x in random.sample(word_drills, 3)]\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>keys = random.sample(word_drills, 3)\n</code></pre>\n\n<p>Reasoning: <code>[x for x in l]</code> results in a copy of <code>l</code> since neither filtering nor element transformations are performed.</p>\n\n<hr>\n\n<p>Before:</p>\n\n<pre><code>key1, key2, key3 = keys[0], keys[1], keys[2]\nprint \"\\n\\n(a)%s (b)%s (c)%s\" % (key1, key2, key3)\na, b, c = word_drills[key1], word_drills[key2], word_drills[key3]\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>print \"\\n\\n(a)%s (b)%s (c)%s\" % tuple(keys)\n</code></pre>\n\n<p>Reasoning: same effect with less code; variables <code>key1, key2, key3, a, b, c</code> are unnecessary (see below).</p>\n\n<h2>Code Refactoring</h2>\n\n<p>Looks like you came from functional programming world. Each of your functions ends in calling another function. Since Python has no tail call optimization you will end up in stack overflow eventually.</p>\n\n<p>Thus your algorithm must be revised in a more imperative way. The whole program looks like this:</p>\n\n<ol>\n<li>Repeat in an infinite loop:\n<ol>\n<li>Print statistics</li>\n<li>Prepare a question</li>\n<li>Gather user input</li>\n<li>Exit program if user input was invalid</li>\n<li>Check whether user's answer was correct</li>\n<li>Update answer statistics</li>\n</ol></li>\n</ol>\n\n<p>For the outer loop a <code>while True:</code> construction will do.</p>\n\n<p>Statistics printing is mostly left intact. The function name changed from <code>stat_tracking</code> to <code>print_stats</code> to reflect the innards. Note that there is no tail call to <code>start()</code> since this function will be invoked from <code>start()</code> not vice versa. Also, to avoid global variables, stats are passed as paramenters:</p>\n\n<pre><code>def print_stats(right_answer_total, wrong_answer_total, percentage):\n os.system('cls' if os.name=='nt' else 'clear')\n print \"-\" * 37\n print \"| Stat Tracking |\"\n print \"-\" * 37\n print \"| Correct | Incorrect | Percentage |\"\n print \"-\" * 37\n print \"| %d | %d | %d %% |\" % (right_answer_total, wrong_answer_total, percentage)\n print \"-\" * 37\n print \"\\n\\n\\n\"\n</code></pre>\n\n<p>Bearing simplifications in mind and renaming the variables to reflect their meanings in mind here's the question preparation:</p>\n\n<pre><code>possible_answers = random.sample(word_drills, 3)\ncorrect_answer = random.choice(possible_answers)\nquestion = word_drills[correct_answer]\nprint \"Question:\", question\nprint \"\\n\\n(a)%s (b)%s (c)%s\" % tuple(possible_answers)\n</code></pre>\n\n<p>Since the whole program resides in a loop there's no need for <code>exit()</code>ing, a simple <code>break</code> will do:</p>\n\n<pre><code>if selection not in ('a', 'b', 'c'):\n print \"That is not a valid selection.\"\n break\n</code></pre>\n\n<p>Checking the answer for correctness needs a little bit more explanation.</p>\n\n<p>First of all, the <code>answered_correctly()</code> and <code>not_answered_correctly()</code> are gone. They were mostly the same, only a single line differed.</p>\n\n<p>Getting the user's answer is basically inferring an index from <code>possible_answers</code>. Since we validated <code>selection</code> (see above) we are sure that its value is in <code>\"a\", \"b\", \"c\"</code>. <code>\"a\", \"b\", \"c\"</code> correspond to <code>0, 1, 2</code> indexes of the <code>possible_answers</code> list respectively. Since <code>\"a\", \"b\", \"c\"</code> are laid out sequentially in ASCII table <code>ord(selection) - ord('a')</code> can be used to convert the string to answer index.</p>\n\n<p>Now figuring out whether user was correct or not is a matter of checking whether <code>answer == correct_answer</code>.</p>\n\n<p>Along with statistics update the code looks like this:</p>\n\n<pre><code>answer = possible_answers[ord(selection) - ord('a')]\nif answer == correct_answer:\n print \"That's correct!\"\n right_answer_total += 1\nelse:\n print \"I'm sorry, that is incorrect...\"\n wrong_answer_total += 1\n\npercentage = 100 * right_answer_total / float(right_answer_total + wrong_answer_total)\n</code></pre>\n\n<h2>Final Touches</h2>\n\n<p><code>sys</code> and <code>math</code> modules are unused, so do not import them.</p>\n\n<p>The main entry point function is called <code>main()</code> rather then <code>start()</code>. Though that is just a convention.</p>\n\n<p>To avoid your program starting when it is imported (as <code>import program</code>) rather then started as a program (as <code>python program.py</code>) the following trick is used:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>And here's the whole code:</p>\n\n<pre><code>#!/usr/bin/env python\n\nimport random\nimport os\n\n# dictionary containing the information for the questions &amp; answers\nword_drills = {'class': 'Tell Python to make a new kind of thing.',\n 'object': 'Two meanings: the most basic kind of thing, and any instance of some thing.',\n 'instance': 'What you get when you tell Python to create a class.',\n 'def': 'How you define a function inside a class.',\n 'self': 'Inside the functions in a class, self is a variable for the instance/object being accessed.',\n 'inheritance': 'The concept that one class can inherit traits from another class, much like you and your parents.',\n 'composition': 'The concept that a class can be composed of other classes as parts, much like how a car has wheels.',\n 'attribute': 'A property classes have that are from composition and are usually variables.',\n 'is-a': 'A phrase to say that something inherits from another, as in a Salmon *** Fish',\n 'has-a': 'A phrase to say that something is composed of other things or has a trait, as in a Salmon *** mouth.'}\n\n\n# Main portion of the program\ndef main():\n right_answer_total = 0\n wrong_answer_total = 0\n percentage = 0.0\n\n while True:\n print_stats(right_answer_total, wrong_answer_total, percentage)\n\n possible_answers = random.sample(word_drills, 3)\n # User is presented with a question. A value from the previous randomly selected possible_answers is selected as the 'correct_answer'\n correct_answer = random.choice(possible_answers)\n question = word_drills[correct_answer]\n print \"Question: \", question\n print \"\\n\\n(a)%s (b)%s (c)%s\" % tuple(possible_answers)\n\n selection = raw_input(\"&gt; \")\n if selection not in ('a', 'b', 'c'):\n print \"That is not a valid selection.\"\n break\n\n answer = possible_answers[ord(selection) - ord('a')]\n if answer == correct_answer:\n print \"That's correct!\"\n right_answer_total += 1\n else:\n print \"I'm sorry, that is incorrect...\"\n wrong_answer_total += 1\n\n percentage = 100 * right_answer_total / float(right_answer_total + wrong_answer_total)\n\n# Stat tracking\ndef print_stats(right_answer_total, wrong_answer_total, percentage):\n os.system('cls' if os.name=='nt' else 'clear') \n print \"-\" * 37\n print \"| Stat Tracking |\"\n print \"-\" * 37\n print \"| Correct | Incorrect | Percentage |\"\n print \"-\" * 37\n print \"| %d | %d | %d %% |\" % (right_answer_total, wrong_answer_total, percentage) \n print \"-\" * 37\n print \"\\n\\n\\n\"\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T17:05:07.993", "Id": "14862", "ParentId": "14838", "Score": "2" } }, { "body": "<p>A few point. These are all mostly smaller tweaks.</p>\n\n<pre><code># variables\nright_answer_total = float(0)\nwrong_answer_total = float(0)\npercentage = 100 * (float(right_answer_total) / float(answer_total)) if (right_answer_total &gt; 0 and answer_total &gt; 0) else 0\n</code></pre>\n\n<p>At this point we know <code>right_answer_total</code> and <code>wrong_answer_total</code> are both 0, so <code>percentage</code> can be initialized to 0 without any extra logic. Additionally, you can never get an answer half-right, so <code>right_answer_total</code> and <code>wrong_answer_total</code> should be integers. Store the data properly and then convert it if you need to later.</p>\n\n<p>You are creating a number of temporary variables that are not providing much benefit.</p>\n\n<pre><code>key1, key2, key3 = keys[0], keys[1], keys[2]\n# User is presented with 3 choices. \nprint \"\\n\\n(a)%s (b)%s (c)%s\" % (key1, key2, key3)\n</code></pre>\n\n<p>This can be done with</p>\n\n<pre><code>print \"\\n\\n(a)%s (b)%s (c)%s\" % tuple(keys)\n</code></pre>\n\n<p>I also don't think you are particularly gaining much by making <code>a</code>,<code>b</code> and <code>c</code>. If you switch to 1-3 instead of a-c, you can remove a lot of the repeated code.</p>\n\n<pre><code>print \"\\n\\n(1)%s (2)%s (3)%s\" % tuple(keys)\n\ntry:\n selection = int(raw_input(\"&gt; \"))\n if selection &lt; 0 or selection &gt; 3:\n print \"That is not a valid selection.\"\n exit(0)\n\n if word_drills[keys[selection-1]] == correctanswer:\n print \"That's correct!\"\n answered_correctly()\n else:\n print \"I'm sorry, that is incorrect...\"\n not_answered_correctly()\nexcept ValueError:\n print \"That is not a valid selection.\"\n exit(0)\n</code></pre>\n\n<p>You can specify a field with when doing a string format that will keeping the stats like from messing up your box boundary.</p>\n\n<p>This last point is the only thing I believe to be a bigger point. The way you are looping through the methods will eventually cause a stack overflow exception. For every question the user answers, the call stack increases by three.</p>\n\n<p><code>stat_tracking()</code> calls <code>start()</code> which calls <code>answered_correctly()</code> which calls <code>stat_tracking()</code>. This will continue and none of the methods will ever return until the user enters an invalid selection and the application quits.</p>\n\n<p>Instead, you should remove calls to <code>stat_tracking()</code> from <code>answered_correctly()</code> and <code>not_answered_correctly()</code>, remove the call to <code>start()</code> from <code>stat_tracking()</code>, and use a while loop to control the repetition.</p>\n\n<pre><code>while True:\n stat_tracking()\n start()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T17:28:22.117", "Id": "14867", "ParentId": "14838", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T20:50:45.567", "Id": "14838", "Score": "3", "Tags": [ "python", "python-2.x" ], "Title": "Multiple Choice Quiz with Stat Tracking" }
14838
<p>This code works fine but is way to bulky for my liking. Is there a better way to go about filtering classes and adding a style to them?</p> <pre><code> $('.leftNav li a').click(function() { $('.leftNav li a').removeClass('active'); $(this).addClass('active'); $('span.overlay').css('opacity','0'); $('ul.thumbnails li').filter('.integrated'), $(function(){ //filter by class $('.integrated span.overlay').css('opacity', '0.9'); //fade overlay to 1 }); return false; //stops link being followed }); $('.leftNav li a.integrated').click(function(){ $('.leftNav li a').removeClass('active'); //remove all active classes $(this).addClass('active'); //add class active $('span.overlay').css('opacity','0'); //hide all active overlays $('ul.thumbnails li').filter('.integrated'), $(function(){ //filter by class $('.integrated span.overlay').css('opacity', '0.9'); //fade overlay to 1 }); return false; //stops link being followed }); $(".leftNav li a.tv").click(function(){ $('.leftNav li a').removeClass('active'); //remove all active classes $(this).addClass('active'); //add class active $('span.overlay').css('opacity','0'); //hide all active overlays $('ul.thumbnails li').filter('.tv'), $(function(){ //filter by class $('.tv span.overlay').css('opacity', '0.9'); //fade overlay to 1 }); return false; //stops link being followed }); $(".leftNav li a.print").click(function(){ $('.leftNav li a').removeClass('active');//remove all active classes $(this).addClass('active'); //add class active $('span.overlay').css('opacity','0'); //hide all active overlays $('ul.thumbnails li').filter('.print'), $(function(){ //filter by class $('.print span.overlay').css('opacity', '0.9'); //fade overlay to 1 }); return false; //stops link being followed }); $(".leftNav li a.digital").click(function(){ $('.leftNav li a').removeClass('active');//remove all active classes $(this).addClass('active'); //add class active $('span.overlay').css('opacity','0'); //hide all active overlays $('ul.thumbnails li').filter('.digital'), $(function(){ //filter by class $('.digital span.overlay').css('opacity', '0.9'); //fade overlay to 1 }); return false; //stops link being followed }); $(".leftNav li a.dm").click(function(){ $('.leftNav li a').removeClass('active');//remove all active classes $(this).addClass('active'); //add class active $('span.overlay').css('opacity','0'); //hide all active overlays $('ul.thumbnails li').filter('.dm'), $(function(){ //filter by class $('.dm span.overlay').css('opacity', '0.9'); //fade overlay to 1 }); return false; //stops link being followed }); $(".leftNav li a.events").click(function(){ $('.leftNav li a').removeClass('active');//remove all active classes $(this).addClass('active'); //add class active $('span.overlay').css('opacity','0'); //hide all active overlays $('ul.thumbnails li').filter('.events'), $(function(){ //filter by class $('.events span.overlay').css('opacity', '0.9'); //fade overlay to 1 }); return false; //stops link being followed }); $(".leftNav li a.social").click(function(){ $('.leftNav li a').removeClass('active');//remove all active classes $(this).addClass('active'); //add class active $('span.overlay').css('opacity','0'); //hide all active overlays $('ul.thumbnails li').filter('.social'), $(function(){ //filter by class $('.social span.overlay').css('opacity', '0.9'); //fade overlay to 1 }); return false; //stops link being followed }); $(".leftNav li a.branding").click(function(){ $('.leftNav li a').removeClass('active');//remove all active classes $(this).addClass('active'); //add class active $('span.overlay').css('opacity','0'); //hide all active overlays $('ul.thumbnails li').filter('.branding'), $(function(){ //filter by class $('.branding span.overlay').css('opacity', '0.9'); //fade overlay to 1 }); return false; //stops link being followed }); </code></pre>
[]
[ { "body": "<p>You have a ton of duplicate code. You can easily extract a common function out, and determine what is variable. This will give you something a little more manageable like the following:</p>\n\n<pre><code>var setup = function(filter, overlayFilter){\n $('.leftNav li a' + filter).click(function() {\n $('.leftNav li a').removeClass('active');\n $(this).addClass('active');\n $('span.overlay').css('opacity','0');\n $('ul.thumbnails li').filter(overlayFilter), $(function(){ //filter by class\n $(overlayFilter + ' span.overlay').css('opacity', '0.9'); //fade overlay to 1\n });\n\n return false; //stops link being followed\n });\n};\n\nsetup(\"\", \".integrated\");\nsetup(\".integrated\", \".integrated\");\nsetup(\".tv\", \".tv\");\nsetup(\".print\", \".print\");\nsetup(\".digital\", \".digital\");\nsetup(\".dm\", \".dm\");\nsetup(\".events\", \".events\");\nsetup(\".social\", \".social\");\nsetup(\".branding\", \".branding\");\n</code></pre>\n\n<p>I'm not saying this is ideal, it's just more manageable. Also, I want to point out that you might have had a bug in your original code, notice that the first call to setup takes an empty string and a \".integrated\" filter, whereas every other call to setup takes the same two parameters. Also, I don't guarantee that the revised code matches your code exactly. This is just the first thing I would do; extracting out some common code into a function. You should be able to get the idea.</p>\n\n<p><strong>Fixing a bug in one place is easier than fixing it in nine places.</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T17:13:05.070", "Id": "14863", "ParentId": "14850", "Score": "1" } }, { "body": "<p>In my opinion there are two solutions to this thing:\nFirst one, if the \"semantically important\" class is the only one in the tag:</p>\n\n<pre><code>$('.leftNav li a').click(function() {\n $('.leftNav li a').removeClass('active');\n $(this).addClass('active');\n $('span.overlay').css('opacity','0');\n semantics = $(this).getAttribute('class');\n if (category === undefined)\n category = \"integrated\";\n $('ul.thumbnails li').filter('.'+category ), $(function(){ \n $('.'+category +' span.overlay').css('opacity', '0.9'); \n });\n return false; //stops link being followed\n });\n</code></pre>\n\n<p>Second solution, if you can modify the tags, can be adding a data- element, which you can then access by simply calling data('something'):\nFor example, if you have the tags as </p>\n\n<pre><code>&lt;a href=\"#\" class=\"something\" data-cat=\"tv\"&gt;&lt;/a&gt;\n</code></pre>\n\n<p>you can then acces the data-cat attribute by calling</p>\n\n<pre><code>$('.leftNav li a').click(function() {\n $('.leftNav li a').removeClass('active');\n $(this).addClass('active');\n $('span.overlay').css('opacity','0');\n category = $(this).data('cat');\n if (category === undefined)\n category = \"integrated\";\n $('ul.thumbnails li').filter('.'+category ), $(function(){ \n $('.'+category +' span.overlay').css('opacity', '0.9'); \n return false; \n });\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T17:22:37.103", "Id": "14865", "ParentId": "14850", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T11:08:07.557", "Id": "14850", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Filtering classes with jQuery" }
14850
<p>Base functionality:</p> <ol> <li>Reading a CSV file and inserting in database after replacing values with web macro.</li> <li><p>Reading values from CSV @ first header information NO,NAME next to that, then read one by one values from CSV and put into web macro context like below:</p> <pre><code>context.put("1","RAJARAJAN") </code></pre></li> <li>Web macro will replace <code>$(NO) ==&gt;1</code> and <code>$(NAME)==&gt;RAJARAJAN</code> values taken from CSV once the web macro replacement is done.</li> <li>Add in statement batch. Once it reaches 1000, execute the batch.</li> </ol> <p>The code is running as per functionality but it takes 4 minutes to parse 50,000 records. I need a performance improvement or a change in logic.</p> <p><strong>Note: I use web macro to replace <code>$(NO)</code> in merge query.</strong></p> <p>Bala.csv </p> <pre><code>NO?NAME ==================&gt;Header Information 1?RAJARAJAN 2?ARUN 3?ARUNKUMAR Connection con=null; Statement stmt=null; Connection con1=null; int counter=0; try{ WebMacro wm = new WM(); Context context = wm.getContext(); String strFilePath = "/home/vbalamurugan/3A/Bala.csv"; String msg="merge into temp2 A using (select '$(NO)' NO,'$(NAME)' NAME from dual)B on(A.NO=B.NO) when not matched then insert (NO,NAME) values(B.NO,B.NAME) when matched then update set A.NAME='Attai' where A.NO='$(NO)'"; String[]rowsAsTokens; con=getOracleConnection("localhost","raymedi_hq","raymedi_hq","XE"); con.setAutoCommit(false); stmt=con.createStatement(); File file = new File(strFilePath); Scanner scanner = new Scanner(file); try { String headerField; String header[]; headerField=scanner.nextLine(); header=headerField.split("\\?"); long start=System.currentTimeMillis(); while(scanner.hasNext()) { String scan[]=scanner.nextLine().split("\\?"); for(int i=0;i&lt;scan.length;i++){ context.put(header[i],scan[i]); } if(context.size()&gt;0){ String m=replacingWebMacroStatement(msg,wm,context); if(counter&gt;1000){ stmt.executeBatch(); stmt.clearBatch(); counter=0; }else{ stmt.addBatch(m); counter++; } } } long b=System.currentTimeMillis()-start; System.out.println("=======Total Time Taken"+b); }catch(Exception e){ e.printStackTrace(); } finally { scanner.close(); } stmt.executeBatch(); stmt.clearBatch(); stmt.close(); }catch(Exception e){ e.printStackTrace(); con.rollback(); }finally{ con.commit(); } // Method For replace webmacro with $ public static String replacingWebMacroStatement(String Query, WebMacro wm, Context context) throws Exception { Template template = new StringTemplate(wm.getBroker(), Query); template.parse(); String macro_replaced = template.evaluateAsString(context); return macro_replaced; } // for getting oracle connection public static Connection getOracleConnection(String IPaddress, String username,String password,String Tns)throws SQLException{ Connection connection = null; try{ String baseconnectionurl ="jdbc:oracle:thin:@"+IPaddress+":1521:"+Tns; String driver = "oracle.jdbc.driver.OracleDriver"; String user = username; String pass = password; Class.forName(driver); connection=DriverManager.getConnection(baseconnectionurl,user,pass); }catch(Exception e){ e.printStackTrace(); } return connection; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T13:32:42.783", "Id": "24244", "Score": "0", "body": "The way this question is worded, it is hard to follow exactly what you are asking. Also, the indentation of the code is not correct, and this is making it hard to understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T13:57:05.750", "Id": "24256", "Score": "4", "body": "The biggest speed gains will come from using a \"Bulk Insert\" feature directly or indirectly. Here is a relevant SO entry: http://stackoverflow.com/questions/2716818/bulk-insert-from-java-into-oracle" } ]
[ { "body": "<p>It appears that you are reading records from a file, processing them in some way and then using the processed data to insert records into a table. Some of the processing involves getting data out of the database.</p>\n\n<p>It looks like you are creating one insert statement for each row from the source file.</p>\n\n<p>I think you would be more likely to get better performance if you broke the processing up into two parts. First, read the file, process the data and create the final version that is going to go into the database. Then, in a separate operation, load the data into the database.</p>\n\n<p>In the first part of the process, you may be able to find ways to improve the performance by caching query results.</p>\n\n<p>You may be able to write the results of the processing out to a temporary file that can be easily imported using an Oracle tool. <a href=\"https://stackoverflow.com/questions/6198863/oracle-import-csv-file-using-sqlplus\">This question</a> may be helpful</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T13:47:35.113", "Id": "14941", "ParentId": "14866", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T17:25:03.300", "Id": "14866", "Score": "2", "Tags": [ "java", "performance", "csv", "oracle" ], "Title": "Merging CSV data into database" }
14866
<p>It's based on the <a href="http://en.wikipedia.org/wiki/Hardy%E2%80%93Weinberg_principle" rel="nofollow">Hardy-Weinberg formula</a>. I used the easygui module because I don't fully understand events in Tkinter yet. It's my first relatively useful script so any constructive criticism would be helpful.</p> <pre><code>from __future__ import division import sys from easygui import * def calculate_frequency(recessive,total): q = (recessive/total)**0.5 #square root of q^2 p = 1-q #since p + q = 1, p = 1-q hzDominantNum = round((p**2)*total,2) #number of homozygous dominant, not percent hzRecessiveNum = round((q**2)*total,2) heterozygousNum = round((2*p*q)*total,2) hzDominantFreq = round((p**2)*100,2) #frequency (percent) hzRecessiveFreq = round((q**2)*100,2) heterozygousFreq = round((2*p*q)*100,2) return hzDominantNum,hzRecessiveNum,heterozygousNum,hzDominantFreq,hzRecessiveFreq,heterozygousFreq #returns all calculations to be printed while True: #loops program until terminated msg = "Leave Total as 100 if you want to enter the percent." #main message lets user know how to input as percent fieldNames = ["How many have the recessive trait","Total population"] fieldValues = ['',100] #first one is blank, the second is defaulted to 100 to make inputing percents easier test = 0 #tests if the proper information has been entered. Test will equal 1 if the conditions are met. while test == 0: fieldValues = multenterbox(msg=msg, title='Enter information about the population', fields=fieldNames, values=fieldValues) if fieldValues == None: sys.exit() #None is returned when the user clicks "Cancel" elif not fieldValues[0].isdigit() or not fieldValues[1].isdigit(): if not ccbox("Please fill out all fields.",'ERROR',('OK','Quit')): sys.exit() elif int(fieldValues[0])&gt;int(fieldValues[1]): if not ccbox("The amount of people with the recessive trait can't be bigger than the total population.",'ERROR',('OK','Quit')): sys.exit() else: test=1 recessive = int(fieldValues[0]) total = int(fieldValues[1]) hzDominantNum,hzRecessiveNum,heterozygousNum,hzDominantFreq,hzRecessiveFreq,heterozygousFreq = calculate_frequency(recessive,total) #displays all the information msg = str(hzDominantNum)+'/'+str(total)+' ('+str(hzDominantFreq)+'%) are normal (homozygous dominant).\n'+''' '''+str(heterozygousNum)+'/'+str(total)+' ('+str(heterozygousFreq)+'%) are carriers (heterozygous).\n'+''' '''+str(hzRecessiveNum)+'/'+str(total)+' ('+str(hzRecessiveFreq)+'%) have the recessive trait (homozygous recessive).' #sees if user wants to quit or continue if not ccbox(msg=msg, title='RESULTS', choices=('Continue', 'Quit'), image=None): sys.exit() </code></pre>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li>call variables <code>this_way</code> not <code>thisWay</code></li>\n<li>use less comments</li>\n<li>put your interaction with user into separate functions</li>\n<li>if code will be splited properly you will be able to user <code>return</code> and <code>while True:</code> instead of <code>test</code> variable</li>\n<li>return object or dict from <code>calculate_frequency</code> rather than long tuple</li>\n<li><p>don't create strings like that:</p>\n\n<p>str(hzDominantNum)+'/'+str(total)+' ('+str(hzDominantFreq)+'%) are normal (homozygous dominant).\\n'</p></li>\n</ul>\n\n<p>this is mutch better:</p>\n\n<pre><code>'%f/%f (%d%%) are normal (homozygous dominant).\\n' % (hzDominantNum, total, hzDominantFreq)\n</code></pre>\n\n<p>if you have to run this as a program do it this way:</p>\n\n<pre><code>def main():\n print \"test\"\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T00:21:19.837", "Id": "24142", "Score": "0", "body": "Good advice. What exactly is the purpose of adding a main loop if I want to run it as a program?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:47:03.157", "Id": "24155", "Score": "0", "body": "that's not a main _loop_, but the `if __name__ == \"__main__\":` entrypoint is used so that you can _also_ reuse `module.calculate_frequency` from another file later if you want to; this also makes it much easier to write unit tests" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T21:09:35.167", "Id": "14873", "ParentId": "14869", "Score": "2" } }, { "body": "<p>Whitespace!<br>\n<code>1 + 1</code> and not <code>1+1</code><br>\n<code>value, value</code> and not <code>value,value</code></p>\n\n<p>Blank lines after imports, loops, function definitions and after five lines of code without (just kidding about the latter) </p>\n\n<p>Break your lines if they're getting too long (http://www.python.org/dev/peps/pep-0008/#maximum-line-length)</p>\n\n<p>And generally have a look at PEP8</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T16:45:56.043", "Id": "15041", "ParentId": "14869", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T19:08:26.163", "Id": "14869", "Score": "2", "Tags": [ "python" ], "Title": "A simple calculator to calculate the frequency of a recessive allele" }
14869
<p>I'm trying to clean up this function to target individual <code>#hdid</code>. I'm also using <code>$this</code>, but with no success. </p> <pre><code>&lt;script&gt; $(function() { $(".delete").click(function() { $('#load').fadeIn(); var commentContainer = $(this).parent(); // var id = $this.(".delete").val(); // var string = id ; // console.log(id); $.ajax({ type: "POST", url: "delete-class.php", data: {hdid: $('#hdid').val()}, cache: false, success: function(){ commentContainer.slideUp('slow', function() {$(this).remove();}); $('#load').fadeOut(); //console.log(string); } }); return false; }); }); &lt;/script&gt; </code></pre>
[]
[ { "body": "<p>If you refactor your code a bit you can do it this way. I'm also making the assumption that you mean <code>.hdid</code> instead of <code>#hdid</code> there should only be one hdid per page if it's really an ID and not a CLASS. <a href=\"http://jsfiddle.net/p5dTt/1/\" rel=\"nofollow\">Here's</a> a quick sample if you're interested in seeing it in action. </p>\n\n<pre><code>&lt;script&gt;\n var DeleteClass = function(hdid){\n $.ajax{\n type: \"POST\",\n url: \"delete-class.php\",\n data: {hdid: hdid.val()},\n cache:false,\n success:function(){\n hdid.parent().slideUp('slow',function(){$(this).remove();});\n }\n }\n\n\n $(function() {\n $(\".delete\").click(function() {\n $('#load').fadeIn();\n $(this).children(\".hdid\").each(function(){\n DeleteClass($(this));\n });\n $('#load').fadeOut();\n return false;\n });\n });\n&lt;/script&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T18:42:07.930", "Id": "24184", "Score": "0", "body": "Any reason you're using `DeleteClass` instead of `deleteClass`? By convention, only Constructor functions should start with an uppercase letter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T18:42:44.183", "Id": "24185", "Score": "0", "body": "Also, please cache you selectors!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T23:02:25.633", "Id": "24208", "Score": "0", "body": "no reason, I don't really write a lot of javascript, so I don't know all the conventions. And I realize there's several things I could do to make it a little better. But the gist of it was the each function on hdid." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T06:50:37.173", "Id": "14883", "ParentId": "14872", "Score": "1" } }, { "body": "<p>I think you actually want to do $(this) instead of $this. $this is a reserved word in PHP, not in JS/Jquery, so in your case it's undefined</p>\n\n<p>$(this) on the other hand is the JQuery object of which your callback is a method of (in your case the clicked .delete element)</p>\n\n<p>Just type $(this).val() and you will get the value of the clicked element.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:01:10.120", "Id": "24150", "Score": "0", "body": "that doesn't answer his question..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T07:53:01.240", "Id": "14885", "ParentId": "14872", "Score": "1" } } ]
{ "AcceptedAnswerId": "14883", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T21:08:29.863", "Id": "14872", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "jQuery to target each #hdid" }
14872
<p>The goal is to solve an ODE numerically with forward Euler method. The programs works well (numerical solution really near analytical one). The problem I see is that the Euler scheme don't jump to eyes, probably because of <code>push_back()</code> functions. This approach is the only one I found to let the time of simulation (number of steps) be variable (change only the <code>t_max</code> constant). Do you have any idea to improve the clarity of the program?</p> <pre><code>/* R. M. 20.08.2012 Exercice 1.2 of Computational Physics, N. Giordano and H. Nakanishi Euler method to solve: dv/dt = a - bv */ #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;vector&gt; void calculate(std::vector&lt;double&gt;&amp; time, std::vector&lt;double&gt;&amp; velocity, const double t_max, const double dt, const double a, const double b) { const int iterations(t_max / dt); for(int i(1); i &lt; iterations; i++) { time.push_back( time[i-1] + dt ); velocity.push_back( a * dt + (1 - b*dt) * velocity[i-1] ); } } void save(const std::vector&lt;double&gt;&amp; time, const std::vector&lt;double&gt;&amp; velocity, const std::string&amp; filename) { std::ofstream file_out(filename); for(int i(0); i &lt; time.size(); i++) { file_out &lt;&lt; time[i] &lt;&lt; ' ' &lt;&lt; velocity[i] &lt;&lt; std::endl; } file_out.close(); } int main() { // Constants constexpr double t_max(8); // Time to end simulation constexpr double dt(0.01); // Time step constexpr double a(10.); // Acceleration constexpr double b(1.); // Air friction std::vector&lt;double&gt; time({0}); // Initial time (t = 0) std::vector&lt;double&gt; velocity({0}); // Initial velocity (v = 0) calculate(time, velocity, t_max, dt, a, b); save(time, velocity, "veocity.dat"); return 0; } </code></pre>
[]
[ { "body": "<p>The smallest change that might make it more readable is to <code>resize</code> the vectors first, so you can index the elements rather than calling <code>push_back</code>.</p>\n\n<p>It's generally a good idea to <code>reserve</code> vectors before a loop anyway if you know how big they're going to end up, and <code>resize</code> will handle that too.</p>\n\n<pre><code>void calculate(std::vector&lt;double&gt;&amp; time, std::vector&lt;double&gt;&amp; velocity,\n const double t_max, const double dt, const double a, const double b)\n{\n const int iterations(t_max / dt);\n time.resize(iterations, 0.);\n velocity.resize(iterations, 0.);\n\n for(int i(1); i &lt; iterations; i++)\n {\n time[i] = time[i-1] + dt;\n velocity[i] = a * dt + (1 - b*dt) * velocity[i-1]; \n }\n}\n</code></pre>\n\n<p>if you're keeping two vectors synchronized like this, it's sometimes nicer to replace them with a single vector whose elements have two fields:</p>\n\n<pre><code>struct step {\n double time;\n double velocity;\n};\n\nvoid calculate(std::vector&lt;step&gt;&amp; steps,\n const double t_max, const double dt, const double a, const double b)\n{\n const int iterations(t_max / dt);\n steps.resize(iterations);\n\n for(int i(1); i &lt; iterations; i++)\n {\n steps[i].time = steps[i-1].time + dt;\n steps[i].velocity = a*dt + (1 - b*dt) * steps[i-1].velocity;\n }\n}\n</code></pre>\n\n<p>this is more of an aesthetic preference though, and it isn't clearly better in your case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T10:47:08.410", "Id": "24147", "Score": "0", "body": "I like very much your solution. Euler scheme is easier to read! Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T10:22:00.677", "Id": "14889", "ParentId": "14877", "Score": "2" } } ]
{ "AcceptedAnswerId": "14889", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T21:48:36.793", "Id": "14877", "Score": "3", "Tags": [ "c++", "c++11", "numerical-methods", "physics" ], "Title": "Solving an ODE numerically with forward Euler method" }
14877
<p>I wrote the following code to test a score-keeping class. The idea was to keep score of a game such that the score was kept across multiple classes and methods. </p> <p>I'm looking for any input on being more efficient, more 'pythonic' and/or just better.</p> <pre><code>import os class Foo(): def __init__(self): self.stored_end = 0 def account(self, a, b): c = float(a) + b print a print b print c self.stored_end = c print self.stored_end def testy(self, q, v): print "\n" print " _ " * 10 z = float(q) + v print self.stored_end self.stored_end = self.stored_end + z print " _ " * 10 print self.stored_end class Bar(): def __init__(self): pass def zippy(self, a, b): print " _ " * 10 print "this is zippy" foo.testy(a, b) class Baz(): def __init__(self): pass def cracky(self, g, m): y = g + m print " _ " * 10 print "calling stored_end" foo.stored_end = foo.stored_end + y print " _ " * 10 print "this is cracky" print "y = %r" % y print foo.stored_end os.system("clear") foo = Foo() foo.account(5, 11) foo.testy(100, 100) bar = Bar() bar.zippy(10, 100) baz = Baz() baz.cracky(1000, 1) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:41:33.970", "Id": "24154", "Score": "0", "body": "Like Matt, I can't really tell what you're trying to achieve: this code is obviously incomplete (there are several references to a `foo` that is never declared), and seems far from minimal. Could you show some runnable code which demonstrates (as simply as possible) what you need to do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T16:07:07.903", "Id": "24178", "Score": "0", "body": "This code runs when I use it. Maybe you need to scroll up to seethe bottom of the code? If not, I think you might be talking over my head." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T16:21:45.057", "Id": "24179", "Score": "0", "body": "Oh yeah, my mistake! Those references are to the global `foo` declared _after_ it's used, which is ... unusual." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T16:42:21.650", "Id": "24180", "Score": "0", "body": "Fair enough. Please rip up the code and tell me where I can do beter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T23:04:26.457", "Id": "24209", "Score": "0", "body": "Also, the fact that a piece of code runs without throwing exceptions is not the same thing as code that has the correct behavior ;)" } ]
[ { "body": "<p>I'm confused on what you are trying to achieve with the code example above, but in general it's usually a bad idea to modify the instance fields of a class from outside of that class. So updating foo.stored_end from another class directly (versus creating a method in foo that takes the new value as a parameter) is usually a bad idea. Here's an example that uses a Game class to keep track of Players and calculate a score.</p>\n\n<pre><code>class Player():\n def __init__(self):\n self.score = 0\n\n def increaseScore(self,x):\n self.score += x\n\n def decreaseScore(self,x):\n self.score -= x\n\nclass Game():\n def __init__(self):\n self.players = []\n\n def addPlayer(self,p):\n self.players.append(p)\n\n def removePlayer(self,p):\n self.players.remove(p)\n\n def printScore(self):\n score = 0\n for p in self.players:\n score += p.score\n print \"Current Score {}\".format(score)\n\np1 = Player()\np2 = Player()\n\ngame = Game()\ngame.addPlayer(p1)\ngame.addPlayer(p2)\n\np2.increaseScore(1)\np1.increaseScore(5)\ngame.printScore()\n\ngame.removePlayer(p1)\ngame.removePlayer(p2)\ngame.printScore()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T07:18:08.827", "Id": "14884", "ParentId": "14881", "Score": "0" } }, { "body": "<p>I think what you may be looking for is the <code>Borg</code> design pattern. It's meant for a single class to maintain state between multiple instances. Not exactly what you're looking for but you could modify it to also maintain state across multiple classes, perhaps by specifying a global for <code>shared state</code>:</p>\n\n<pre><code>## {{{ http://code.activestate.com/recipes/66531/ (r2)\nclass Borg:\n __shared_state = {}\n def __init__(self):\n self.__dict__ = self.__shared_state\n # and whatever else you want in your class -- that's all!\n## end of http://code.activestate.com/recipes/66531/ }}}\n</code></pre>\n\n<p>Here are some links to various code examples of this, non chronological:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/747888/1431750\">Python borg pattern problem</a></li>\n<li><a href=\"http://code.activestate.com/recipes/66531-singleton-we-dont-need-no-stinkin-singleton-the-bo/\" rel=\"nofollow noreferrer\">Singleton? We don't need no stinkin' singleton: the Borg design pattern (Python recipe)</a></li>\n<li><a href=\"https://raw.github.com/faif/python-patterns/master/borg.py\" rel=\"nofollow noreferrer\">Usage example</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T11:28:06.683", "Id": "15024", "ParentId": "14881", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T03:30:05.403", "Id": "14881", "Score": "1", "Tags": [ "python", "classes" ], "Title": "Python: keeping track of info across classes by storing a variable to self" }
14881
<p>I have been trying to optimize the filtering process of a <code>Collection&lt;Alert&gt;</code> based on the <code>DateTime GeneratedOn</code> property of <code>Alert</code> class.</p> <p>Below is the code block which filters the <code>List</code> by taking in <code>From Date</code> and <code>To Date</code>.</p> <pre><code>if (this.Alerts != null) { var fromDt = Convert.ToDateTime(this.FromDateAlert.ToShortDateString() + " " + this.FromTimeAlert.ToLongTimeString()); var toDt = Convert.ToDateTime(this.ToDateAlert.ToShortDateString() + " " + this.ToTimeAlert.ToLongTimeString()); if (fromDt &gt; toDt) { Messages.InfoMessage("FromDate cannot be greater than ToDate", "Alert"); return; } this.IsBusy = true; var filteredAlerts = this.Alerts.Where(a =&gt; (DateTime.Parse(a.Created) &gt;= fromDt) &amp;&amp; (DateTime.Parse(a.Created) &lt;= toDt)); this.PagedAlerts = new PagedCollectionView(filteredAlerts); this.IsBusy = false; } </code></pre> <p>Is there a better way of doing this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T10:28:55.797", "Id": "24145", "Score": "0", "body": "You mean you're trying to make this code faster? Did profiling tell you this code is really a bottleneck in your application?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T10:35:32.993", "Id": "24146", "Score": "2", "body": "But my primary advice would be to try to avoid strings for representing dates and times as much as possible. Certainly don't use them to combine a date with a time, that will be slow and unreliable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T12:00:48.723", "Id": "24149", "Score": "0", "body": "I want a very precise filtering that can even filter out records based on time, that's why I combined the Date and Time, by converting it to ToShortDateString() and ToLongTimeString()." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T17:49:19.783", "Id": "24182", "Score": "2", "body": "Yeah, but I don't see any reason why you would use strings for that. You should work only with the `DateTime`s directly." } ]
[ { "body": "<p><strong>Why are you storing <code>FromDate</code> and <code>FromTime</code> seperately to begin with?</strong></p>\n\n<p>Instead of storing using four properties, use only two, storing both Date and TimeOfDay inside them:</p>\n\n<pre><code>public DateTime FromAlert { get; private set; }\npublic DateTime ToAlert { get; private set; }\n</code></pre>\n\n<p>In the following code:</p>\n\n<pre><code>var fromDt = Convert.ToDateTime(this.FromDateAlert.ToShortDateString() + \" \" + this.FromTimeAlert.ToLongTimeString());\nvar toDt = Convert.ToDateTime(this.ToDateAlert.ToShortDateString() + \" \" + this.ToTimeAlert.ToLongTimeString());\n</code></pre>\n\n<p>You are converting multiple DateTime values to strings in order to parse them again <em>(this should immediately raise a red flag)</em>. When you use the DateTime fields like they were meant to (i.e. containing both Date and TimeOfDay), you can get rid of these redundant conversions:</p>\n\n<pre><code>if (FromAlert &gt; ToAlert)\n{\n Messages.InfoMessage(\"FromDate cannot be greater than ToDate\", \"Alert\"); \n return; //always put this on a separate line!!\n}\n</code></pre>\n\n<blockquote>\n <p>I have been trying to optimize the filtering process of a Collection based on the DateTime<br>\n GeneratedOn property of Alert class.</p>\n</blockquote>\n\n<p>And why are you parsing the string <code>Alert.Created</code> if you already have a <code>DateTime Alert.GeneratedOn</code>? Just use it:</p>\n\n<pre><code>var filteredAlerts = Alerts.Where(a =&gt; a.GeneratedOn &gt;= fromDt &amp;&amp; a.GeneratedOn &lt;= toDt);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T07:06:15.363", "Id": "24321", "Score": "0", "body": "Hi @codesparkle thanks for your valuable post. For some strange and anonymous reason I had been getting the Alert's CreatedOn prop as a string. So I went up to that guy who was associated with this retrieving Alerts of a system from system center operations manager and asked him why can't you just get CreatedOn as DateTime instead of a string so he changed its type to DateTime. The whole mess of multiple conversions and parsing was 'cause of the CreatedOn prop being a string type." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T10:05:54.737", "Id": "14935", "ParentId": "14886", "Score": "3" } } ]
{ "AcceptedAnswerId": "14935", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T07:54:49.397", "Id": "14886", "Score": "2", "Tags": [ "c#", "optimization", "linq", "datetime" ], "Title": "DateTime filter" }
14886
<p>I have written a parser function that returns a JQuery Promise. You can see from the code that this is the top level parser and it delegates out to two other more specific parsers.</p> <p>At the minute it feels a little scattered about with the promise being rejected and resolved all over the place. perhaps it would be better with a try and catch and an error handler that rejected the promsie? how would others approach this?</p> <pre><code>/** * Inspects JSON and delegates to either the sourceParser or the dataParser. * * @constructor * @param {Object} json * * @returns JQuery Promsise * done: - * fail: error message * progress: Progress message */ function Parser(json) { var dfd = $.Deferred(); dfd.notify("Parsing"); if (json &amp;&amp; typeof json === "object") { if (json.hasOwnProperty("GetDataSources")) { var dataSource = json.GetDataSources; if (this.isSuccessfulResponse(dataSource.Response)) { // Notify the caller of any progress dfd.notify("Parsing Source"); // Create a new Source Parser var sourceParser = new SourceParser(dataSource); sourceParser.done(dfd.resolve); sourceParser.fail(dfd.reject); } else { dfd.reject("Parsing Source Failed"); } } else if (json.hasOwnProperty("GetData")) { var data = json.GetData; if (this.isSuccessfulResponse(data.Response)) { // Notify the caller of any progress dfd.notify("Parsing Data"); // Create a new Data Parser var dataParser = new DataParser(data); dataParser.done(dfd.resolve); dataParser.fail(dfd.reject); } else { // Pass back an error message? dfd.reject("Parsing Data Failed"); } } } else { dfd.reject("There was a problem reading the JSON") } return dfd.promise(); } </code></pre>
[]
[ { "body": "<p>Chop up functions longer than 12 lines of code into smaller functions.\nSince you're using <code>this</code>, then you can attach the additional functions to the prototype on <code>Parser</code>.</p>\n\n<p>Here's what I came up with.</p>\n\n<pre><code>function Parser(json) {\n var dfd = $.Deferred();\n dfd.notify(\"Parsing\");\n if (json &amp;&amp; typeof json === \"object\") {\n if (json.hasOwnProperty(\"GetDataSources\")) {\n this._handleData( dfd, json.GetDataSources, SourceParser, \"Source\" );\n } else if (json.hasOwnProperty(\"GetData\")) {\n this._handleData( dfd, json.GetData, DataParser, \"Data\" );\n }\n } else {\n dfd.reject(\"There was a problem reading the JSON\");\n }\n return dfd.promise();\n}\nParser.prototype._handleData = function(dfd, data, OtherParser, type){\n if (data &amp;&amp; this.isSuccessfulResponse(data.Response)) {\n dfd.notify(\"Parsing \" + type );\n var otherParser = new OtherParser(data);\n otherParser.done(dfd.resolve);\n otherParser.fail(dfd.reject);\n } else {\n dfd.reject(\"Parsing \"+ type +\" Failed\");\n }\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T16:20:40.993", "Id": "24845", "Score": "0", "body": "Thanks Larry. I had improved the code since posting it here but your approach is even better still. I have a tendency to create promises on top of promises unnecessarily! and I liked passing the parser as an Argument." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T16:23:38.717", "Id": "24846", "Score": "0", "body": "one thing though sinsided the hasOwnProperty functions should they be something like dfd = this._handleData otherwise the dfd object gets lost." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T16:32:53.577", "Id": "24847", "Score": "0", "body": "It's not really needed because objects are passed by reference and primitive values are passed by value in javascript. But I like returning the value of `dfd` to check the output since `dfd` is a private member. However, if `return dfd;` causes confusion then take it out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T15:25:14.850", "Id": "25303", "Score": "0", "body": "have I mentioned that this is awesome?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T13:15:15.207", "Id": "25362", "Score": "0", "body": "Out of interest, Parser is a constructor function, do you see anything wrong with it returning a promise rather than an instance of itself?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T15:21:11.153", "Id": "25378", "Score": "0", "body": "@CrimsonChin I removed the return since it's causing confusing and not necessary." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T15:55:58.133", "Id": "15326", "ParentId": "14890", "Score": "1" } } ]
{ "AcceptedAnswerId": "15326", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T10:24:44.650", "Id": "14890", "Score": "3", "Tags": [ "javascript", "jquery", "parsing", "json" ], "Title": "JQuery Promise Interface for a (very) simple JSON Parser" }
14890
<p>I have two code examples that I wrote for best practices encrypting a string that I'm looking for feedback both in terms of best practices and security. They are both using <a href="http://en.wikipedia.org/wiki/Authenticated_encryption">authenticated encryption</a>. One is using the <a href="http://www.bouncycastle.org/csharp/">bouncy castle API</a> to do AES-<a href="http://en.wikipedia.org/wiki/Galois/Counter_Mode">GCM</a>and the other is for the limitation of only using the built in .NET API so it does encryption then authentication separately. </p> <p>Each example has the ideal API of passing the key as a byte array (because it was randomly generated). </p> <p><em>However</em> each has a less secure helper method that uses a string password to derive the bytes for the key using PBKDF2 with salt and iterations. The salt is passed in the clear using the authenticated payload.</p> <p><strong>Bouncy Castle AES-GCM</strong></p> <pre><code>/* * This work (Modern Encryption of a String C#, by James Tuley), * identified by James Tuley, is free of known copyright restrictions. * https://gist.github.com/4336842 * http://creativecommons.org/publicdomain/mark/1.0/ */ using System; using System.IO; using System.Text; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; namespace Encryption { public static class AESGCM { private static readonly SecureRandom Random = new SecureRandom(); //Preconfigured Encryption Parameters public static readonly int NonceBitSize = 128; public static readonly int MacBitSize = 128; public static readonly int KeyBitSize = 256; //Preconfigured Password Key Derivation Parameters public static readonly int SaltBitSize = 128; public static readonly int Iterations = 10000; public static readonly int MinPasswordLength = 12; /// &lt;summary&gt; /// Helper that generates a random new key on each call. /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public static byte[] NewKey() { var key = new byte[KeyBitSize / 8]; Random.NextBytes(key); return key; } /// &lt;summary&gt; /// Simple Encryption And Authentication (AES-GCM) of a UTF8 string. /// &lt;/summary&gt; /// &lt;param name="secretMessage"&gt;The secret message.&lt;/param&gt; /// &lt;param name="key"&gt;The key.&lt;/param&gt; /// &lt;param name="nonSecretPayload"&gt;Optional non-secret payload.&lt;/param&gt; /// &lt;returns&gt; /// Encrypted Message /// &lt;/returns&gt; /// &lt;exception cref="System.ArgumentException"&gt;Secret Message Required!;secretMessage&lt;/exception&gt; /// &lt;remarks&gt; /// Adds overhead of (Optional-Payload + BlockSize(16) + Message + HMac-Tag(16)) * 1.33 Base64 /// &lt;/remarks&gt; public static string SimpleEncrypt(string secretMessage, byte[] key, byte[] nonSecretPayload = null) { if (string.IsNullOrEmpty(secretMessage)) throw new ArgumentException("Secret Message Required!", "secretMessage"); var plainText = Encoding.UTF8.GetBytes(secretMessage); var cipherText = SimpleEncrypt(plainText, key, nonSecretPayload); return Convert.ToBase64String(cipherText); } /// &lt;summary&gt; /// Simple Decryption &amp; Authentication (AES-GCM) of a UTF8 Message /// &lt;/summary&gt; /// &lt;param name="encryptedMessage"&gt;The encrypted message.&lt;/param&gt; /// &lt;param name="key"&gt;The key.&lt;/param&gt; /// &lt;param name="nonSecretPayloadLength"&gt;Length of the optional non-secret payload.&lt;/param&gt; /// &lt;returns&gt;Decrypted Message&lt;/returns&gt; public static string SimpleDecrypt(string encryptedMessage, byte[] key, int nonSecretPayloadLength = 0) { if (string.IsNullOrEmpty(encryptedMessage)) throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); var cipherText = Convert.FromBase64String(encryptedMessage); var plaintext = SimpleDecrypt(cipherText, key, nonSecretPayloadLength); return plaintext == null ? null : Encoding.UTF8.GetString(plaintext); } /// &lt;summary&gt; /// Simple Encryption And Authentication (AES-GCM) of a UTF8 String /// using key derived from a password (PBKDF2). /// &lt;/summary&gt; /// &lt;param name="secretMessage"&gt;The secret message.&lt;/param&gt; /// &lt;param name="password"&gt;The password.&lt;/param&gt; /// &lt;param name="nonSecretPayload"&gt;The non secret payload.&lt;/param&gt; /// &lt;returns&gt; /// Encrypted Message /// &lt;/returns&gt; /// &lt;remarks&gt; /// Significantly less secure than using random binary keys. /// Adds additional non secret payload for key generation parameters. /// &lt;/remarks&gt; public static string SimpleEncryptWithPassword(string secretMessage, string password, byte[] nonSecretPayload = null) { if (string.IsNullOrEmpty(secretMessage)) throw new ArgumentException("Secret Message Required!", "secretMessage"); var plainText = Encoding.UTF8.GetBytes(secretMessage); var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload); return Convert.ToBase64String(cipherText); } /// &lt;summary&gt; /// Simple Decryption and Authentication (AES-GCM) of a UTF8 message /// using a key derived from a password (PBKDF2) /// &lt;/summary&gt; /// &lt;param name="encryptedMessage"&gt;The encrypted message.&lt;/param&gt; /// &lt;param name="password"&gt;The password.&lt;/param&gt; /// &lt;param name="nonSecretPayloadLength"&gt;Length of the non secret payload.&lt;/param&gt; /// &lt;returns&gt; /// Decrypted Message /// &lt;/returns&gt; /// &lt;exception cref="System.ArgumentException"&gt;Encrypted Message Required!;encryptedMessage&lt;/exception&gt; /// &lt;remarks&gt; /// Significantly less secure than using random binary keys. /// &lt;/remarks&gt; public static string SimpleDecryptWithPassword(string encryptedMessage, string password, int nonSecretPayloadLength = 0) { if (string.IsNullOrWhiteSpace(encryptedMessage)) throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); var cipherText = Convert.FromBase64String(encryptedMessage); var plaintext = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength); return plaintext == null ? null : Encoding.UTF8.GetString(plaintext); } public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] key, byte[] nonSecretPayload = null) { //User Error Checks if (key == null || key.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key"); if (secretMessage == null || secretMessage.Length == 0) throw new ArgumentException("Secret Message Required!", "secretMessage"); //Non-secret Payload Optional nonSecretPayload = nonSecretPayload ?? new byte[] { }; //Using random nonce large enough not to repeat var nonce = new byte[NonceBitSize / 8]; Random.NextBytes(nonce, 0, nonce.Length); var cipher = new GcmBlockCipher(new AesFastEngine()); var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload); cipher.Init(true, parameters); //Generate Cipher Text With Auth Tag var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length)]; var len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0); cipher.DoFinal(cipherText, len); //Assemble Message using (var combinedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(combinedStream)) { //Prepend Authenticated Payload binaryWriter.Write(nonSecretPayload); //Prepend Nonce binaryWriter.Write(nonce); //Write Cipher Text binaryWriter.Write(cipherText); } return combinedStream.ToArray(); } } public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] key, int nonSecretPayloadLength = 0) { //User Error Checks if (key == null || key.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key"); if (encryptedMessage == null || encryptedMessage.Length == 0) throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); using (var cipherStream = new MemoryStream(encryptedMessage)) using (var cipherReader = new BinaryReader(cipherStream)) { //Grab Payload var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength); //Grab Nonce var nonce = cipherReader.ReadBytes(NonceBitSize / 8); var cipher = new GcmBlockCipher(new AesFastEngine()); var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload); cipher.Init(false, parameters); //Decrypt Cipher Text var cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length); var plainText = new byte[cipher.GetOutputSize(cipherText.Length)]; try { var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0); cipher.DoFinal(plainText, len); } catch (InvalidCipherTextException) { //Return null if it doesn't authenticate return null; } return plainText; } } public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null) { nonSecretPayload = nonSecretPayload ?? new byte[] {}; //User Error Checks if (string.IsNullOrWhiteSpace(password) || password.Length &lt; MinPasswordLength) throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password"); if (secretMessage == null || secretMessage.Length == 0) throw new ArgumentException("Secret Message Required!", "secretMessage"); var generator = new Pkcs5S2ParametersGenerator(); //Use Random Salt to minimize pre-generated weak password attacks. var salt = new byte[SaltBitSize / 8]; Random.NextBytes(salt); generator.Init( PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, Iterations); //Generate Key var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize); //Create Full Non Secret Payload var payload = new byte[salt.Length + nonSecretPayload.Length]; Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length); Array.Copy(salt,0, payload,nonSecretPayload.Length, salt.Length); return SimpleEncrypt(secretMessage, key.GetKey(), payload); } public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0) { //User Error Checks if (string.IsNullOrWhiteSpace(password) || password.Length &lt; MinPasswordLength) throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password"); if (encryptedMessage == null || encryptedMessage.Length == 0) throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); var generator = new Pkcs5S2ParametersGenerator(); //Grab Salt from Payload var salt = new byte[SaltBitSize / 8]; Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length); generator.Init( PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, Iterations); //Generate Key var key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize); return SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength); } } } </code></pre> <p><strong>.NET Built-in Encrypt(AES)-Then-MAC(HMAC)</strong></p> <pre><code>/* * This work (Modern Encryption of a String C#, by James Tuley), * identified by James Tuley, is free of known copyright restrictions. * https://gist.github.com/4336842 * http://creativecommons.org/publicdomain/mark/1.0/ */ using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace Encryption { public static class AESThenHMAC { private static readonly RandomNumberGenerator Random = RandomNumberGenerator.Create(); //Preconfigured Encryption Parameters public static readonly int BlockBitSize = 128; public static readonly int KeyBitSize = 256; //Preconfigured Password Key Derivation Parameters public static readonly int SaltBitSize = 64; public static readonly int Iterations = 10000; public static readonly int MinPasswordLength = 12; /// &lt;summary&gt; /// Helper that generates a random key on each call. /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public static byte[] NewKey() { var key = new byte[KeyBitSize / 8]; Random.GetBytes(key); return key; } /// &lt;summary&gt; /// Simple Encryption (AES) then Authentication (HMAC) for a UTF8 Message. /// &lt;/summary&gt; /// &lt;param name="secretMessage"&gt;The secret message.&lt;/param&gt; /// &lt;param name="cryptKey"&gt;The crypt key.&lt;/param&gt; /// &lt;param name="authKey"&gt;The auth key.&lt;/param&gt; /// &lt;param name="nonSecretPayload"&gt;(Optional) Non-Secret Payload.&lt;/param&gt; /// &lt;returns&gt; /// Encrypted Message /// &lt;/returns&gt; /// &lt;exception cref="System.ArgumentException"&gt;Secret Message Required!;secretMessage&lt;/exception&gt; /// &lt;remarks&gt; /// Adds overhead of (Optional-Payload + BlockSize(16) + Message-Padded-To-Blocksize + HMac-Tag(32)) * 1.33 Base64 /// &lt;/remarks&gt; public static string SimpleEncrypt(string secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null) { if (string.IsNullOrEmpty(secretMessage)) throw new ArgumentException("Secret Message Required!", "secretMessage"); var plainText = Encoding.UTF8.GetBytes(secretMessage); var cipherText = SimpleEncrypt(plainText, cryptKey, authKey, nonSecretPayload); return Convert.ToBase64String(cipherText); } /// &lt;summary&gt; /// Simple Authentication (HMAC) then Decryption (AES) for a secrets UTF8 Message. /// &lt;/summary&gt; /// &lt;param name="encryptedMessage"&gt;The encrypted message.&lt;/param&gt; /// &lt;param name="cryptKey"&gt;The crypt key.&lt;/param&gt; /// &lt;param name="authKey"&gt;The auth key.&lt;/param&gt; /// &lt;param name="nonSecretPayloadLength"&gt;Length of the non secret payload.&lt;/param&gt; /// &lt;returns&gt; /// Decrypted Message /// &lt;/returns&gt; /// &lt;exception cref="System.ArgumentException"&gt;Encrypted Message Required!;encryptedMessage&lt;/exception&gt; public static string SimpleDecrypt(string encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0) { if (string.IsNullOrWhiteSpace(encryptedMessage)) throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); var cipherText = Convert.FromBase64String(encryptedMessage); var plainText = SimpleDecrypt(cipherText, cryptKey, authKey, nonSecretPayloadLength); return plaintext == null ? null : Encoding.UTF8.GetString(plainText); } /// &lt;summary&gt; /// Simple Encryption (AES) then Authentication (HMAC) of a UTF8 message /// using Keys derived from a Password (PBKDF2). /// &lt;/summary&gt; /// &lt;param name="secretMessage"&gt;The secret message.&lt;/param&gt; /// &lt;param name="password"&gt;The password.&lt;/param&gt; /// &lt;param name="nonSecretPayload"&gt;The non secret payload.&lt;/param&gt; /// &lt;returns&gt; /// Encrypted Message /// &lt;/returns&gt; /// &lt;exception cref="System.ArgumentException"&gt;password&lt;/exception&gt; /// &lt;remarks&gt; /// Significantly less secure than using random binary keys. /// Adds additional non secret payload for key generation parameters. /// &lt;/remarks&gt; public static string SimpleEncryptWithPassword(string secretMessage, string password, byte[] nonSecretPayload = null) { if (string.IsNullOrEmpty(secretMessage)) throw new ArgumentException("Secret Message Required!", "secretMessage"); var plainText = Encoding.UTF8.GetBytes(secretMessage); var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload); return Convert.ToBase64String(cipherText); } /// &lt;summary&gt; /// Simple Authentication (HMAC) and then Descryption (AES) of a UTF8 Message /// using keys derived from a password (PBKDF2). /// &lt;/summary&gt; /// &lt;param name="encryptedMessage"&gt;The encrypted message.&lt;/param&gt; /// &lt;param name="password"&gt;The password.&lt;/param&gt; /// &lt;param name="nonSecretPayloadLength"&gt;Length of the non secret payload.&lt;/param&gt; /// &lt;returns&gt; /// Decrypted Message /// &lt;/returns&gt; /// &lt;exception cref="System.ArgumentException"&gt;Encrypted Message Required!;encryptedMessage&lt;/exception&gt; /// &lt;remarks&gt; /// Significantly less secure than using random binary keys. /// &lt;/remarks&gt; public static string SimpleDecryptWithPassword(string encryptedMessage, string password, int nonSecretPayloadLength = 0) { if (string.IsNullOrWhiteSpace(encryptedMessage)) throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); var cipherText = Convert.FromBase64String(encryptedMessage); var plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength); return plaintext == null ? null : Encoding.UTF8.GetString(plainText); } public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null) { //User Error Checks if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey"); if (authKey == null || authKey.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "authKey"); if (secretMessage == null || secretMessage.Length &lt; 1) throw new ArgumentException("Secret Message Required!", "secretMessage"); //non-secret payload optional nonSecretPayload = nonSecretPayload ?? new byte[] { }; byte[] cipherText; byte[] iv; using (var aes = new AesManaged { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { //Use random IV aes.GenerateIV(); iv = aes.IV; using (var encrypter = aes.CreateEncryptor(cryptKey, iv)) using (var cipherStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) using (var binaryWriter = new BinaryWriter(cryptoStream)) { //Encrypt Data binaryWriter.Write(secretMessage); } cipherText = cipherStream.ToArray(); } } //Assemble encrypted message and add authentication using (var hmac = new HMACSHA256(authKey)) using (var encryptedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(encryptedStream)) { //Prepend non-secret payload if any binaryWriter.Write(nonSecretPayload); //Prepend IV binaryWriter.Write(iv); //Write Ciphertext binaryWriter.Write(cipherText); binaryWriter.Flush(); //Authenticate all data var tag = hmac.ComputeHash(encryptedStream.ToArray()); //Postpend tag binaryWriter.Write(tag); } return encryptedStream.ToArray(); } } public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0) { //Basic Usage Error Checks if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("CryptKey needs to be {0} bit!", KeyBitSize), "cryptKey"); if (authKey == null || authKey.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("AuthKey needs to be {0} bit!", KeyBitSize), "authKey"); if (encryptedMessage == null || encryptedMessage.Length == 0) throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); using (var hmac = new HMACSHA256(authKey)) { var sentTag = new byte[hmac.HashSize / 8]; //Calculate Tag var calcTag = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length); var ivLength = (BlockBitSize / 8); //if message length is to small just return null if (encryptedMessage.Length &lt; sentTag.Length + nonSecretPayloadLength + ivLength) return null; //Grab Sent Tag Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length); //Compare Tag with constant time comparison var compare = 0; for (var i = 0; i &lt; sentTag.Length; i++) compare |= sentTag[i] ^ calcTag[i]; //if message doesn't authenticate return null if (compare != 0) return null; using (var aes = new AesManaged { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { //Grab IV from message var iv = new byte[ivLength]; Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length); using (var decrypter = aes.CreateDecryptor(cryptKey, iv)) using (var plainTextStream = new MemoryStream()) { using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write)) using (var binaryWriter = new BinaryWriter(decrypterStream)) { //Decrypt Cipher Text from Message binaryWriter.Write( encryptedMessage, nonSecretPayloadLength + iv.Length, encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length ); } //Return Plain Text return plainTextStream.ToArray(); } } } } public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null) { nonSecretPayload = nonSecretPayload ?? new byte[] {}; //User Error Checks if (string.IsNullOrWhiteSpace(password) || password.Length &lt; MinPasswordLength) throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password"); if (secretMessage == null || secretMessage.Length ==0) throw new ArgumentException("Secret Message Required!", "secretMessage"); var payload = new byte[((SaltBitSize / 8) * 2) + nonSecretPayload.Length]; Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length); int payloadIndex = nonSecretPayload.Length; byte[] cryptKey; byte[] authKey; //Use Random Salt to prevent pre-generated weak password attacks. using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / 8, Iterations)) { var salt = generator.Salt; //Generate Keys cryptKey = generator.GetBytes(KeyBitSize / 8); //Create Non Secret Payload Array.Copy(salt, 0, payload, payloadIndex, salt.Length); payloadIndex += salt.Length; } //Deriving separate key, might be less efficient than using HKDF, //but now compatible with RNEncryptor which had a very similar wireformat and requires less code than HKDF. using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / 8, Iterations)) { var salt = generator.Salt; //Generate Keys authKey = generator.GetBytes(KeyBitSize / 8); //Create Rest of Non Secret Payload Array.Copy(salt, 0, payload, payloadIndex, salt.Length); } return SimpleEncrypt(secretMessage, cryptKey, authKey, payload); } public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0) { //User Error Checks if (string.IsNullOrWhiteSpace(password) || password.Length &lt; MinPasswordLength) throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password"); if (encryptedMessage == null || encryptedMessage.Length == 0) throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); var cryptSalt = new byte[SaltBitSize / 8]; var authSalt = new byte[SaltBitSize / 8]; //Grab Salt from Non-Secret Payload Array.Copy(encryptedMessage, nonSecretPayloadLength, cryptSalt, 0, cryptSalt.Length); Array.Copy(encryptedMessage, nonSecretPayloadLength + cryptSalt.Length, authSalt, 0, authSalt.Length); byte[] cryptKey; byte[] authKey; //Generate crypt key using (var generator = new Rfc2898DeriveBytes(password, cryptSalt, Iterations)) { cryptKey = generator.GetBytes(KeyBitSize / 8); } //Generate auth key using (var generator = new Rfc2898DeriveBytes(password, authSalt, Iterations)) { authKey = generator.GetBytes(KeyBitSize / 8); } return SimpleDecrypt(encryptedMessage, cryptKey, authKey, cryptSalt.Length + authSalt.Length + nonSecretPayloadLength); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T14:15:33.153", "Id": "24169", "Score": "14", "body": "As far as best practices go, I see a few offhand: 1. `static public XXX` is idiomatically written as `public static XXX`. 2. Since all your methods are `static`, the class should be made `static` as well to prevent (useless) instances from being created. 3. Are your bit size numbers near the top of the classes intended to be modified? If so, make them `private` and have `public` properties to access them. If not, make them `const`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T15:01:14.593", "Id": "24174", "Score": "5", "body": "Looks snazzy. One more thing I just noticed: `Rfc2898DeriveBytes` inherits from a class which implements `IDisposable` in .NET 4 and beyond. So its use should be wrapped in a `using` block if you're targeting that version of the framework. .NET 2 (and 3.0/3.5), don't worry about it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T14:38:12.637", "Id": "44834", "Score": "0", "body": "Take a look at the source code in https://effortlessencryption.codeplex.com/ Some of it may be of help" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T15:32:06.223", "Id": "44839", "Score": "0", "body": "@SimonHughes This is here for peer review of best practices in security. But taking a quick peak, effortlessencryption could use some peer review too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-10T15:41:55.723", "Id": "126693", "Score": "0", "body": "/// <param name=\"secretMessage\">The secret message.</param>\n /// <param name=\"password\">The password.</param>\n\netc... are horrible code smell and don't provide anything useful to your method summaries." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-11T07:23:13.940", "Id": "396167", "Score": "0", "body": "I'd like to show [one more sample](https://github.com/lukemerrett/Bouncy-Castle-AES-GCM-Encryption/blob/master/Cryptography/EncryptionService.cs) how to do AES GCM in c#." } ]
[ { "body": "<p>As far as best practices go, I see a few offhand:</p>\n\n<ol>\n<li><code>static public XXX</code> is idiomatically written as <code>public static XXX</code>. </li>\n<li>Since all your methods are <code>static</code>, the class should be made <code>static</code> as well to prevent (useless) instances from being created.</li>\n<li>Are your bit size numbers near the top of the classes intended to be modified? If so, make them <code>private</code> and have <code>public</code> properties to access them. If not, make them <code>const</code>.</li>\n</ol>\n\n<p>One more thing I just noticed: <code>Rfc2898DeriveBytes</code> inherits from a class which implements <code>IDisposable</code> in .NET 4 and beyond. So its use should be wrapped in a <code>using</code> block if you're targeting that version of the framework. .NET 2 (and 3.0/3.5), don't worry about it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T13:26:41.677", "Id": "35598", "ParentId": "14892", "Score": "7" } }, { "body": "<ol>\n<li>The bit sizes at the top should be <code>public static const</code> rather than <code>public static readonly</code>.</li>\n<li>Why are these classes static in the first place? I may have missed something but they should really be normal classes you can instantiate. Which leads to the next point.</li>\n<li>Both classes offer the same interface so you should define a common interface which both classes implement (which you can't do if they are static). This would allow a user to define a dependency on a <code>ICryptoProvider</code> for example which allows him to de/encrypt data without really having to care which implementation is used. It would also make unit tests easier at the same time.</li>\n<li>You repeat a lot of code when dividing the constant bit size definitions by 8. Consider adding a byte size definition as well like <code>KeyByteSize</code>, <code>BlockByteSize</code>, <code>SaltByteSize</code> which is calculated of the bit size. This would makes reading the code a bit easier on the eyes.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T17:16:20.273", "Id": "107068", "Score": "2", "body": "I disagree with turning at least some of those into constants. Changing the number of iterations shouldn't require a rebuild of code using this library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T21:31:06.183", "Id": "107143", "Score": "1", "body": "Sure, but in the original code they are readonly fields without a way to change them anyway - in this case `const` expresses that better. I guess selected values could be made configurable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-08T08:01:32.933", "Id": "107209", "Score": "6", "body": "The difference is that with `static readonly` you only need to rebuild that particular library, with `const` you need to rebuild every project using it. Use public `const` for things that will never change (e.g. mathematical constants) and `static readonly` for configuration like values that merely describe what the library happens to use at the moment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-25T22:00:19.137", "Id": "129490", "Score": "2", "body": "@ChrisWue\nconst vs. static readonly is not about runtime but designtime. The reason public constants shouldn't be used is that if a constant changes all assemblies using the constant must be recompiled because the constant value is compiled into assembly.\nstatic readonly values on the other hand are not compiled into assembly, instead the value is only used at runtime so is safe to change and deploy new version because all clients will start using the new value without having to recompile.\nThere are many articles on this topic if you are interested. See CodesInChaos' comment for exceptions whe" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T08:49:23.410", "Id": "35816", "ParentId": "14892", "Score": "0" } }, { "body": "<p>There are a couple of typos with the casing on <code>var plainText</code> at the return of <code>SimpleDecryptWithPassword</code> and <code>SimpleDecrypt</code>. It's declared in camelCase, but it's later used without capitalization as <code>plaintext</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-15T22:47:04.910", "Id": "97066", "ParentId": "14892", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T12:54:57.017", "Id": "14892", "Score": "53", "Tags": [ "c#", "security", "cryptography", "aes" ], "Title": "Simplified secure encryption of a String" }
14892
<p>I want to search a DB table and display the records in a gridview below is my stored proc</p> <pre><code> create procedure search @Firstname varchar (50), @Lastname varchar (50), @Gender varchar (10), @Maritalstatus varchar (20), @Height varchar (30), @Complexion varchar (10), @Religion varchar (30), @State varchar (30), @Mothertongue varchar (30), @Education varchar (40), @Occupation varchar (40), @Annualincome varchar (30), @Starsign varchar (30), @Rassi varchar (30), @Gothram varchar (30), @DOB datetime, @Timeofbirth nchar (10), @Emailid varchar (50) as begin select Firstname,Lastname,Gender,Maritalstatus,Height,Complexion, Religion,State,Mothertongue,Education,Occupation,AnnualIncome, Starsign,Rassi,Gothram,Dob,TimeOfBirth From Profile_Master where (Firstname LIKE '%'+@Firstname+'%') and (Emailid LIKE '%'+Emailid+'%') end </code></pre> <p>Code in DAL</p> <pre><code> public void getdata(string fname,string lname,string gender,string maritalstatus, string height,string complexion,string religion,string state, string mothertongue,string education,string occupation, string aincome,string starsign,string rasi,string gothram, DateTime dob,DateTime tob,string emailid) { SqlConnection conn = Generic.DBConnection.OpenConnection(); try { SqlCommand cmdd = new SqlCommand("search", conn); cmdd.CommandType = CommandType.StoredProcedure; cmdd.Parameters.AddWithValue("@Firstname", fname); cmdd.Parameters.AddWithValue("@Emailid", emailid); SqlDataAdapter da = new SqlDataAdapter(cmdd); da.Fill(dt); return dt; } catch (Exception) { throw; } </code></pre> <p>in BAL</p> <pre><code>public DataTable search(string fname, string lname, string gender, string maritalstatus, string height, string complexion, string religion, string state,string mothertongue, string education, string occupation, string aincome, string starsign, string rasi, string gothram, DateTime dob, DateTime tob, string emailid) { ProfileMasterDAL dal=new ProfileMasterDAL(); try { returndal.getdata(fname,lname,gender,maritalstatus, height,complexion,religion, state, mothertongue, education, occupation, aincome, starsign, rasi,gothram, dob, tob, emailid); } catch (Exception ex) { throw ex; } } </code></pre> <p>in my UI</p> <pre><code> public DataTable bind(string fname, string lname, string gender, string maritalstatus, string height, string complexion, string religion, string state, string mothertongue, string education, string occupation, string aincome, string starsign, string rasi, string gothram, DateTime dob, DateTime tob, string emailid) { ProfileMasterBLL bll=new ProfileMasterBLL(); try { DataTable dt = bll.search(fname, lname, gender, maritalstatus, height, complexion, religion, state, mothertongue, education, occupation, aincome, starsign, rasi, gothram, dob, tob, emailid); GridView1.DataSource = dt; GridView1.DataBind(); return dt; } catch (Exception ex) { throw ex; } } </code></pre> <p>i want to search with two textboxes how to assign the textbox values??Is there any better way to code than this?Thanks.</p> <p>EDIT</p> <pre><code>protected void Button1_Click(object sender, EventArgs e) { ProfileMasterBLL bll=new ProfileMasterBLL(); string fname = TextBox1.Text; string email = TextBox2.Text; bll.FirstName = fname; bll.EmailID = email; try { DataTable dt=new DataTable(); //what to code here? </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T12:49:02.557", "Id": "24156", "Score": "0", "body": "Well, one thing is that Connection, Command and DataTable aren't being disposed. You might find that codereview.stackexchange is better suited toward style and best practice type questions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T12:56:26.173", "Id": "24157", "Score": "0", "body": "I would for a start make your BL class inherit from you DAL class and make your methods virtual, that way at least if you are not doing anything useful in your BL class you don't have to bother instantiating you DAL class then calling the search method. IT is a good general pattern for n-tier and if you want to do BL in you BL layer you just overide the method and add your logic on top of what the DAL layer is doing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T12:57:23.167", "Id": "24158", "Score": "0", "body": "Using the construction `LIKE '%'+@Firstname+'%'` is a guaranteed table scan, hence super slow. And it opens up the floodgates on SQL-Injection attacks. If you want to pattern match you are better off creating full text indexes and using those." } ]
[ { "body": "<p>if you want assign your textbox</p>\n\n<pre><code>void Btn_Click(Object sender, EventArgs e)\n{\n\n string fname = YourTextBoxName.Text.Trim();\n string emailid =YourTextBoxEmail.Text.Trim(); \n\n //Call bll.Search\n //Bind your grid\n\n}\n</code></pre>\n\n<p>You can use optinal parameters, just modify your format of Search method</p>\n\n<pre><code>public DataTable Search(fname = \"\", lname =\"\" , gender = \"\", maritalstatus, ......)\n{\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T12:58:01.577", "Id": "24159", "Score": "0", "body": "I want to call the values in a button click as i am searching..how to assign the values?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:00:50.993", "Id": "24160", "Score": "0", "body": "I updated answer Chandra" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:03:52.140", "Id": "24161", "Score": "0", "body": "If i call the search method i have to pass the 18 arguments as i have declared them..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:05:18.570", "Id": "24162", "Score": "0", "body": "you ca use optional parameters" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T12:55:23.857", "Id": "14897", "ParentId": "14896", "Score": "0" } }, { "body": "<p>Rather do this in your DAL:</p>\n\n<pre><code> public System.Data.DataSet spGetUser(string firstname)\n {\n using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConnectionString))\n {\n using (System.Data.SqlClient.SqlCommand command = GetCommand(\"sp_GetUser\", connection))\n {\n command.CommandType = System.Data.CommandType.StoredProcedure;\n System.Data.SqlClient.SqlParameter parameter;\n\n parameter = new System.Data.SqlClient.SqlParameter(\"@fname\", System.Data.SqlDbType.VarChar);\n parameter.Direction = System.Data.ParameterDirection.Input;\n parameter.Value = firstname;\n command.Parameters.Add(parameter);\n\n System.Data.DataSet dataSet = new System.Data.DataSet();\n System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(command);\n adapter.Fill(dataSet);\n return dataSet;\n }\n\n\n}\n</code></pre>\n\n<p>Using a USING handles the closing of connections implicitly, so you dont have to.</p>\n\n<p>Edit the above block to add more params etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T12:58:52.993", "Id": "14898", "ParentId": "14896", "Score": "2" } }, { "body": "<p>There are couple of things you could improve </p>\n\n<ol>\n<li><p>Connection, Command, DataTable object should be disposed. </p></li>\n<li><p>Instead of sending too many parameter in the bll.search() method, you should create entity class that will accept all the params that you are passing in to method. Set all params and pass that entity class object to method. Code would be more readable.</p></li>\n<li><p>(Firstname LIKE '%'+@Firstname+'%') and (Emailid LIKE '%'+Emailid+'%') will this code work as expected if you pass empty or null value?</p></li>\n<li><p>In DAL code, There is no need for throwing the exception, you can log your exception in database and return null value from exception block and apply null check where you are getting data from database.</p></li>\n<li><p>In your UI code, Before binding the grid with data, better to initialize it with NULL value and then bind it. Good for practice.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:11:58.490", "Id": "24163", "Score": "0", "body": "In finally i have to dipose the objects?\n\nHow to create a entity class? that accept params?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:15:28.413", "Id": "24164", "Score": "0", "body": "Create a class that will have get/set properties for your parameters that you are passing in bind method. Pass the object of that entity class object in to your bind method and process the data. let me know if you have any confusion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:16:38.273", "Id": "24165", "Score": "0", "body": "You mean in the DAL or can i create new class file and assign them?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:25:24.337", "Id": "24166", "Score": "0", "body": "Not in DAL. Class will be created in BAL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:28:04.970", "Id": "24167", "Score": "0", "body": "oops yeah in BAL can i use a new class file for this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:31:03.257", "Id": "24168", "Score": "0", "body": "I don't know your architecture, yeah you can there is no issue." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:08:34.750", "Id": "14899", "ParentId": "14896", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T12:45:03.693", "Id": "14896", "Score": "3", "Tags": [ "c#", "asp.net", "sql-server" ], "Title": "Search using stored procedure" }
14896
<p>Let's say I want to parse audio track information into two variables like this:</p> <ul> <li><code>'2/15'</code> -> <code>track = 2, num_tracks = 15</code></li> <li><code>'7'</code> -> <code>track = 7, num_tracks = None</code></li> </ul> <p>What's an elegant way to do this in Python? For example:</p> <pre><code>track, num_tracks = track_info.split('/') </code></pre> <p>This works for the first format, but not for the second, raising <em>ValueError: need more than 1 value to unpack</em>. So I came up with this:</p> <pre><code>try: track, num_tracks = track_info.split('/', 1) except: track, num_tracks = track_info, None </code></pre> <p>How can this be more elegant or better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T07:34:41.070", "Id": "24173", "Score": "3", "body": "Don't use a bare `except` though; catch specific exceptions only. You'd be amazed how many bugs could be masked by blanket `except` statements." } ]
[ { "body": "<p>This may be overly generic, but could be reused. It \"pads\" a sequence by making it long enough to fit the requested length, adding as many repetitions as necessary of a given padding item.</p>\n\n<pre><code>def right_pad(length, seq, padding_item=None):\n missing_items = length - len(seq)\n return seq + missing_items * [ padding_item]\n</code></pre>\n\n<p>If the sequence is long enough already, nothing will be added.\nSo the idea is to extend to 2 elements with None, if the second is not present:</p>\n\n<pre><code>track, num_tracks = right_pad(2, track_info.split('/'))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T16:16:20.803", "Id": "14906", "ParentId": "14901", "Score": "6" } }, { "body": "<blockquote>\n<pre><code>try:\n track, num_tracks = track_info.split('/', 1)\nexcept:\n track, num_tracks = track_info, None\n</code></pre>\n</blockquote>\n\n<p>Honestly, this is not a terrible solution. But you should almost never use <code>except:</code>; you should catch a specific exception.</p>\n\n<p>Here is another way:</p>\n\n<pre><code>tracks, _, num_tracks = text.partition('/')\nreturn int(tracks), int(num_tracks) if num_tracks else None\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-10T18:05:29.607", "Id": "107580", "Score": "1", "body": "I would remove the parameter maxsplit=1 to split. If the text contains more than one '/' it is a good thing to get an error." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-08-21T17:04:17.573", "Id": "14907", "ParentId": "14901", "Score": "19" } }, { "body": "<p>You can concatenate an array with your default value.</p>\n\n<pre><code>track, num_tracks = (track_info.split('/', 1) + [None])[:2]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-01T14:22:47.970", "Id": "200753", "ParentId": "14901", "Score": "5" } } ]
{ "AcceptedAnswerId": "14907", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T03:26:11.547", "Id": "14901", "Score": "32", "Tags": [ "python", "parsing", "error-handling", "null" ], "Title": "Using default None values in Python when assigning split() to a tuple" }
14901
<p>I cannot quite see all the advantages of OOP PHP. I have already started translating some procedural functions into object oriented. How is the second code better than the first one? Is there anything I am missing? Could it be improved? It is surely a newbie question but I'm starting now with the Object Oriented aspect. Thank you all!</p> <h2>Old Procedural code</h2> <pre><code>//LANGUAGES //Detect the language if ( !empty($_POST['lang']) ) // If the user tries to change the language { $Lang = mysql_real_escape_string($_POST['lang']); // Assign the language to variable $Lang. $_SESSION['lang']= $_POST['lang']; //Sets the session to have that language. if ($Logged==1) // If user is logged mysql_query("INSERT INTO users (lang) VALUES ('$Lang') WHERE user='$User'"); // Saves the language into user preferences } else // If no request is done. { if ( !empty ($_SESSION['lang'])) // If the session exists (not empty) $Lang = $_SESSION['lang']; // Assign the session language to variable $Lang. else // If it doesn't exist $Lang = substr ($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); // Get it from the browser } //If the language is not supported (or still doesn't exist), then put "en" as default. Supported so far: en, es. if ( $Lang !== "en" &amp;&amp; $Lang !== "es") $Lang="en"; ////lang() function //Return the right name of the language. //Taken from here: http://www.w3schools.com/tags/ref_language_codes.asp //And here: http://web.forret.com/tools/html.asp function lang () { global $Lang; // Action to do. $numargs = func_num_args(); // Get the number of arguments that are being passed. if ($numargs == 1) // If there is one $Arg=func_get_arg(0); // Set $Arg with that value. Example: $ArgLang="en" else return $Lang; //If there is no language passed, echoes the default one switch ($Arg) { case "bn": echo "&amp;#2476;&amp;#2494;&amp;#2434;&amp;#2482;&amp;#2494;"; break; //Bengali case "de": echo "Deutsch"; break; //German [Deutsch] case "en": echo "English"; break; //English case "es": echo "Espa&amp;#241;ol"; break; //Spanish [Español] case "fr": echo "Fran&amp;#231;ais"; break; //French [Français] case "it": echo "Italiano"; break; //Italian [Italiano] case "ja": echo "&amp;#26085;&amp;#26412;&amp;#35486;"; break; //Japanese case "pt": echo "Portugu&amp;#234;s"; break; //Portuguese [Português] case "ru": echo "&amp;#1088;&amp;#1091;&amp;#1089;&amp;#1089;&amp;#1082;&amp;#1080;&amp;#1081;"; break; //Russian [русский] case "zh": echo "&amp;#31616;&amp;#20307;&amp;#20013;&amp;#25991;"; break; //Simplified chinese [简体中文] default: echo "Weird error. Please report."; break; } } </code></pre> <h2>New Object Oriented code</h2> <pre><code>class Language { public $Lang; public function __construct() { if ( !empty($_POST['lang']) ) // If the user tries to change the language { $this-&gt;Lang = mysql_real_escape_string($_POST['lang']); // Assign the language to variable $Lang. $_SESSION['lang']= $_POST['lang']; //Sets the session to have that language. if ($Logged==1) // If user is logged mysql_query("INSERT INTO users (lang) VALUES ('$this-&gt;Lang') WHERE user='$User'"); // Saves the language into user preferences } else // If no request is done. { if ( !empty ($_SESSION['lang'])) // If the session exists (not empty) $this-&gt;Lang = $_SESSION['lang']; // Assign the session language to variable $Lang. else // If it doesn't exist $this-&gt;Lang = substr ($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); // Get it from the browser //If the language is not supported (or still doesn't exist), then put "en" as default. Supported so far: en, es. if ( $this-&gt;Lang !== "en" &amp;&amp; $this-&gt;Lang !== "es") $this-&gt;Lang="en"; } //Return the right name of the language. //Taken from here: http://www.w3schools.com/tags/ref_language_codes.asp and here: http://web.forret.com/tools/html.asp public function lang($Arg) { switch ($Arg) { case "bn": return "&amp;#2476;&amp;#2494;&amp;#2434;&amp;#2482;&amp;#2494;"; break; //Bengali [বাংলা] case "de": return "Deutsch"; break; //German [Deutsch] case "en": return "English"; break; //English case "es": return "Espa&amp;#241;ol"; break; //Spanish [Español] case "fr": return "Fran&amp;#231;ais"; break; //French [Français] case "it": return "Italiano"; break; //Italian [Italiano] case "ja": return "&amp;#26085;&amp;#26412;&amp;#35486;"; break; //Japanese case "pt": return "Portugu&amp;#234;s"; break; //Portuguese [Português] case "ru": return "&amp;#1088;&amp;#1091;&amp;#1089;&amp;#1089;&amp;#1082;&amp;#1080;&amp;#1081;"; break; //Russian [русский] case "zh": return "&amp;#31616;&amp;#20307;&amp;#20013;&amp;#25991;"; break; //Simplified chinese [简体中文] default: return "English"; error("Invalid language"); break; //English + error } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T14:13:42.827", "Id": "24336", "Score": "0", "body": "See the update in my answer for some of the answers to your questions from the comments. In the future only use one name per comment, or if the comment is on the answer of someone you are trying to get the attention of you don't have to call their name, they will be informed automatically, this allows you to call someone else at the same time. Corbin isn't likely to see that last comment because he wasn't \"called\"." } ]
[ { "body": "<p>When you have just 1 class, it doesn't really come into perspective...the fact that you're modularizing your code is one of the many bonuses of OOP. Here's your code, cleaned up, with an added Database class:</p>\n\n<pre><code>class DB{\n private $query; \n\n public function __construct(){}\n\n /**\n * Save a user preference\n */\n public function SaveUserPreference($table, $values, $where){\n $this-&gt;dbConnect();\n\n # Build the query\n $this-&gt;query = \"INSERT INTO \";\n if( !empty($table) ) $this-&gt;query .= $table;\n if( !empty($values) ) $this-&gt;query .= \"VALUES(\" . $values . \") \";\n if( !empty($where) ) $this-&gt;query .= \"WHERE \" . $where; \n\n mysql_query($this-&gt;query);\n }\n\n /**\n * Clean data using mysql_real_escape_string\n */\n public function cleanData($data){\n return mysql_real_escape_string($data);\n }\n\n /**\n * Create a mysqli connection\n */\n private function dbConnect(){}\n}\n</code></pre>\n\n<p>And here's your Language class, which extends class DB, so that it can use its methods:</p>\n\n<pre><code>class Language extends DB{\n public $language, $isLogged;\n\n public function __construct(){\n parent::__construct(); \n }\n\n public function setPost($_POST){\n $this-&gt;language = $this-&gt;cleanData($_POST);\n }\n\n /**\n * If the user tries to change the language\n */\n function setLanguage(){\n if( !empty($this-&gt;language['lang']) ){\n $_SESSION['lang'] = $this-&gt;language['lang'];\n\n # If logged, save the language into user preferences in db\n if ($this-&gt;isLogged == 1)\n $this-&gt;SaveUserPreference(\"users(`lang`)\", $this-&gt;language, \"user=\".$User);\n } else {\n if ( !empty ($_SESSION['lang']) ) # If the session exists\n $this-&gt;language = $_SESSION['lang']; # Assign the session language to variable $Lang.\n else # If it doesn't exist\n $this-&gt;language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); # Get it from the browser\n\n # If the language is not supported (or still doesn't exist), then put \"en\" as default. Supported so far: en, es.\n if ( $this-&gt;language !== \"en\" &amp;&amp; $this-&gt;language !== \"es\") $this-&gt;language = \"en\";\n }\n }\n\n /**\n * Return the right name of the language.\n * @Ref: http://www.w3schools.com/tags/ref_language_codes.asp\n * @Ref: http://web.forret.com/tools/html.asp\n */\n public function GetLanguage($arg){\n switch ($arg){\n case \"bn\": return \"&amp;#2476;&amp;#2494;&amp;#2434;&amp;#2482;&amp;#2494;\"; break; # Bengali\n case \"de\": return \"Deutsch\"; break; # German\n case \"en\": return \"English\"; break; # English\n case \"es\": return \"Espa&amp;#241;ol\"; break; # Spanish [Español]\n case \"fr\": return \"Fran&amp;#231;ais\"; break; # French [Français]\n case \"it\": return \"Italiano\"; break; # Italian [Italiano]\n case \"ja\": return \"&amp;#26085;&amp;#26412;&amp;#35486;\"; break; # Japanese\n case \"pt\": return \"Portugu&amp;#234;s\"; break; # Portuguese [Português]\n case \"ru\": return \"&amp;#1088;&amp;#1091;&amp;#1089;&amp;#1089;&amp;#1082;&amp;#1080;&amp;#1081;\"; break; # Russian [???????]\n case \"zh\": return \"&amp;#31616;&amp;#20307;&amp;#20013;&amp;#25991;\"; break; # Simplified chinese [????]\n default: return \"English\"; break; # return English\n }\n }\n}\n</code></pre>\n\n<p>Good, now lets use our classes. Note that we only initialize the parent class, and we don't need to init the DB class separately because we can call the DB methods from the parent class. </p>\n\n<pre><code>#Initialize our class\n$r = new Language;\n\n# Build a fake post for testing\n$_POST = array('lang' =&gt; 'en', 'asa' =&gt; 54);\n\n# Set options\n$r-&gt;setPost($_POST);\n$r-&gt;isLogged = 1;\n\n# Set Language\n$r-&gt;setLanguage();\n</code></pre>\n\n<p>Now that we've saved our users language preferences, let's see what the long form is:</p>\n\n<pre><code># Now, get the long version of the user language\necho $r-&gt;GetLanguage($r-&gt;language);\n</code></pre>\n\n<p>That was easy! And no need to write a mysql_query here and there, just write once and forget about it. We have a set of classes that is modular, abstract, and the parent class inherits methods from its child classes, so no need to reinitialize a DB class, we can just recycle the language class (although in many cases, you shouldn't do this). </p>\n\n<p>OOP is good in some cases, not all. You wouldn't bring a gun to a tickle-fight, would you? Your use of OOP completely depends on what your project is and how big it is, amongst other things.</p>\n\n<p>By the way, here's the above code in action:\n <a href=\"http://juanleonardosanchez.com/data/sandbox/php/test.php\" rel=\"nofollow\">http://juanleonardosanchez.com/data/sandbox/php/test.php</a></p>\n\n<p>You can give it different codes via GET:\n <a href=\"http://juanleonardosanchez.com/data/sandbox/php/test.php?lang=fr\" rel=\"nofollow\">http://juanleonardosanchez.com/data/sandbox/php/test.php?lang=fr</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T08:36:03.300", "Id": "24237", "Score": "0", "body": "I'm still trying to understand your ultra-complete post! It will take me some time, but thank you so much!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T15:17:26.837", "Id": "24260", "Score": "0", "body": "No worries @FrankPresenciaFandos - if you have any questions about my post, please feel free to post them up here as a comment" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:39:46.723", "Id": "24268", "Score": "0", "body": "There are a couple things you could take from my answer too. Otherwise, good job +1 :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T17:26:20.367", "Id": "24273", "Score": "0", "body": "Isn't `public function cleanData($data) { return mysql_real_escape_string($data); }` a bit redundant? Creating a function that only calls a function? The only explanation I could see for that is to be able to change `mysql_real_escape_string()` for other method in all my code, but since this is not necessary, is it okay to delete it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T20:07:18.807", "Id": "24285", "Score": "0", "body": "There's a few major issues in this answer. The language should by no means extend DB, and the language class shouldn't be directly touching $_POST." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T00:52:38.530", "Id": "24296", "Score": "0", "body": "@jsanc623 I think I have understood almost everything. Aren't both `public function __construct()` unnecessary, since they are empty? Corbin , if not extending, how would you do it? Creating a new class and calling it? And how do yo suggest handling the $_POST data?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T16:52:17.107", "Id": "24345", "Score": "0", "body": "@FrankPresenciaFandos The proper course of action would be to pass a DB instance to the class in the constructor. A Language object isn't a DB object, and it sure shouldn't be responsible for connecting to a database. As for the $_POST data, that answer gets a bit more complex. I will probably write a full response later in an answer when I have time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T17:11:10.650", "Id": "24348", "Score": "0", "body": "Don't worry, I don't know what I was thinking asking for that. Normally I just need to be told what I'm doing wrong and I'll find my way around. I'm [googling](http://www.daniweb.com/web-development/php/threads/202923/using-get-post-request-in-oop) right now about how to handle $_GET and $_POST data, if I have more specific doubts I'll ask again. Thank you Corbin." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T19:19:16.787", "Id": "24356", "Score": "0", "body": "@mseancole answered in great detail and fixed many of my errors/mistakes in his answer below. And nope, as mseancole mentioned, cleanData isn't redundant, its just very simple. You can add more to the body to clean the data than just mysql_real_escape_string such as regex checking for patterns, etc..." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T22:04:37.787", "Id": "14921", "ParentId": "14905", "Score": "2" } }, { "body": "<p>I'm glad to see you lost the globals. That's the first thing I saw and I immediately had to perform an exorcism on my computer. Globals are always bad, avoid them like the plague. I have a few comments to add to jsanc623's post. He had a good start, but there are some things he did not cover, or that he could do better as well.</p>\n\n<p>First, in your attempt you escaped the POST variable very nicely for MySQL, but then you dumped the unmodified version into the SESSION to be reused. It will be clean the first time this is run, but then every other time it will be using raw data. This is bad, just pass the session the class property <code>$Lang</code> since it has already been cleaned.</p>\n\n<pre><code>$this-&gt;Lang = mysql_real_escape_string( $_POST[ 'lang' ] );\n$_SESSION[ 'lang' ] = $this-&gt;Lang;\n</code></pre>\n\n<p>It appears that you are recreating a boolean with your <code>$Logged</code> variable. Don't do this, just set it to a boolean so you don't have to worry about type conversions, then you can do cool things like below. Admittedly, you can do this without booleans, but still, the concept is sound, no reason to reinvent a language construct for such a simple task.</p>\n\n<pre><code>if( $Logged ) {\n//OR\nif( ! $Logged ) {\n</code></pre>\n\n<p>A switch statement in this context seems inefficient. I would set this up in an array like so:</p>\n\n<pre><code>$languages = array(\n \"bn\" =&gt; \"&amp;#2476;&amp;#2494;&amp;#2434;&amp;#2482;&amp;#2494;\",//Bengali [?????]\n \"de\" =&gt; \"Deutsch\",//German [Deutsch]\n //etc...\n);\n\n$language = array_key_exists( $Arg, $languages ) ? $languages[ $Arg ] : 'English';\n</code></pre>\n\n<p>Here's something from jsanc623's post. If a variable is empty, appending it onto a string will not change that string, so all these <code>empty()</code> checks are unnecessary and just add overhead. Additionally, both of you appear to be fond of braceless if statements. This is PHP not Python. While this is possible, it is not advisable. This can lead to mistakes and illegible code. Normally I rant about PHP also considering this bad practice, but they have since removed it and have updated their \"if\" doc page to reflect this syntax. I think this was a bad move as it misleads beginners because it doesn't explain that this syntax only allows one argument. Some helpful commenter mentioned it, but PHP neglected to.</p>\n\n<pre><code>if( !empty($table) ) $this-&gt;query .= $table;\nif( !empty($values) ) $this-&gt;query .= \"VALUES(\" . $values . \") \";\nif( !empty($where) ) $this-&gt;query .= \"WHERE \" . $where; \n</code></pre>\n\n<p>When extending a class, it is not necessary to redefine the constructor unless you are planning on manipulating it. I believe this is a habit Java people are bringing over to PHP. Its only necessary to override and then call the parent constructor if you are planning on changing some data going into the parent constructor, or that coming out.</p>\n\n<pre><code>public function __construct(){\n $before = 'variable used by parent constructor, usually passed as param';\n parent::__construct(); \n $after = 'variable defined in parent constructor';\n}\n</code></pre>\n\n<p>I agree with the rest of jsanc623's post. As he said, OOP only really starts to make sense when used between many classes. Its not always necessary to use classes, sometimes it makes more sense to use just plain procedural code and functions. Just remember, classes/functions don't define OOP/Not-OOP. A class that doesn't follow the key principles of OOP is just a class. And while I've not really looked into it, you can apparently have groups of functions that are considered OOP too.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Perhaps I jumped to conclusions on jsanc623's post. My only excuse is that I mostly skimmed over it, I should really stop that. It does give the general \"right\" idea. But, just as Corbin said, there are some major problems in it.</p>\n\n<p>Language should not extend DB because it isn't a database. It can use the db, but extending it is the wrong thing to do here. Extending is what you do when two classes implicitly share resources and a purposes. For instance, you could create a MySQL class to extend DB, not saying to do that, just trying to demonstrate. In this instance, you would create a db property in the Language constructor so that it can be reused through out the rest of the class.</p>\n\n<pre><code>public function __construct() {\n $this-&gt;db = new DB();\n}\n</code></pre>\n\n<p>I believe the empty methods in jsanc623's classes are there to illustrate the need for them, not to demonstrate using empty methods. You should still initialize your class with a constructor. I don't know what kinds of things you would need to do to initialize your object. There are some generic things I can think of off the top of my head, such as setting default values to class properties and calling the methods necessary for creating a database or connecting to one, but the exact things you will need to do are up to you. Same with the <code>dbConnect()</code> method.</p>\n\n<p><code>cleanData()</code> is not redundant. The class doesn't know that it needs to clean data for MySQL, this method could just as easily be changed to use htmlspecialchars, or anything else. This is one of the core ideas behind OOP. You have a method whose current contents can be changed without disrupting the flow of the rest of the program. A class should be generic enough to be used in many situations, not specialized for one only. That's what extending classes is for, and even then the specializing should only go so far as to add features and not change it so that other situations couldn't reuse the same solution. Think of that MySQL extending DB scenario again. They are both databases and share very similar characteristics. MySQL still does everything DB does, but it is specialized for MySQL and it can be reused in other situations that require MySQL.</p>\n\n<p>I hope this makes sense, I feel like I'm starting to ramble. OOP is one of the harder concepts to grasp. You could spend days looking at descriptions and explanations before one, with only slightly different wording, finally clicks for you. At least, that's how it was for me. Don't be discouraged, keep asking questions.</p>\n\n<p>Oh, and before I forget. Passing <code>$_POST</code> as a parameter in a function/method, is a bad idea. I would say even passing it TO a function/method is bad. This is a reserved PHP super global, as such, it contents should not be changed only used. Make a copy of it and manipulate that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T01:07:18.500", "Id": "24298", "Score": "0", "body": "True, I just missed the $_POST bit. The only reason I didn't use the language array was because the `default` of the `switch` provided a good way to return 'English'. Your solution is **much** neater. I never did python, the only reason I use it is so 1. I know that it's inside for sure (habit) and 2. I can include later statements easier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T17:33:06.977", "Id": "24349", "Score": "0", "body": "One more thing, strange enough, through [Yaho answers](http://answers.yahoo.com/question/index?qid=20071225154159AA6avO6) I found out what the ? and : meant in your code. But if I wanted to call a function apart of returning the default language if it was not found? A custom error function that logs the info. This code works but can I make it smaller like your answer? `if ( array_key_exists( $Arg, $languages ) ) echo $languages [$Arg]; else { echo \"English\"; error(\"Undetermined language\"); }` Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T18:25:26.260", "Id": "24352", "Score": "1", "body": "That's called a ternary statement. Google that to get a better answer than yahoo. Anyways, its the same as an if/else statement. The if is handled by the `?` and the else is handled by the `:`. `echo array_key_exists( $Arg, $languages ) ? $languages[ $Arg ] : 'English';` Don't go too crazy with those, they are a powerful tool, but should only be used when they can ENHANCE legibility and not hinder it. This means no nested ternary, and no super long ternary. In fact, there are many developers that think about as much of ternary, as I think of braceless statements. You've been warned :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T19:12:05.737", "Id": "24354", "Score": "0", "body": "Excellent points...and proves even I have things to learn :) Thanks for that @mseancole!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T19:16:59.910", "Id": "24355", "Score": "0", "body": "\"I believe the empty methods in jsanc623's classes are there to illustrate the need for them, not to demonstrate using empty methods.\" - I should have pointed this out, but yes, I just wrote them to illustrate that they should/might be there, but didn't give them a body." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:39:03.323", "Id": "14952", "ParentId": "14905", "Score": "3" } } ]
{ "AcceptedAnswerId": "14921", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T16:12:15.460", "Id": "14905", "Score": "2", "Tags": [ "php", "object-oriented" ], "Title": "OOP PHP with language detection" }
14905
<p>I'm working on a battery indicator feature in my app, and I was wondering if there is a better way than what I am doing to check what image should be displayed when. I am currently using <code>if</code> statements, but I was wondering if case statements would be a better option.</p> <pre><code>- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { UIDevice *device = [UIDevice currentDevice]; //Observer for the battery level //Updates the percentage label and the battery icon if (KEY_PATH_IF_THEN(@"batteryLevel")) { LabelBatteryStatus.text = [NSString stringWithFormat:@"%.0f%%", device.batteryLevel * 100]; //shows battery image if (kBatteryLevelBetween(100, 100)) { batteryImage.image = [UIImage imageNamed:@"battery100fullycharged.png"]; } else if (kBatteryLevelBetween(99, 81)) { batteryImage.image = [UIImage imageNamed:@"battery90.png"]; } else if (kBatteryLevelBetween(80, 65)) { batteryImage.image = [UIImage imageNamed:@"battery75.png"]; } else if (kBatteryLevelBetween(64, 41)) { batteryImage.image = [UIImage imageNamed:@"battery50.png"]; } else if (kBatteryLevelBetween(40, 35)) { batteryImage.image = [UIImage imageNamed:@"battery30.png"]; } else if (kBatteryLevelBetween(34, 15)) { batteryImage.image = [UIImage imageNamed:@"battery20.png"]; } else if (kBatteryLevelBetween(14, 0)) { batteryImage.image = [UIImage imageNamed:@"battery10.png"]; } } } </code></pre> <p><strong><code>kBatteryLevelBetween</code>:</strong></p> <pre><code>#define kBatteryLevelBetween(higherNum,lowerNum) (device.batteryLevel *100 &lt;= higherNum &amp;&amp; device.batteryLevel *100 &gt;= lowerNum) </code></pre>
[]
[ { "body": "<p>I think this code is easier to read and should result in significantly less comparisons, as it just compares in every step the lower bound, where as your define macro checks twice each. And note that you are checking also equality. this should result into </p>\n\n<ol>\n<li>at least 2 checks at cpu level and </li>\n<li>checking equality for floats in nver a good idea, as due to rounding errors they tend to be not equal, even if in pure math they should be (a <code>1</code> might be save as <code>0.99</code> or <code>1.001</code>) </li>\n<li>and if you would check integer numbers for being in some range it make sense, to have an equal check just on one bound like <code>if (a &lt;= higherNum &amp;&amp; b &gt; lowerNum)</code></li>\n</ol>\n\n<p>my code suggestion</p>\n\n<pre><code>-(NSUInteger)batteryLevel\n{\n UIDevice *device = [UIDevice currentDevice];\n float level = device.batteryLevel;\n if(level &gt; .99) return 100;\n if(level &gt; .80) return 90;\n if(level &gt; .64) return 75;\n if(level &gt; .40) return 50;\n if(level &gt; .34) return 30;\n if(level &gt; .14) return 20;\n return 10;\n}\n\n\n-(UIImage *)imageForBatteryLevel\n{\n NSUInteger level = [self batteryLevel];\n NSString *imageName;\n if(level &gt; 99){\n imageName = @\"battery100fullycharged.png\";\n } else {\n imageName = [NSString stringWithFormat:@\"battery%d.png\", level];\n }\n return [UIImage imageNamed:imageName];\n}\n\n- (void)observeValueForKeyPath:(NSString *)keyPath \n ofObject:(id)object \n change:(NSDictionary *)change \n context:(void *)context \n{\n if (KEY_PATH_IF_THEN(@\"batteryLevel\")) {\n LabelBatteryStatus.text = [NSString stringWithFormat:@\"%.0f%%\", device.batteryLevel * 100];\n batteryImage.image = [self imageForBatteryLevel];\n }\n}\n</code></pre>\n\n<hr>\n\n<p>I was taught at university, that in assembler code checking equality is actually done by checking, that the value is neither smaller nor greater, this makes it 2 comparisons. I am not sure, that this is true for every CPU, but let's walk through an example with that. </p>\n\n<p>Let's assume, the level is down to 2%. with your code, it will go liek this:</p>\n\n<ol>\n<li>is .02 * 100 bigger or equal than 100 and</li>\n<li>is .02 * 100 smaller or equal than 100 -> No</li>\n<li>is .02 * 100 smaller or equal than 99 and</li>\n<li>is .02 * 100 bigger or equal than 81 -> No</li>\n<li>is .02 * 100 smaller or equal than 80 and</li>\n<li>is .02 * 100 bigger or equal than 65 -> No</li>\n<li>is .02 * 100 smaller or equal than 64 and</li>\n<li>is .02 * 100 bigger or equal than 41 -> No</li>\n<li>is .02 * 100 smaller or equal than 40 and</li>\n<li>is .02 * 100 bigger or equal than 35 -> No</li>\n<li>is .02 * 100 smaller or equal than 34 and</li>\n<li>is .02 * 100 bigger or equal than 15 -> No</li>\n<li>is .02 * 100 smaller or equal than 14 -> Yes</li>\n</ol>\n\n<p>As you see you have 13 comparisons for smaller or bigger and 13 for equal. that yields in 39 comparisons. Additionally you have 13 times the same floating number multiplication (<code>.02 * 100</code>). And a gap between the boundaries: If the percentage would result in 14.5, no rule would be triggered.</p>\n\n<p>Let's use my rules</p>\n\n<ol>\n<li>is .02 > .99 -> No</li>\n<li>is .02 > .80 -> No</li>\n<li>is .02 > .64 -> No</li>\n<li>is .02 > .40 -> No</li>\n<li>is .02 > .34 -> No</li>\n<li>is .02 > .14 -> No</li>\n</ol>\n\n<p>=> return 10</p>\n\n<p>As you see, I have maximum 6 comparisons and no floating point multiplication.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T23:08:39.430", "Id": "14961", "ParentId": "14911", "Score": "7" } }, { "body": "<p>I know you have already accepted an answer to this, but in general, I would recommend a completely different strategy. Instead of picking from many different images, drawn and named to match the battery level, pick a battery background (fuel, or fill level) image, that you can turn into a <em>stretchable</em> image (sometimes called a <em>9-patch</em> image). <code>UIImage</code> fully supports this concept.</p>\n\n<p>I actually built an app where I did exactly this. I built a class that completely encapsulates the battery display. In order to use it, you simply tell it the current battery level (e.g. 0 to 100) and it stretches the background image accordingly, to yield a perfectly continuous (not discrete) battery meter.</p>\n\n<p>Also, if you fundamentally want a <em>few</em> different images, for example, to support changing the color when the battery gets too low, then this implementation supports that, too. My meter shows red fuel when the level gets below a certain threshold. It also allows the battery meter to animate smoothly, when you change its value.</p>\n\n<p>Anyway, you can take a look at the project <a href=\"http://www.enscand.com/roller/enscand/entry/reusable_iphone_battery_meter_uiview\" rel=\"nofollow\">here on my blog</a>. Sample code is provided, too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-25T01:19:24.090", "Id": "15897", "ParentId": "14911", "Score": "3" } }, { "body": "<p>When I see a bunch of repetitive if statements of this kind, I often think \"this belongs in some kind of tabular format\". Even if that table is something simple like a struct array definition.</p>\n\n<p>Why not something like this? (Warning, my objc is a bit rusty; my C is much fresher.)</p>\n\n<pre><code>struct BatteryMapping\n{\n int minValue;\n NSString *imagePath;\n};\n\nstatic const struct BatteryMapping Mappings[] =\n{\n {100, @\"battery100fullycharged.png\"},\n {81, @\"battery90.png\"},\n {65, @\"battery75.png\"},\n {41, @\"battery50.png\"},\n {35, @\"battery30.png\"},\n {15, @\"battery20.png\"},\n {0, @\"battery10.png\"},\n {0, nil} // terminating record. shouldn't hit this but just in case...\n};\n\nconst struct BatteryMapping *p = Mappings;\nNSString *imagePath = nil;\n\nint percent = device.batteryLevel * 100;\n\nwhile (!imagePath &amp;&amp; p-&gt;imagePath)\n{\n if (percent &gt;= p-&gt;minValue)\n imagePath = p-&gt;imagePath;\n else\n ++p;\n}\n\nif (imagePath)\n batteryImage.image = [UIImage imageNamed:imagePath];\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-25T03:15:13.890", "Id": "15898", "ParentId": "14911", "Score": "1" } } ]
{ "AcceptedAnswerId": "15897", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T19:35:17.450", "Id": "14911", "Score": "3", "Tags": [ "objective-c" ], "Title": "Showing an image based on the battery level" }
14911
<p>What would be the best (performance, memory wise) to achieve a clean way to create a class or some way to properly structure the code, that shares 2 variables (req, res) which have a decent object size.</p> <p>And yes, for those who use <code>Node.js</code> it are the <code>req</code> and <code>res</code> variables, but it is irrelevant.</p> <p>This is what I tried so far:</p> <pre><code>function Client(req, res){ var self = this; self.req = req; self.res = res; route.call(self); handleRoute.call(self); handleRequestData.call(self); } function route(){ var self = this; self.req.route = // ... } function handleAuth(){ var self = this; self.req.auth = // ... } function handleRequestData(){ var self = this; self.req.data = // ... } </code></pre> <p>I am wondering if it could be improved, since I mentioned req and res are pretty decent objects with methods, properties. Since .call(self) you pass through the instance, would it be most effective way?</p> <p>Also I don't like using "var self = this;" all the time, it is useless. </p> <p>And btw, I don't want to use Coffeescript.</p> <p>Solution 1. (fails because of the massive passing through req and res)</p> <p>Lets assume we got to files <strong><em>1. client.js</em></strong></p> <pre><code>var Client = { route: function(req, res){}, auth: function(req, res, callback){ callback(req, res); }, getData: function(req, res, callback){ callback(req, res); } // async } </code></pre> <p>file <strong><em>2. main.js</em></strong></p> <pre><code>var client = require('./client.js'); client.route(req, res); // fine because this is syncronous. // This is where the problem is, massive passing through req and res parameters. client.auth(req, res, function(req, res){ client.getData(req, res, function(req, res){ // Do something... }); }); </code></pre>
[]
[ { "body": "<p>Note: I assumed the Client function would be used a constructor, e.g.</p>\n\n<pre><code>var clientInstance = new Client();\nclientInstance.req;//access req\n</code></pre>\n\n<p>I think I may have been wrong about that.</p>\n\n<p>Objects are passed via reference, so they shouldn't be taking up more memory than the bytes that go into linking to another namespace/scope. By passing in as local parameters, you've probably eliminated overhead for the call object compared to if they were referenced from outside of your function constructor but you could probably build dozens of similar objects without seeing a major impact on memory. (although I don't know what the last three lines do - they might create new object instances with properties that are passed by value which would hit memory harder).</p>\n\n<p>The advantage of function constructors is that you can build factories where vars that would be passed as values are instead accessed via closure. In JIT compilers at least, I wouldn't expect those to take up more space in memory either. Example:</p>\n\n<pre><code>function objFactory(){\n\n var someHandyProperty = 42;\n\n function ObjConstructor(){\n var internalHandyProperty = someHandyProperty;\n this.publicMethodAlert = function(){ alert('The answer to the ultimate question: ' + internalHandyProperty);\n\n }\n\n return new ObjConstructor()\n\n}\n\nvar someInstance = objFactory();\nsomeInstance.publicMethodAlert();//alerts 42 referenced via closure\n</code></pre>\n\n<p>For a bigger example, have a look at jQuery. Nearly all of a JQ objects methods and values are accessed via a hand-me-down prototype or closures. JQ objects themselves carry a massive array of methods and properties around but don't take up much memory at all.</p>\n\n<p>In the example above, defining the 'publicMethodAlert' in the prototype of the constructor would be even more efficient since I'm not redefining a function for every instance.</p>\n\n<p>Example:</p>\n\n<pre><code>function objFactory(){\n\n var someHandyProperty = 42;\n\n\n function ObjConstructor(){\n }\n\n ObjConstructor.prototype.publicMethodAlert = function(){ alert('The answer to the ultimate question: ' + someHandyProperty);\n\n return new ObjConstructor()\n\n}\n\nvar someInstance = objFactory();\nsomeInstance.publicMethodAlert();//still alerts 42 referenced via closure\n</code></pre>\n\n<p>Now the instances just builds from an empty function with a prototype fallback (always the same function) so we're not redefining a function for every instance (note: in non-JIT interpreters we might actually redefine the function for every firing of the factory, but I would expect JITs, which I'm certain Node uses, to cache everything defined locally in this case)</p>\n\n<p>One of the things I personally dislike about CoffeeScript is reduced flexibility in the manner in which I go about building my objects and defining my functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T21:12:36.317", "Id": "24196", "Score": "0", "body": "thanks for the answer, tried some more, changed my question" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T20:39:22.270", "Id": "14915", "ParentId": "14912", "Score": "1" } }, { "body": "<p>Why not simply</p>\n\n<pre><code>function Client(req, res){\n this.req = req;\n this.res = res;\n\n this.route();\n this.handleRoute();\n this.handleRequestData();\n}\n\nClient.prototype = = {\n route: function() {\n this.req.route = // ...\n },\n\n handleAuth: function() {\n this.req.auth = // ...\n },\n\n handleRequestData: function() {\n this.req.data = // ...\n }\n};\n</code></pre>\n\n<p>You would call it like this:</p>\n\n<pre><code>var client = new Client(req, res);\n</code></pre>\n\n<p>Javascript does not have classes. But constructor functions used this way are a reasonable approximation for many uses.</p>\n\n<hr>\n\n<p><strong>EDIT</strong> based on note that functions should be private:</p>\n\n<pre><code>var Client = (function() {\n var route = function() {\n this.req.route = // ...\n },\n\n handleAuth = function() {\n this.req.auth = // ...\n },\n\n handleRequestData = function() {\n this.req.data = // ...\n };\n\n return function(req, res) {\n this.req = req;\n this.res = res;\n\n route.call(this);\n handleRoute.call(this);\n handleRequestData.call(this);\n } \n}());\n</code></pre>\n\n<p>The functions are available now only to the constructor function. If other functions need access to them, they would have to be defined inside the same closure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T21:28:48.093", "Id": "24199", "Score": "0", "body": "Thing is, route, handleAuth and handleRequestData should be private, not public." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T11:45:45.390", "Id": "24242", "Score": "0", "body": "Added another version that handles this." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T20:41:05.603", "Id": "14917", "ParentId": "14912", "Score": "1" } }, { "body": "<p>I don’t know <em>why</em> you are constantly saving the context (<code>this</code>) in a local variable (<code>self</code>). You might as well use <code>this</code> all the way, unless you need to bring it into a local object with different scope.</p>\n\n<p>Also, you can chain the other methods in the Prototype to gain access to the context inside them:</p>\n\n<pre><code>function Client(req, res){\n\n this.req = req;\n this.res = res;\n\n this.route();\n this.handleRoute();\n this.handleRequestData();\n}\n\nClient.prototype.route = function(){\n this.req.route = // ...\n}\n\nClient.prototype.handleAuth = function(){\n this.req.auth = // ...\n}\n\nClient.prototype.handleRequestData = function(){\n this.req.data = // ...\n}\n</code></pre>\n\n<p>If you don’t want \"public\" methods, just do:</p>\n\n<pre><code>function Client(req, res){\n\n this.req = req;\n this.res = res;\n\n route.call(this);\n handleRoute.call(this);\n handleRequestData.call(this);\n}\n\nfunction route(){\n this.req.route = // ...\n}\n\nfunction handleAuth(){\n this.req.auth = // ...\n}\n\nfunction handleRequestData(){\n this.req.data = // ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T20:36:15.117", "Id": "24217", "Score": "0", "body": "private methods? the constructor does cascading, I don't want to be able to call client.handleAuth();" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T20:37:32.183", "Id": "24218", "Score": "0", "body": "OK, you should probably mention that. BTW that doesn’t explain why you are putting `this` into `self`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T20:39:48.877", "Id": "24219", "Score": "0", "body": "Some functions are asyncronous, and redefine the \"this\" variable, but I still want to be able to refer to the actual instance of the class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T20:50:12.707", "Id": "24220", "Score": "0", "body": "Well that would be up to each function to deal with it’s context I guess. You could always pass it as an argument to save yourself some extra lines of code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T20:34:20.513", "Id": "14924", "ParentId": "14912", "Score": "0" } }, { "body": "<p>Are you intending to reuse the <code>route</code>, <code>handleAuth</code>, and <code>handleRequestData</code> functions? They could be \"private\" to the Client constructor function:</p>\n\n<pre><code>function Client(req, res) {\n function route() {\n //...\n }\n\n function handleAuth() {\n //...\n }\n\n function handleRequestData() {\n //...\n }\n\n route();\n handleRoute();\n handleRequestData();\n}\n</code></pre>\n\n<p>See that I didn't set <code>req</code> and <code>res</code> as <code>this</code> members. I don't know if this is mandatory in your case. Also, this is just the beginning of what could be done; as stated in the comments to this answer, every time a new <code>Client</code> is created, new instances of the private functions are created as well, wasting resources.</p>\n\n<p>A more sophisticated approach could define <code>Client</code> using a self-invoking function expression:</p>\n\n<pre><code>var Client = (function() {\n function route(req, res) {\n //...\n }\n\n function handleAuth(req, res) {\n //...\n }\n\n function handleRequestData(req, res) {\n //...\n }\n\n // This is the constructor function:\n return function(req, res) {\n route(req, res);\n handleRoute(req, res);\n handleRequestData(req, res);\n }\n})();\n</code></pre>\n\n<p>Here, <code>Client</code> is defined as the product of the function expression enclosed in the outermost parenthesis. The function expression returns the constructor function, which has access to the closure functions <code>route</code>, <code>handleRoute</code>, and <code>handleRequestData</code>. Note that each of these functions is defined with <code>req</code> and <code>res</code> parameters. This way, they behave like static private functions, and you can code and use them regardless of what's referenced by <code>this</code>.</p>\n\n<p><strong>About self = this:</strong> it's known that JavaScript may be very confusing about the <code>this</code> keyword. <a href=\"https://stackoverflow.com/questions/3127429/javascript-this-keyword\">Some information here</a>. So, sometimes it's convenient to assign <code>this</code> to a closure variable named like <code>self</code> or <code>me</code>. It should not be done blindly though... as anything after all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T20:42:42.560", "Id": "24221", "Score": "2", "body": "I would not suggest this if you are planning on creating multiple Client objects. There will be multiple copies of the route, handleAuth, etc. functions, one for each instance. David's suggestion will deal better with this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T20:44:09.240", "Id": "24222", "Score": "1", "body": "You are right, @ScottSauyet. The code I posted may not be suitable for production. I'll expand my answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T20:37:22.853", "Id": "14925", "ParentId": "14912", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T20:27:48.883", "Id": "14912", "Score": "2", "Tags": [ "javascript", "object-oriented", "url-routing" ], "Title": "Structuring code to do URL routing for Node.js" }
14912