body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am studying the composite pattern and have created a very simple project that uses composite to introduce family members. I have decided to go with the 'fully transparent' implementation by defining all of my common functions in the interface class, I feel this is the neatest implementation and am considering throwing an exception in Leaf classes if client tries to call add / remove... </p> <p>Below are the sample classes I have created. I would like to get some thoughts on how I implemented.</p> <ol> <li>Am I implementing composite correctly?</li> <li>Is this a good piece of sample code?</li> <li>Thoughts on throwing an exception in leaf class for un-needed function implementations like add / remove Person?</li> </ol> <p><strong>Client class</strong></p> <pre><code>public class Client { public static void main(String args[]) { Person gretchen = new Parent("gretchen", 101); Person steve = new Parent("Steve", 57); Person mary = new Parent("Mary", 56); Person timmy = new Child("Timmy", 10); Person molly = new Child("Molly", 5); gretchen.add(steve); gretchen.add(mary); steve.add(timmy); steve.add(molly); mary.add(timmy); mary.add(molly); //introduces entire family gretchen.introduce(); } } </code></pre> <p><strong>Component Class</strong></p> <pre><code>public interface Person { public String getName(); public int getAge(); public int getNumOfChildren(); public void add(Person person); public void remove(Person person); public void introduce(); } </code></pre> <p><strong>Composite class</strong></p> <pre><code>public class Parent implements Person { private String name; private int age; private List&lt;Person&gt; children = new ArrayList&lt;Person&gt;(); public Parent(String name, int age) { this.name = name; this.age = age; } public void introduce() { System.out.println("Hi, I am ".concat(getName())); System.out.println("I am ".concat(Integer.toString(getAge()).concat( " years old"))); System.out.println("I have ".concat(Integer.toString(children.size()).concat(" kids."))); System.out.println("Children... introduce your selves!"); for (Person person : children) { person.introduce(); } } @Override public String getName() { return this.name; } @Override public int getAge() { return this.age; } @Override public int getNumOfChildren() { return this.children.size(); } @Override public void add(Person person) { children.add(person); } @Override public void remove(Person person) { children.remove(person); } } </code></pre> <p><strong>Leaf class</strong></p> <pre><code>public class Child implements Person { private String name; private int age; public Child(String name, int age) { this.name = name; this.age = age; } @Override public void introduce() { System.out.println("Hi, I am ".concat(getName())); System.out.println("I am ".concat(Integer.toString(getAge()).concat( " years old"))); } @Override public String getName() { return this.name; } @Override public int getAge() { return this.age; } @Override public int getNumOfChildren() { return 0; } @Override public void add(Person person) { // no implementation here, throw exception maybe? } @Override public void remove(Person person) { // no implementation here, throw exception maybe? } } </code></pre>
[]
[ { "body": "<blockquote>\n <ol>\n <li>Am I implementing composite correctly.</li>\n </ol>\n</blockquote>\n\n<p>Although you are doing it correctly, a part of me wonders if it was the correct solution for you problem. The reason I ask is because a interface usually means that each method that you define is going to need to be implemented differently for each sub class that implements it. In your case it doesn't matter what type of person you have they will always introduce themselves the same way, and they will always say their name the same way, and they will always tell their age the same way. That being said an abstract class would have been a better choice because the basics will be the same for both parent and child (and even if you decide to add another branch of a person) for things such as their name, and age. The introduction would possibly be the only exception if you added a culture to this mixture. Since different cultures introduce themselves differently in almost all scenarios that would be a good candidate for a interface.</p>\n\n<blockquote>\n <ol>\n <li>Is this a good piece of sample code?</li>\n </ol>\n</blockquote>\n\n<p>The code appears to be in good order. It is easy to read and easy to understand. My only issue (and it is debatable) is having the age part of the constructor. In this context it makes sense, but when i first introduce my self to someone I don't say, \"Hi my name is Robert Snyder, I'm 30 years old\". Instead I just introduce my self as \"Robert\" but judging by the context of your code it might be fair to have the age (such as in the case of the entrance to a liquor store, they want your id which has your name and age)</p>\n\n<blockquote>\n <ol>\n <li>Thoughts on throwing an exception in leaf class for un-needed function implementations like add / remove Person?</li>\n </ol>\n</blockquote>\n\n<p>No. Never. Only in the higher levels do you want that to happen. This forces the user to use child classes. If your child classes are \"dangerous\" then people will either make their own, or not use yours. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T02:47:58.877", "Id": "53755", "Score": "0", "body": "Thanks very much for the thorough review. There is actually not a real problem I am trying to solve, instead I am simply studying design patterns and making sure I understand them correctly. I plan to put this code on a website I am working on for person reference and to share with anyone who might also want to learn it. I like your idea about adding different cultures, I feel that will better help to show what the actual pattern is capable of. I will most likely add some additional composite / leaf classes to show how extendable it can be. once again, thanks for your review!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T02:30:10.087", "Id": "33488", "ParentId": "33487", "Score": "1" } }, { "body": "<blockquote>\n <p>Thoughts on throwing an exception in leaf class for un-needed function implementations like add / remove Person?</p>\n</blockquote>\n\n<p>In Java7, the Collections library will throw an UnsupportedOperationException if you call a method that changes the state of a collection returned by <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#unmodifiableCollection%28java.util.Collection%29\" rel=\"nofollow\">Collections.unmodifiableCollection</a>. ImmutableList, from the Google Collections Library, will throw UnsupportedOperationException if you attempt to modify the state of the list.</p>\n\n<p>So if you were already starting with an interface that allowed modification (Person), then this would be a reasonable way to deal with the leaf implementation (Child).</p>\n\n<p>In designing a new interface, I'd try to stay away from that. There are a couple possibilities. One is that your leaf nodes don't <em>really</em> have different behavior than the interior nodes - Child is just a Parent in the state where Parent.children.isEmpty(). In other words, the instances are all just nodes in a directed graph, some of which are end points. In that case, I'd just use a single class, and give the children empty arrays.</p>\n\n<p>Note: with the Collections libraries, you get a free punt here, if you want it:</p>\n\n<pre><code>private List&lt;Person&gt; children = Collections.EMPTY_LIST;\n</code></pre>\n\n<p>And then let the empty list throw what ever it is going to throw when somebody tries to insert a new Person into it.</p>\n\n<p>Another possibility is that Parent and Child really are two different ideas, but after the composite is constructed, those details are hidden from the consumer. In that case, you want a single interface that does NOT include the add and remove methods. Instead, you build a List first, and then pass that list to the Parent constructor. Once the construction is done, the composite nature is no longer important, so consumers only see the Person interface of the outermost Parent.</p>\n\n<p>Another possibility is that the relationships between Person instances aren't really part of the objects themselves, but belong to some other thing. It is fairly common in graph implementations to discover that there are Nodes, and Edges that connect Nodes. The logic that does the traversal knows about both, but the Nodes don't know about their edges at all. Notice that in your implementation, you need to bake ordering into the objects themselves (breadth first? depth first? what order do you visit the children?). In that case, split the edges out from Person, and work with an abstraction (Family? SocialNetwork?) that manages the relationships when new Persons are added.</p>\n\n<p>My most common cases are those where the nodes and edges are known during construction, and fixed from that point forward. So there, I use my concrete leaf and container classes to build the correct object graph from the outset, but I do <em>not</em> publish the availability of methods to change the contents of the graph. In other words, it only looks like a composite during the construction phase.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T05:39:02.333", "Id": "33493", "ParentId": "33487", "Score": "1" } } ]
{ "AcceptedAnswerId": "33488", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T01:55:35.273", "Id": "33487", "Score": "4", "Tags": [ "java" ], "Title": "Is this a good example of the composite pattern?" }
33487
<pre><code>public void something() { Session session = HibernateUtil.newSession(); AModelDAO amd = new AModelDAO(session); BModelDAO bmd = new BModelDAO(session); Transaction tx = session.beginTransaction(); amd.savesomething(object); bmd.savesomething(object2); tx.commit(); session.close(); } </code></pre> <p>I would like to know if my coding here is good enough or if there is a better method to produce the same result.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T07:36:56.560", "Id": "53665", "Score": "0", "body": "I do not know hibernate. This is a general guideline that you should handle exception here and also think of the case where the transaction fails and how you revert back the state." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T11:53:29.210", "Id": "53680", "Score": "0", "body": "of course I handled exception... In my example code, I skipped exception." } ]
[ { "body": "<p>Instead of working with Hibernate sessions, I encourage you to use the JPA API. I think this is the most common way to work with Hibernate now. (<a href=\"http://www.theserverside.com/news/2240186700/The-JPA-20-EntityManager-vs-the-Hibernate-Session-Which-one-to-use\" rel=\"nofollow\">http://www.theserverside.com/news/2240186700/The-JPA-20-EntityManager-vs-the-Hibernate-Session-Which-one-to-use</a>)</p>\n\n<p>For the transaction aspects and the initialization of your DAOs, I also think that a solution like Spring (<a href=\"http://projects.spring.io/spring-framework/\" rel=\"nofollow\">http://projects.spring.io/spring-framework/</a>) would help to simplify the code of your application.</p>\n\n<p>Your code would look more like the following (with annotations stuff):</p>\n\n<pre><code>public class MyService {\n @Resource\n private AModelDAO aDao;\n\n @Transactional\n public void something(object) {\n // no need to manage transactions or sessions here\n aDao.save(object);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T14:28:23.027", "Id": "33516", "ParentId": "33495", "Score": "1" } } ]
{ "AcceptedAnswerId": "33516", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T07:06:54.167", "Id": "33495", "Score": "1", "Tags": [ "java", "session", "hibernate" ], "Title": "Coherent usage of Hibernate's session and DAO" }
33495
<p>I am pretty new to iOS development - I'm writing an app the uses web services, pretty extensively. With that in mind, I decided to use AFNetworking 2.0 and subclass <code>AFHTTPSessionManager</code>. </p> <p>I created a method to build a URL for me - based on <code>NSDictionary</code> parameters and then I use the URL with the parameters to execute a GET / POST / PUT request. My worry is the last part - have I made this class less readable and less manageable by doing that? </p> <p><strong>BBWebService.h</strong> </p> <pre><code>#import &lt;Foundation/Foundation.h&gt; #import "AFNetworking.h" @interface BBWebService : AFHTTPSessionManager @property (strong, nonatomic) NSData *responseData; //Designated Initilizer - (id) initWithURL: (NSString*) url RequestType: (NSString*) requestType PostDataValuesAndKeys: (NSDictionary*) postData RequestProperties: (NSDictionary*) requestProperties UrlParameters: (NSDictionary*) urlParameters; @end </code></pre> <p><strong>BBWebService.m</strong> </p> <pre><code>import "BBWebService.h" @interface BBWebService () @end @implementation BBWebService - (id) initWithURL: (NSString*) url RequestType: (NSString*) requestType PostDataValuesAndKeys: (NSDictionary*) postData RequestProperties: (NSDictionary*) requestProperties UrlParameters: (NSDictionary*) urlParameters { self = [super init]; if (self) { NSString* urlWithParameters = [NSString stringWithString: url]; // check to see if url parameters have been specified if (urlParameters != nil) { NSString *paramString = nil; // Work-around for URLs that may use a parameter to indicate an "action" instead of a path in the URL itself. BOOL hasQuestionMark = NO; NSRange textRange; textRange = [urlWithParameters rangeOfString:@"?"]; if(textRange.location != NSNotFound) { hasQuestionMark = YES; } for (int i = 0; i &lt; [[urlParameters allKeys] count]; i++) { if (i == 0) { if (hasQuestionMark == YES) { paramString = [NSString stringWithFormat: @"&amp;%@=%@", [[urlParameters allKeys] objectAtIndex: i], [urlParameters objectForKey:[[urlParameters allKeys] objectAtIndex: i]]]; } else { paramString = [NSString stringWithFormat: @"?%@=%@", [[urlParameters allKeys] objectAtIndex: i], [urlParameters objectForKey:[[urlParameters allKeys] objectAtIndex: i]]]; } } else { paramString = [NSString stringWithFormat: @"%@&amp;%@=%@", paramString, [[urlParameters allKeys] objectAtIndex: i], [urlParameters objectForKey:[[urlParameters allKeys] objectAtIndex: i]]]; } } urlWithParameters = [url stringByAppendingString:paramString]; urlWithParameters = [urlWithParameters stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"Url with encoded parameters: %@", urlWithParameters); } __unused AFHTTPSessionManager* sessiomNamager = [BBWebService buildRequest:urlWithParameters RequestType:requestType PostDataValuesAndKeys:postData RequestProperties:requestProperties]; } return self; } //Class method + (AFHTTPSessionManager *) buildRequest: (NSString*) url RequestType: (NSString*) requestType PostDataValuesAndKeys: (NSDictionary*) postData RequestProperties: (NSDictionary*) requestProperties { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; if ([requestType isEqualToString:@"GET"]) { [manager GET:url parameters:postData success:^(NSURLSessionDataTask *dataTask, id responseObject){ //Success NSLog (@"Success"); } failure:^(NSURLSessionDataTask *dataTask, NSError *error){ //Failure NSLog (@"Failure"); }]; }else if ([requestType isEqualToString:@"POST"]){ [manager POST:url parameters:postData success:^(NSURLSessionDataTask *dataTask, id responseObject){ //Success NSLog (@"Success!!"); } failure:^(NSURLSessionDataTask *dataTask, NSError *error){ //Failure NSLog (@"Failure"); }]; }else if ([requestType isEqualToString:@"PUT"]){ [manager PUT:url parameters:postData success:^(NSURLSessionDataTask *dataTask, id responseObject){ //Success } failure:^(NSURLSessionDataTask *dataDask, id responseObject){ //Failure }]; } return manager; } @end </code></pre> <p>Questions: </p> <ol> <li><p>In my designated <code>initWithURL</code> method - is this a good way to build a URL based on <code>NSDictionary</code> parameters? </p></li> <li><p>With the class method: <code>builRequest</code> - I looked in the header file of <code>AFHTTPSessionManager.h</code> - I couldn't see a way to properly detect the <code>requestType</code> (GET/POST, etc) - and this is why I am checking with an <code>NSString</code> value. </p></li> </ol> <p>I worry that should someone else use this class and they type / spell the GET / POST part wrong - the service won't run and it may be a hard to track bug as the compiler won't show a warning for <code>NSString</code> values. </p> <p>This is how I would use this method in another class: </p> <pre><code>BBWebService *newWebService = [[BBWebService alloc]initWithURL:URL RequestType:@"GET" PostDataValuesAndKeys:nil RequestProperties:nil UrlParameters:nil]; </code></pre> <p>I am aware I have not added the class method to the header file - reason being is I am still finishing the rest of the file - and I have not decided yet if I want it exposed.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-08T06:31:54.583", "Id": "168912", "Score": "0", "body": "@Tender I am also looking for same thing but could not able to handle if Service is Get, post..... Please if u could update ur complete answer then it would be great for us to handle" } ]
[ { "body": "<p>My first thought is does AFNetworking not handle this already but if not I would suggest doing this in a more AFNetworking style: create an object of type AFHTTPResponseSerializer * and set an instance of it as the session manager's requestSerializer property</p>\n\n<p>This way you can use the default session managers request methods (i.e. using the get methods and not having to worry about spelling GET, POST etc correctly), and you can be responsible for how the request is formatted by implementing</p>\n\n<pre><code>- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request\n withParameters:(NSDictionary *)parameters\n error:(NSError *__autoreleasing *)error;\n</code></pre>\n\n<p>Adding comment into answer: basically i think the request creation should happen in the requestSerializer object, not in the session manager itself. its ok to do this yourself (this is why AFNetworking provides the property to modify, and protocol to implement), but the session manager (subclass or not) isn't the place for it</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T11:40:12.527", "Id": "53679", "Score": "0", "body": "I have looked through the various documents on AFNetworking 2.0 - and cannot see anything related to this. Would I need a singleton of the BBWebservice then to use that correctly? Also - wouldn't I still need to implement the success / fail blocks - I really don't want to do that outside of BBWebService - I'll be calling GET / POST requests multiple times in the app and this is why I tried to make a class just for those methods. Sorry if this is really silly - still trying to figure it out. Appreciate the feedback." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T12:10:04.997", "Id": "53682", "Score": "0", "body": "you could use a subclass of session manager which always creates an appropriate serializer. to me the BBWebService class seems to much like fighting the framework you are using. Also the build request method is kind of hard to understand since it doesn't actually build the request: it runs it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T12:11:54.917", "Id": "53683", "Score": "0", "body": "also for completion / error blocks you would just use the standard AFNetworking blocks. I can't see where you are passing blocks to the build request method anyway?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T12:41:14.370", "Id": "53686", "Score": "0", "body": "BBWebService is a subclass of AFHTTPSessionManager. In the completion blocks - I plan on running a separate method [self requestDone] that takes the responseObject as an argument. Maybe I am subclassing AFHTTPSessionManager incorrectly. What I need to really do in this class is: take the base url and it's parameters and build the url - which I do with the initWithUrl method. Then I need to check if it was GET/POST/PUT request and then run it. Once GET/POST has ran - I take the responseObject and store it in NSData and use that to parse the XML/JSON data and return it using a protocol." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T12:45:31.843", "Id": "53687", "Score": "0", "body": "So it would go like this: Call the web service with a URL and parameters - BBWebService class builds URL with parameters. Then I check which type of request (GET/POST/PUT, etc) - then in the completion block call requestDone/Failed methods which take the responseObject as an argument and I store it into NSData and hand it off to the parser. That was the plan.. appreciate the feedback @wattson12" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T12:51:38.327", "Id": "53688", "Score": "0", "body": "OK but since that is what AFNetworking already does, it seems like you are breaking the functionality. e.g. the init method of the session manager shouldn't build a full URL, because then it is only useful for 1 request" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T12:56:27.367", "Id": "53689", "Score": "0", "body": "So what you're saying is I should override methods in the superclass to do the stuff I am trying to do in the subclass? (Superclass being AFHTTPSessionManager)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T13:08:19.160", "Id": "53690", "Score": "0", "body": "well i think the request creation should happen in the requestSerializer object, not in the session manager itself. its ok to do this yourself, but the session manager (subclass or not) isn't the place for it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T13:28:09.667", "Id": "53692", "Score": "0", "body": "Okay - so it appears I am definitely doing this wrong. Will go back to AFNetworking documentation and do more reading. Can you put your last comment as an answer so i can accept it and vote. Thank you @wattson12" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T10:11:03.230", "Id": "33501", "ParentId": "33497", "Score": "1" } } ]
{ "AcceptedAnswerId": "33501", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T07:42:35.537", "Id": "33497", "Score": "4", "Tags": [ "beginner", "objective-c", "ios", "http", "session" ], "Title": "Subclassing AFNetworking to handle POST / GET requests" }
33497
<p>I've got a string that has values that are delimited by comma's, like so:</p> <pre><code>$var = '1,23,45,123,145,200'; </code></pre> <p>I'd like to get just the first value, so what I do is create an array from it and get the first element:</p> <pre><code>$first = current(explode(',', $var)); </code></pre> <p>Fine enough. But this string can sometimes contain perhaps hundreds of values. Exploding it into an array and only using the first one seems kind of a waste. Is there a smarter alternative which is also more performant/less wasteful? I'm thinking some sort of regex or trimming, but I'm guessing that could be actually slower...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T11:11:08.283", "Id": "53678", "Score": "0", "body": "+1 for _not_ ignoring your gut feeling, and being reluctant to tackle this using regex. It's proof of sentient activity, some people lack" } ]
[ { "body": "<p>I am not familiar with php syntax but I hope you could do this </p>\n\n<pre><code> $var = \"1,23,45,123,145,200\"; \n $first_word = substr($var, 0, strpos($var, ','));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T10:33:50.420", "Id": "33502", "ParentId": "33500", "Score": "2" } }, { "body": "<p><em>UPDATE:</em><br/>\nA more complete benchmark script:</p>\n\n<pre><code>$start = $first = $str = null;//create vars, don't benchmark this\n//time preg_match\n$start = microtime(true);\n$first = $str = implode(',', range(213,9999));\nif (preg_match('/^[^,]+/', $str, $match))\n{\n $first = $match[0];\n}\necho $first, PHP_EOL, microtime(true) - $start, ' time taken&lt;br/&gt;', PHP_EOL;\n//time str* functions\n$start = microtime(true);\n$first = $str = implode(',', range(213,9999));\n$first = substr($str, 0, strpos($str, ','));\necho $first, PHP_EOL, microtime(true) - $start, ' time taken&lt;br/&gt;', PHP_EOL;\n//now explode + current\n$first = null;\n$start = microtime(true);\n$str = implode(',', range(213, 9999));\n$first = current(explode(',', $str));\necho $first, PHP_EOL, microtime(true) - $start, ' time taken';\n</code></pre>\n\n<p>The result varried a little, but after 100 runs, the averages amounted to:</p>\n\n<pre><code>#1 substr+strpos: ~.0022ms as 1//base for speed\n#2 preg_match: ~.0041 as ~2//about twice as slow as #1\n#3 explode: ~.00789 as ~4//about 4 times &lt;=&gt; #1, twice as slow &lt;=&gt; regex\n</code></pre>\n\n<hr>\n\n<p>You're absolutely right, exploding a string, constructing an array to get just the first value is a waste of resources, and it is not the fastest way to get what you want.<br/>\nSome might run to regex for help, and chances are that, in your case that will be faster. But nothing I can think of will beat the speed of PHP's string functions (which are very close to the C string functions). I'd do this:</p>\n\n<pre><code>$first = substr($var, 0, strpos($var, ','));\n</code></pre>\n\n<p>If the comma isn't present (say <code>$var = '123'</code>), then your current approach will assign <code>123</code> to <code>$first</code>. To preserve this behaviour, I'd go for:</p>\n\n<pre><code>$first = strpos($var, ',') === false ? $var : substr($var, 0, strpos($var, ','));\n</code></pre>\n\n<p>This is to say: if <code>strpos</code> returns false, then there is no comma at all, so assign the entire string to <code>$first</code>, else get everything in front of the first comma.</p>\n\n<p>For completeness sake (and after some initial bench-marking), using <code>preg_match</code> did indeed prove to be faster than using <code>explode</code> with large strings (<code>$var = implode(',', range(1, 9999));</code>), when using this code:</p>\n\n<pre><code>$first = $var = implode(',', range(1,9999));\nif (preg_match('/^[^,]*/',$var, $match))\n{\n $first = $match[0];\n}\n</code></pre>\n\n<p>But honestly, I wouldn't use regex in this case.</p>\n\n<p>In the interest of fairness, and to to clarify how I found the regex to be faster:</p>\n\n<pre><code>$start = microtime(true);\n$first = $str = implode(',', range(213,9999));\nif (preg_match('/^[^,]+/', $str, $match))\n{\n $first = $match[0];\n}\necho $first, PHP_EOL, $str, PHP_EOL, microtime(true) - $start, ' time taken';\n$first = null;\n$start = microtime(true);\n$str = implode(',', range(213, 9999));\n$first = current(explode(',', $str));\necho $first, PHP_EOL, microtime(true) - $start, ' time taken';\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T11:01:45.490", "Id": "53676", "Score": "0", "body": "Thanks, I did some benchmarking myself and found that both string and regex solutions are a lot faster than exploding. They are about the same when using this exact code, when losing the ternary notation for the string solution, I found it was actually faster than the regex by about 20% (because ternary uses copy-on-write). So I think I'll use that. As you said: nothing beats the speed of PHP's string functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T11:09:24.697", "Id": "53677", "Score": "0", "body": "@kasimir: I've edited my answer some more, adding my benchmark code, and its results (over 100 runs). I found the string functions to be twice as fast as regex. Though I did run it on a VM, and didn't check how I had configured PHP (it's been ages, and still running 5.3). But if my answer answered your question, would you mind awfully accepting (and or upvoting) it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T13:15:36.417", "Id": "53691", "Score": "0", "body": "Don't worry... Ok, so string function is definitely the fastest, great! Also, the regex solution is the 'ugliest' in my opinion, kind of obscuring what you are doing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T13:29:20.940", "Id": "53693", "Score": "1", "body": "Along the same lines: did you know `$count = substr_count($var, ',') + 1;` is a lot faster than `$count = count(explode(',', $var));`? http://codepad.org/KGqtWbxO" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T13:59:14.053", "Id": "53696", "Score": "0", "body": "@Kasimir: It ought to be... I would've been surprized if it wasn't. Iterating through a `char[]` comparing `j += char[i] == 44 ? 1 : 0` each time just _has_ to be faster than iterating through that string, copying every chunk of data that is not a comma to a new array, only to count the chunks just cannot be as fast, because both operations start by doing the same thing, the difference is the copying, which isn't done in the first case. Good of you to check, though. I'd +1 you again for not taking assumptions for granted, but actually bother _checking_ those things. A commendable attitude" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T05:40:30.557", "Id": "411621", "Score": "0", "body": "Why is the construction of the input array included in the benchmark time?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T10:35:00.327", "Id": "33503", "ParentId": "33500", "Score": "8" } }, { "body": "<p>I am shocked that the first three approaches that came to mind didn't even get considered/mentioned/tested!</p>\n\n<p>In reverse order of my preference...</p>\n\n<p>Least robust because only works on integers and poorly handles an empty string, casting string as integer: (<a href=\"https://3v4l.org/dCW9P\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$tests = ['1,23,45,123,145,200', '345,999,0,1', '0', '0,2', '-1,-122', '', '1.5,2.9'];\n\nforeach ($tests as $test) {\n var_export((int)$test); \n echo \"\\n\";\n}\n// 1\n// 345\n// 0\n// 0\n// -1\n// 0\n// 1\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/function.strstr.php\" rel=\"nofollow noreferrer\">strstr()</a> with the <code>before_needle</code> parameter: (<a href=\"https://3v4l.org/q1sMY\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>// same tests\n$before_comma = strstr($test, ',', true);\nvar_export($before_comma === false ? $test : $before_comma);\n// '1'\n// '345'\n// '0'\n// '0'\n// '-1'\n// ''\n// '1.5'\n</code></pre>\n\n<p><code>explode()</code> with a limit parameter: (<a href=\"https://3v4l.org/tUGnL\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>// same tests\nvar_export(explode(',', $test, 2)[0]);\n// '1'\n// '345'\n// '0'\n// '0'\n// '-1'\n// ''\n// '1.5'\n</code></pre>\n\n<p>While I don't like the idea of creating an array to extract a string value of the first element, it is a single call solution. Setting an element limit means that function isn't asked to do heaps of unnecessary labor.</p>\n\n<p>I am a big fan of <code>strstr()</code> but it must involve a conditional to properly handle comma-less strings.</p>\n\n<p>If your comma-separated string is never empty and only contains integers, I would strongly recommend the <code>(int)</code> approach, surely that is fastest.</p>\n\n<p>As much as I love regex, I would not entertain the use of a <code>preg_</code> call -- not even for a second.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T04:36:52.713", "Id": "212822", "ParentId": "33500", "Score": "2" } } ]
{ "AcceptedAnswerId": "33503", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T10:01:23.603", "Id": "33500", "Score": "4", "Tags": [ "php", "performance", "strings", "array", "regex" ], "Title": "Performance: getting first value from comma delimited string" }
33500
<blockquote> <p><strong>Even Fibonacci numbers</strong></p> <p><strong>Problem 2</strong></p> <p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p> <p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p> <p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</p> </blockquote> <pre><code>object Problem_2 extends App { def fibLoop():Long = { var x = 1L var y = 2L var sum = 0L var swap = 0L while (x &lt; 4000000) { if (x % 2 ==0) sum += x swap = x x = y y = swap + x } sum } def fib:Int = { lazy val fs: Stream[Int] = 0 #:: 1 #:: fs.zip(fs.tail).map(p =&gt; p._1 + p._2) fs.view.takeWhile(_ &lt;= 4000000).filter(_ % 2 == 0).sum } val t1 = System.nanoTime() val res = fibLoop val t2 = (System.nanoTime() - t1 )/1000 println(s"The result is: $res time taken $t2 ms ") } </code></pre> <p>Is there a more functional way of calculating the Fibonacci sequence and taking the sum of the even values below 4 million?</p> <p>Is the imperative method 1000x faster?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T19:46:59.130", "Id": "53666", "Score": "0", "body": "Have you solved the problem on PE? Have you looked at the attached pdf (see http://i.stack.imgur.com/WLwim.png ) that goes into the math for a better implementation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T19:52:09.977", "Id": "53667", "Score": "3", "body": "Project Euler has its own forum. Once you solve the problem using ANY way that gives you a solution, you get access to the forum for that problem where plenty of other people post their solutions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T19:56:20.233", "Id": "53668", "Score": "0", "body": "@ MichaelT the fibLoop function implements the algorithm that is recommended by the site, i was looking for a functional solution which would be as fast as the imperative method, maybe a tail recursive solution" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T19:59:34.770", "Id": "53669", "Score": "0", "body": "@firephil there's a rather elegant solution on page 5 of the PE question #2 forum. Don't know how fast they compare though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T20:13:47.577", "Id": "53670", "Score": "0", "body": "@ MichaelT Read what i've written its the same function and its taken from the scaladoc http://www.scala-lang.org/files/archive/nightly/docs/library/index.html#scala.collection.immutable.Stream" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T23:21:01.170", "Id": "53671", "Score": "1", "body": "From a programming point of view, the loops is the best you can do. Any better solutions rely on mathematical principles, not programming efficiency. If you're learning to program (or learning a new language), PE is a poor tool, since many of the problems come down to having mathematical knowledge or already knowing a particular algorithm for a solution." } ]
[ { "body": "<p>No iteration is required to calculate this result.</p>\n\n<p>Every third Fibonacci number is even. The <a href=\"http://en.wikipedia.org/wiki/Fibonacci_number\">Fibonacci numbers can be expressed in closed form</a> as: </p>\n\n<pre><code>Fib(n) = 1/sqrt(5) * (phi^n - psi'^n)\n</code></pre>\n\n<p>where</p>\n\n<pre><code>phi = (1 + sqrt(5) / 2)\n</code></pre>\n\n<p>and </p>\n\n<pre><code>psi = (1 - sqrt(5) / 2)\n</code></pre>\n\n<p>F(n) is even when n is a multiple of 3.</p>\n\n<p>Therefore the sum of even fibonacci numbers is equal to the sum of two geometric series, and can be calculated directly and exactly.</p>\n\n<p>P.S. A little experimentation shows that</p>\n\n<pre><code>sum(i=0..n) Fib(3*i) = (Fib(3*n + 2) - 1) / 2\n</code></pre>\n\n<p>e.g. </p>\n\n<pre><code>2 + 8 + 34 = 44 = (89 - 1) / 2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T20:27:47.850", "Id": "53672", "Score": "0", "body": "still you have to iterate on the collected values and add them though.And i think adding is more efficient than calculating the values directly if you had started for an initial value say fib(5000) would have more efficient to jump there but with this given problem you have to start from 1 so its faster to start calculating from fib(1)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T23:21:06.537", "Id": "53673", "Score": "1", "body": "@firephil: no, you don't have to iterate. The sum of even fibonacci numbers is equal to the sum of two geometric series. There is a closed form expression for the sum of a geometric series: `sum(0..n) x^n = (x^(n+1)-1)/(x-1)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T17:58:57.393", "Id": "53674", "Score": "0", "body": "thnx i see what you mean now" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-08T10:46:48.207", "Id": "107240", "Score": "0", "body": "@kevin cline it is more expensive to compute the closed form than a simple iteration or tail recursive algorithm. It may seem the closed form is faster but its not. I have performed measurements. Also you run into accuracy problems because you need to calculate the sqrt(5) which in most languages it is calculated with \"double\" precision" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T20:14:08.610", "Id": "33505", "ParentId": "33504", "Score": "6" } } ]
{ "AcceptedAnswerId": "33505", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T19:41:23.090", "Id": "33504", "Score": "1", "Tags": [ "optimization", "scala", "project-euler", "fibonacci-sequence" ], "Title": "Better way of calculating Project Euler #2 (Fibonacci sequence)" }
33504
<p>As a challenge I decided to do the following problem:</p> <blockquote> <p>How many different numbers with <em>n</em> digits are there whose digits add up to <em>k</em>?</p> </blockquote> <p>As this is an embarrassingly parallel problem I decided to use a bit of GPGPU programming (partly for learning purposes) using C++AMP and came up with the following solution:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;assert.h&gt; #include &lt;amp.h&gt; #include &lt;chrono&gt; #include &lt;ctime&gt; #include &lt;numeric&gt; inline unsigned int AddDigits( unsigned int n ) restrict(amp, cpu) { unsigned int sum = 0; while( n &gt; 0 ) { sum += n % 10; n /= 10; } return sum; } int main() { std::chrono::steady_clock clock; unsigned int iSize, iSumRequired; std::cout &lt;&lt; "Please enter the number of digits: "; std::cin &gt;&gt; iSize; std::cout &lt;&lt; std::endl &lt;&lt; "Please enter the sum required: "; std::cin &gt;&gt; iSumRequired; std::cout &lt;&lt; std::endl; unsigned long long iMaxNum = std::pow( 10, iSize ); assert( vecData.max_size() &gt; iMaxNum ); std::vector&lt;unsigned int&gt; vecData( iMaxNum ); std::vector&lt;int&gt; vecNumValid( iMaxNum ); auto tpBegin = clock.now(); std::iota( vecData.begin(), vecData.end(), 1 ); concurrency::array_view&lt;const unsigned int, 1&gt; arrayView( iMaxNum, vecData ); concurrency::array_view&lt;int, 1&gt; numValid( iMaxNum, vecNumValid ); concurrency::parallel_for_each( numValid.extent, [=]( concurrency::index&lt;1&gt; idx ) restrict( amp ) { numValid[idx] = (AddDigits( arrayView[idx] ) == iSumRequired ? 1 : 0); } ); numValid.synchronize(); int iNumValid = concurrency::parallel_reduce( vecNumValid.begin(), vecNumValid.end(), 0 ); std::cout &lt;&lt; "The number of valid numbers are: " &lt;&lt; iNumValid &lt;&lt; std::endl; auto tpTimeTaken = clock.now() - tpBegin; std::cout &lt;&lt; "Time Taken: " &lt;&lt; std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(tpTimeTaken).count() &lt;&lt; std::endl; return 0; } </code></pre> <p>This offers a significant improvement over parallel brute-forcing on the CPU (2x speedup versus 8 threads on an 8-core CPU), however out of curiosity I was wondering whether any further speedup could be gained, perhaps through somehow running the <code>parallel_reduce</code> on the GPU rather than on the CPU; removing the necessity to synchronize the <code>array_view</code>?</p> <p>Moreover, this only allows for up to 8-digits (because of the restriction of the maximum value being less than 2<sup>31</sup>-1) because the GPU only supports types of <code>float</code>, <code>double</code>, <code>int</code>, <code>unsigned int</code> and <code>bool</code>; is there a way to circumvent this and improve the maximum number of digits allowed?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T11:05:34.050", "Id": "54422", "Score": "0", "body": "Could you please clarify this: `How many different numbers with n digits are there that add up to k`\n\nDo you mean: `How many different numbers with n digits are there whose digits add up to k`? Sorry probably my fault for not understanding." } ]
[ { "body": "<p>I understand that you are asking from a parallel point of view, but I am unable to provide feedback on that, as I have never worked with this system before. But from my point of view, creating a parallel solution is has been done premature.</p>\n\n<p>Prior to creating a parallel solution to speed up your solution, you should improve the efficiency of the algorithm. At present you consider all numbers in the range of [1, 10<sup>N</sup>), whereas you only need to evaluate numbers where the number of digits in the number is equal to <code>N</code>. In which case you only need to evaluate numbers in the range of [10<sup>N-1</sup>, 10<sup>N</sup>).</p>\n\n<p>You could further improve this via considering permutations and combinations. This would allow you to calculate all the different combinations of the digits for the given range. Once you have these you can then check which of the combinations digits sum to the required total. </p>\n\n<p>If <code>X</code> combinations sum to a given total then you can quickly calculate how many numbers within the require range have <code>N</code> digits and sum to the goal. By computing <code>X * (N Perm N)</code> where N is the number of digits and where permutations are calculated without replacement. Representing just the N digits in the solution.</p>\n\n<p>At this point you would be using a parallel solution to calculate the combination hits, but you may find the bottle neck of data transfer to a GPU causes the parallel solution to perform slower than the non-GPU enabled solution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T11:25:57.987", "Id": "33918", "ParentId": "33506", "Score": "1" } }, { "body": "<p>I agree with @Christopher. The brute force might be embarrassingly parallel, but its complexity is dreadful.</p>\n\n<p>Calling <code>f(n,k)</code> the answer, there is a simple approach : the case <code>n&gt;1</code> boils down to <code>sum (g(n-1,k-i) for i in [1..min(k,9)])</code>, where <code>g</code> also allows <code>i=0</code>. \nThe case <code>n=1</code> is left as an exercise, and some other early stop shortcuts might be used.</p>\n\n<p>With this algorithm, you don't even need C++. Instead, a language with lightweight threads (scala) will prove profitable, since up to 9^n threads may be instantiated.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T09:22:30.670", "Id": "35282", "ParentId": "33506", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T12:12:08.510", "Id": "33506", "Score": "3", "Tags": [ "c++", "c++11", "combinatorics", "amp" ], "Title": "Max-digits of digit summing" }
33506
<pre><code>public static DateTime NextByDayOfWeek(this DateTime target, IEnumerable&lt;DayOfWeek&gt; validDaysOfWeek) { validDaysOfWeek = validDaysOfWeek .OrderBy(item =&gt; item); var nextDayOfWeek = validDaysOfWeek .Where(item =&gt; item &gt; target.DayOfWeek) .FirstOrDefault(); return nextDayOfWeek != 0 ? target.AddDays(nextDayOfWeek - target.DayOfWeek) : target.AddDays((validDaysOfWeek.First() + 7) - target.DayOfWeek); } </code></pre> <p>Usage:</p> <pre><code>DateTime.Today.NextByDayOfWeek(new[] { DayOfWeek.Monday, DayOfWeek.Friday }) </code></pre> <p>I don't think there are any possible edge cases here, at least some initial tests don't reveal any problem.</p> <p>I think it's short and readable, but readability is often hard to judge when you're the author.</p> <p>Any remarks?</p>
[]
[ { "body": "<p>I think a more readable way to write this would be to get the dates of the 7 days following the given date and return first one that matches the given days of week:</p>\n\n<pre><code>public static DateTime NextByDayOfWeek(\n this DateTime target, params DayOfWeek[] validDaysOfWeek)\n{\n return Enumerable.Range(1, 7)\n .Select(n =&gt; target.AddDays(n))\n .First(date =&gt; validDaysOfWeek.Contains(date.DayOfWeek));\n}\n</code></pre>\n\n<p>Notice that I also changes the <code>validDaysOfWeek</code> parameter to <code>params DayOfWeek[]</code>, because that allows you to call the method like this:</p>\n\n<pre><code>DateTime.Today.NextByDayOfWeek(DayOfWeek.Monday, DayOfWeek.Friday)\n</code></pre>\n\n<p>If you also want the method to accept any <code>IEnumerable&lt;DayOfWeek&gt;</code>, you could add an overload for that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T14:51:45.307", "Id": "53701", "Score": "0", "body": "This way hadn't crossed my mind, I like it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T14:44:07.683", "Id": "33517", "ParentId": "33510", "Score": "2" } }, { "body": "<p>You can just step forward one day at a time, until you find a week day that is valid. If you change the second parameter to a <code>params</code> parameter, as svick suggested, the code gets very straight forward:</p>\n\n<pre><code>public static DateTime NextByDayOfWeek(this DateTime target, params DayOfWeek[] validDaysOfWeek) {\n do {\n target = target.AddDays(1);\n } while (!validDaysOfWeek.Contains(target.DayOfWeek));\n return target;\n}\n</code></pre>\n\n<p>You can also make a bitmask out of the valid days, so that you don't have to use the <code>Contains</code> method, which would loop through the collection of valid days for each iteration:</p>\n\n<pre><code>public static DateTime NextByDayOfWeek(this DateTime target, IEnumerable&lt;DayOfWeek&gt; validDaysOfWeek) {\n int valid = 0;\n foreach (DayOfWeek d in validDaysOfWeek) {\n valid |= 1 &lt;&lt; (int)d;\n }\n do {\n target = target.AddDays(1);\n } while ((valid &amp; 1 &lt;&lt; (int)target.DayOfWeek) == 0);\n return target;\n}\n</code></pre>\n\n<p>I tested both these functions with a range of different values, and they seem to give the correct result in all cases.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T15:24:29.860", "Id": "53703", "Score": "1", "body": "This one too is a clean solution. The second one is clever, but I don't want the next maintainer to curse me :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T15:33:16.140", "Id": "53704", "Score": "1", "body": "I'm not sure it makes much sense trying to optimize this. After all, there are only 7 days in week." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T15:13:07.827", "Id": "33518", "ParentId": "33510", "Score": "4" } } ]
{ "AcceptedAnswerId": "33517", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T13:31:22.417", "Id": "33510", "Score": "2", "Tags": [ "c#", "datetime" ], "Title": "Get the next date based on a collection of valid weekdays" }
33510
<p>I have wrote a simple util to submit my code to <a href="http://poj.org" rel="nofollow">a online judge site</a>, how to avoid the evil function?</p> <pre><code>(setq url-proxy-services '(("http" . "localhost:8888"))) (setq debug-on-error t) (require-package 'http-post-simple) (require 'http-post-simple) (eval-when-compile (require 'cl)) (defstruct form action (method "POST") fields) (defstruct site url forms) (setq poj (make-site :url "http://poj.org" :forms '( (login . (make-form :action "login" :fields `( (user_id1 . "you-name") (password1 . ,(read-passwd "input your password: ")) (url . "%2F") (B1 . "login")))) (submit . (make-form :action "submit" :fields `( (problem_id ,(read-string "inpur problem id: ")) (language ,(read-string "select language: 0:G++,1:GCC,2:Java,3:Pascal,4:C++,5:C,6:Fortan ")) (source ,(with-temp-buffer (insert-file-contents (read-file-name "select source file"))(buffer-string))) (submit "Submit")))) (logout . (make-form :action "login?action=logout&amp;url=%2F" :method "GET"))))) (defun http-get-simple(url) (let (header data status) (with-current-buffer (url-retrieve-synchronously url) (setq status url-http-response-status) (goto-char (point-min)) (if (search-forward-regexp "^$" nil t) (setq header (buffer-substring (point-min) (point)) data (buffer-substring (1+ (point)) (point-max))) (setq data (buffer-string))) (kill-buffer (current-buffer))) (values data header status))) (defun request-site(site form) "perform a request to site" (let* ((url (site-url site)) (form (cdr (assoc form (site-forms site)))) (form-inst (eval form)) (result (if (equal (form-method form-inst) "POST") (http-post-simple (concat url "/" (form-action form-inst)) (form-fields form-inst)) (http-get-simple (concat url "/" (form-action form-inst)))))) result)) (defun poj-login() (interactive) (request-site poj 'login)) (defun poj-logout() (interactive) (request-site poj 'logout)) (defun poj-submit() (interactive) (request-site poj 'submit)) </code></pre> <p>Above is my code, I have tried this</p> <pre><code>(let* ((form (cdr (assoc 'submit (site-forms poj)))) (frm-inst (apply (car form) (cdr form)))) ; get weird result (eval form)) ; get proper result </code></pre> <p>And can you give me some advice about coding style?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T15:06:22.967", "Id": "53702", "Score": "1", "body": "please indent your code properly!" } ]
[ { "body": "<p>The short answer to your question is that <em>forms</em> are <em>evaluated</em> while <em>functions</em> are <em>called</em> (using <code>funcall</code> or <code>apply</code>).</p>\n\n<p>I.e., the way you structure your code (lists of forms) you are painting yourself into the <code>eval</code> corner. You need to replace lists of forms with lists of functions and then you will be able to use <code>funcall</code> or <code>apply</code>.</p>\n\n<p>E.g., replace</p>\n\n<pre><code>`((problem_id ,(read-string \"inpur problem id: \"))\n (language ,(read-string \"select language: 0:G++,1:GCC,2:Java,3:Pascal,4:C++,5:C,6:Fortan \"))\n (source ,(with-temp-buffer\n (insert-file-contents (read-file-name \"select source file\"))\n (buffer-string)))\n (submit \"Submit\"))\n</code></pre>\n\n<p>with something like</p>\n\n<pre><code>`((problem-id read-string \"problem id: \")\n (language read-string \"language: 0:G++,1:GCC,2:Java,3:Pascal,4:C++,5:C,6:Fortan \")\n (source ,(lambda () (file-to-string (read-file-name \"source file: \"))))\n (submit identity \"Submit\"))\n</code></pre>\n\n<p>Where <code>file-to-string</code> is defined thus:</p>\n\n<pre><code>(defun file-to-string (file)\n \"Read the content of FILE and return it as a string.\"\n (with-temp-buffer\n (insert-file-contents file)\n (buffer-string)))\n</code></pre>\n\n<p>Now you can replace <code>(eval form)</code> with <code>(apply (car form) (cdr form))</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T09:00:13.533", "Id": "53889", "Score": "0", "body": "Use lambda can't get right result, because `cl-defstruct` will wrap list with list, it's so weird. Thanks for your answer, it a good clue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T13:14:08.243", "Id": "53901", "Score": "1", "body": "@ifree: you should use defstruct-defined accessors instead of car/cdr." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T15:21:44.023", "Id": "33521", "ParentId": "33515", "Score": "3" } } ]
{ "AcceptedAnswerId": "33521", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T14:27:54.883", "Id": "33515", "Score": "1", "Tags": [ "lisp", "elisp" ], "Title": "How do I avoid eval in elisp?" }
33515
<p>I have created a module/factory/directive for AngularJS which allows to save user input to localStorage and restore it if needed.</p> <p>Although it works quite good, I am sure that I could improve its code base and am looking for advice to do so.</p> <p>It can be found on github: <a href="https://github.com/sprottenwels/saintAnthony.js" rel="nofollow">https://github.com/sprottenwels/saintAnthony.js</a></p> <p>Code : </p> <pre><code>;var saintAnthony = angular.module('saintAnthony',[]); saintAnthony.directive('savior',function(blackbox){ return{ restrict: 'A', scope: true, link: function(scope,element,attrs){ var elementData = {}; var _getElementData = function(el){ var data = {}; var dotIndex = 0; el = el.isString ? el : el.toString(); dotIndex = el.indexOf('.'); data.container = attrs.savior !== "" ? attrs.savior : false; data.index = attrs.saviorindex !== undefined ? parseInt(attrs.saviorindex) : 0 ; data.mainGroup = dotIndex !== -1 ? el.substr(0,dotIndex) : el; data.key = el.substr(dotIndex +1,el.length); data.value = element[0].value; return data; }; scope.saveSingleElement = function(){ var obj = {}; if (!blackbox.hasGroup(elementData.mainGroup)){ blackbox.addGroup(elementData.mainGroup); } obj[elementData.key] = elementData.value; blackbox.updateGroup(elementData.mainGroup,obj); }; scope.saveRepeatedElement = function(){ var obj = {}; if (!blackbox.hasGroup(elementData.container)){ blackbox.addGroup(elementData.container,true); } obj[elementData.key] = elementData.value; blackbox.updateRepeatGroup(elementData.container,obj,elementData.index); console.dir(blackbox.groups); }; element.bind('input',function(){ elementData = _getElementData(attrs.ngModel); scope.$apply(function(){ if(!elementData.container){scope.saveSingleElement();} else{scope.saveRepeatedElement();} }); }); } } }); </code></pre>
[]
[ { "body": "<p>my two cents : </p>\n\n<ul>\n<li><p>add <code>.idea</code> to your <code>.gitignore</code>. If someone else uses the same IDE as you and works on this code, it could get very frustrating.</p></li>\n<li><p>your code is not minification-proof, which can be annoying for someone who plans to use it. See <a href=\"http://docs.angularjs.org/tutorial/step_05\" rel=\"nofollow\">angular's doc</a> (section \"a note on minification\") for directions on how to fix this.</p></li>\n<li><p>you dynamically extend <code>String.prototype</code> - this kind of monkey-patching can create conflicts with other libs, and lead to unexpected behaviors. If you want people to use your code, you should avoid this, especially for such simple code that you only use once.</p></li>\n<li><p>you have two different entities defined in the same file, but that's ok as the whole lib is very lightweight. For more complex projects, split up your code, one entity per file.</p></li>\n<li><p>your code lacks tests, which is a major no-go for many people.</p></li>\n<li><p>instead of the quirky ng-change directive, you can directly set a change handler during the linking phase using <code>$scope.$watch('something', function(){...})</code>. </p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T19:50:30.787", "Id": "53716", "Score": "0", "body": "I've seldom seen a better criticsm. Thank you.\nSolely, i've got another question: Could you explain what makes the ng-change directive a bad one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T20:09:15.570", "Id": "53719", "Score": "1", "body": "it's not bad _per se_, it's just that it hinders flexibility in this case : what if you want to add another handler than your one via `ng-change` ? Moreover, directives are here to encapsulate behaviour of your components ; here you ask people to know a bit too much about the internals of your directive. It's better to provide a default handler, and maybe let people override this via a data-attribute for instance" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T18:42:44.950", "Id": "33533", "ParentId": "33519", "Score": "4" } } ]
{ "AcceptedAnswerId": "33533", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T15:13:30.080", "Id": "33519", "Score": "1", "Tags": [ "javascript", "angular.js" ], "Title": "Local Storage accessor and modifier helper" }
33519
<p>So I was trying to do <a href="http://tour.golang.org/#71" rel="nofollow">this exercise from Tour of Go</a>. I managed to get it working. I am not at all sure that it is correctly concurrent or idiomatic (I started learning Go, like, 4 hours ago).</p> <p>I would really appreciate feedback about my solution. Here's the relevant meat of the code. Full code available below.</p> <pre><code>type urlToFetch struct { Url string Depth int } // Group stuff together, so that it's easier to pass around. type fetchContext struct { Queue chan urlToFetch History map[string]int Quit chan int Fetcher Fetcher } func Crawl(url string, depth int, fetcher Fetcher) { context := fetchContext{ Queue: make(chan urlToFetch, 500), History: make(map[string]int), Quit: make(chan int, 50), Fetcher: fetcher, } go fetchOne(&amp;context) context.Queue &lt;- urlToFetch{url, depth} &lt;-context.Quit } func fetchOne(ctx *fetchContext) { timeout := time.After(2000 * time.Millisecond) select { case utf := &lt;-ctx.Queue: if utf.Depth &gt; 0 { body, urls, err := ctx.Fetcher.Fetch(utf.Url) ctx.History[utf.Url] = 1 if err != nil { fmt.Println(err) return } fmt.Printf("found: %s %q\n", utf.Url, body) for _, u := range urls { go fetchOne(ctx) if _, ok := ctx.History[u]; !ok { ctx.Queue &lt;- urlToFetch{u, utf.Depth - 1} } else { } } } case &lt;-timeout: ctx.Quit &lt;- 1 } } </code></pre> <p>The full source is at: <a href="http://pastie.org/8443147" rel="nofollow">http://pastie.org/8443147</a></p>
[]
[ { "body": "<p>There are two things I see.</p>\n\n<ul>\n<li><p>Don't store a reference to a time out. I think the count down starts when After() is called.</p>\n\n<pre><code>timeout := time.After(2000 * time.Millisecond)\n...\ncase &lt;- timeout:\n</code></pre>\n\n<p>Most code I've seen writes it like this.</p>\n\n<pre><code>case &lt;- time.After(2000 * time.Millisecond):\n</code></pre></li>\n<li><p>Use a lock when accessing a map from multiple goroutines because maps aren't thread safe.</p></li>\n</ul>\n\n<p><a href=\"http://soniacodes.wordpress.com/2011/10/09/a-tour-of-go-69-exercise-web-crawler/\" rel=\"nofollow noreferrer\">Better solution:</a></p>\n\n<pre><code>func Crawl(url string, depth int, fetcher Fetcher) {\n m := map[string]bool{url: true}\n var mx sync.Mutex\n var wg sync.WaitGroup\n var c2 func(string, int)\n c2 = func(url string, depth int) {\n defer wg.Done()\n if depth &lt;= 0 {\n return\n }\n body, urls, err := fetcher.Fetch(url)\n if err != nil {\n fmt.Println(err)\n return\n }\n fmt.Printf(\"found: %s %q\\n\", url, body)\n mx.Lock()\n for _, u := range urls {\n if !m[u] {\n m[u] = true\n wg.Add(1)\n go c2(u, depth-1)\n }\n }\n mx.Unlock()\n }\n wg.Add(1)\n c2(url, depth)\n wg.Wait()\n}\n</code></pre>\n\n<p>Useful link:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/12224962/exercise-web-crawler-concurrency-not-working\">https://stackoverflow.com/questions/12224962/exercise-web-crawler-concurrency-not-working</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T22:13:18.560", "Id": "36877", "ParentId": "33524", "Score": "3" } } ]
{ "AcceptedAnswerId": "36877", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T16:42:07.177", "Id": "33524", "Score": "4", "Tags": [ "go", "concurrency", "http" ], "Title": "Web Crawler (A Tour of Go #71)" }
33524
<p>I'll gladly appreciate it if you could review my code below and let me know if they are sufficiently secure.</p> <p>My main website and these scripts will use same database, so I need to make sure they are sufficiently secure before I put them live.</p> <p>Since I cannot post more than two links, I'll post my Anti-SQL Injection script, and below are the actual two scripts.</p> <pre><code>&lt;?php if (!function_exists('sql_inject_chec')) { function sql_inject_chec(){ // Anti-SQL Injection $badwords = array("--",";","'",'"',"DROP", "SELECT", "UPDATE", "DELETE", "drop", "select", "update", "delete", "WHERE", "where","exec","EXEC", "procedure","PROCEDURE"); foreach($_REQUEST as $value) { foreach($badwords as $word) if(substr_count($value, $word) &gt; 0) { die("SQL Эnjection Denemesi Yaptэnэz... ama Baюarэsэz Oldunuz ;)"); } } } } sql_inject_chec(); ?&gt; </code></pre> <p><a href="http://pastebin.com/HnGiYAVt" rel="nofollow">Ingame registration</a> - SCRIPT</p> <p><a href="http://pastebin.com/eLTZ2p2q" rel="nofollow">Score display</a> - SCRIPT</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T17:51:22.740", "Id": "53711", "Score": "3", "body": "[Please include the code in the question, not a link to it.](http://codereview.stackexchange.com/help/on-topic)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T09:31:44.580", "Id": "53774", "Score": "0", "body": "Use Mysqli or even better, PDO" } ]
[ { "body": "<p>personally I would just parameterize your Queries, this is going to be easier and more secure to do for your code than to try and weed out all the bad words or Escape Characters or other SQL Symbols. </p>\n\n<p>I am not 100% sure how you do it PHP. lucky for us, someone has asked this question on <a href=\"https://stackoverflow.com/q/60174/1214743\">StackOverflow</a> already.</p>\n\n<p>they go through ways to protect your Database with prepared statements and parameterized queries.</p>\n\n<p>you should probably look at this, fix your code, and then repost.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T19:14:49.810", "Id": "33537", "ParentId": "33526", "Score": "2" } }, { "body": "<p>Trying to improve the structure of the code which you posted by removing the inner foreach loop. </p>\n\n<pre><code>foreach($_REQUEST as $value) {\n if isset($badwords[$value]) { \n die(\"SQL -njection Denemesi YaptMnMz... ama BaNarMsMz Oldunuz ;)\"); \n }\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T20:49:37.250", "Id": "54351", "Score": "0", "body": "You don't use $value in your code, if you meant to invert the badwords array, then it won't pick up cases where the string contains more than just the badword - which is a pre-requisite for SQL injection, you ignore the case issue....." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T03:14:50.887", "Id": "54385", "Score": "0", "body": "@symcbean you are right. I actually typed wrong and wrote $word instead of $value. I edited my answer.My intention with this code is to eliminate the inner foreach loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T05:17:35.880", "Id": "54389", "Score": "0", "body": "This is different functionality than the original code (and the original functionality isn't worth recreating to begin with...). Also, there's a syntax error in it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T11:24:46.680", "Id": "33574", "ParentId": "33526", "Score": "-3" } }, { "body": "<p>This is not a constructive way to protect your scripts from SQL injection — the objective of SQL-injection prevention should not be to <em>disallow</em> characters or words, but to <em>escape</em> characters. What you have now, prevents your users from submitting perfectly valid English words such as <em>select</em>, <em>update</em>, etc. and/or perfectly valid characters such as --, \" and '.</p>\n\n<p>Consider this fictional comment:</p>\n\n<blockquote>\n <p>When I select \"where\" from the menu, it updates the procedure -- strange.</p>\n</blockquote>\n\n<p>This would be rejected by your code.</p>\n\n<p>Now, I'm sure, for your application, this might (currently) be irrelevant, but your code is not very flexible or portable. What happens if your current application, or another future application needs to accept these words? You'd have to rewrite your code, and for a possible new application you wouldn't be able to copy existing code.</p>\n\n<p>More importantly though, your current code is probably not elaborate enough to mitigate all possible attack vectors. You'd really be wise to implement prepared, parameterized statements by using <a href=\"http://php.net/PDO\">PDO</a>, instead of trying to prevent your users from entering possible SQL keywords and characters. With prepared, parameterized statements you don't have to worry about escaping the correct characters anymore — PDO (or, if the driver supports it natively, the database driver) will escape the parameter values you supply for you.</p>\n\n<p>Let me give you a short introductory example of how you could implement SQL-injection prevention with PDO:</p>\n\n<pre><code>// create a database connection handle\n$driver = 'odbc';\n$database = 'kn_online';\n$username = '*redacted*';\n$password = '*redacted*';\n$dbh = new PDO( \"$driver:$database\", $username, $password );\n\n// create a parameterized statement to select a record from CURRENTUSER\n// uses a named parameter (denoted by :), called accountId\n// that will be properly escaped by PDO\n$sql = 'SELECT * FROM CURRENTUSER WHERE StrAccountID = :accountId';\n\n// prepare the statement; returns a PDOStatement object\n$stmt = $dbh-&gt;prepare( $sql );\n\n// execute the statement by passing the parameter values in an associative array\n$executionResult = $stmt-&gt;execute( array(\n ':accountId' =&gt; $acc\n) );\n\n// if the execution succeeded\nif( $executionResult )\n{\n // fetch the record as an associative array\n $record = $stmt-&gt;fetch( PDO::FETCH_ASSOC );\n}\n</code></pre>\n\n<p>The beauty of prepared statements is that you can also easily execute them repeatedly, with new parameter values. Consider this example (connection handle creation omitted for brevity):</p>\n\n<pre><code>// insert into some table\n$sql = 'INSERT INTO SOMETABLE VALUES( :id, :name )';\n\n$stmt = $dbh-&gt;prepare( $sql );\n\n// some fictional data\n// parameter value keys don't need : prepended\n$data = array(\n array( 'id' =&gt; 1, 'name' =&gt; 'Name One' ),\n array( 'id' =&gt; 2, 'name' =&gt; 'Name Two' ),\n array( 'id' =&gt; 3, 'name' =&gt; 'Name Three' )\n);\n\nforeach( $data as $datum )\n{\n // using the same prepared statement\n // to execute for each datum\n $stmt-&gt;execute( $datum );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T13:37:49.183", "Id": "53905", "Score": "0", "body": "very nice, thank you for the Examples and Explanation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T12:43:21.177", "Id": "33578", "ParentId": "33526", "Score": "9" } }, { "body": "<blockquote>\n <p>if (!function_exists('sql_inject_chec')) {</p>\n</blockquote>\n\n<p>Oh dear, fail on line one. </p>\n\n<p>If you don't know how your code is linking at runtime then you can't predict it's behaviour and hence can be fairly sure that you won't be able to say with any certainty that it's secure. Admittedly it's impossible to keep track of exactly how a complex system will behave - that's why we test code. A better approach is to define the function unconditionally - then if it fails try to work out why.</p>\n\n<p>Next, why the mix of lower case and UPPER case words? I can simply bypass your check by sending <code>DrOp TaBlE uSeRs;</code></p>\n\n<p>Not reviewing the linked code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T20:47:54.623", "Id": "33884", "ParentId": "33526", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T17:03:58.523", "Id": "33526", "Score": "3", "Tags": [ "php", "security", "sql-injection" ], "Title": "SQL-injection mitigation script" }
33526
<p>Given a particular <code>Date</code>, want to find the next occurring Friday. I solved it using the below code. Various tested scenarios work good for me.</p> <ol> <li>Are there any boundary conditions the code might break?</li> <li>Can it be written any better?</li> </ol> <p></p> <pre><code>function dates() { var dayOfWeek = 5;//friday var date = new Date(2013, 10, 13); var diff = date.getDay() - dayOfWeek; if (diff &gt; 0) { date.setDate(date.getDate() + 6); } else if (diff &lt; 0) { date.setDate(date.getDate() + ((-1) * diff)) } console.log(date); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T18:50:50.023", "Id": "53712", "Score": "0", "body": "Do you mean the next friday following the date, or the next friday on the date or later? The code will do the latter. There is a bug i the code, you are using `6` instead of `diff` if `diff > 0`. The code `(-1) * diff` can be written simpler as `-diff`, but then of course `+ ((-1) * diff)` can be written as `- diff`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T08:42:38.063", "Id": "53771", "Score": "0", "body": "yes the later.. that's wat i want to find. On 6. The logic is for saturday. If diff > 0 that means i can only saturday. saturday + 6 gives you next consecutive firday" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T12:52:22.123", "Id": "53782", "Score": "0", "body": "Then the implementation only works for friday, while the question title specifies that it should work for any dayOfWeek value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T02:11:04.147", "Id": "53882", "Score": "0", "body": "you are right 6 is specific to friday! :)" } ]
[ { "body": "<ol>\n<li>No, it looks fine.</li>\n<li>Yes, it can be. A hint: use \"% 7\" - this will narrow the delta to the one week only.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T08:41:47.153", "Id": "53770", "Score": "0", "body": "Alex, date.getDay() is already Mod 7. I don;t know how %7 can improve" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T11:33:10.087", "Id": "53779", "Score": "0", "body": "`d.setDate(d.getDate() + (12 - d.getDay()) % 7);` will set the `d` to the next Friday." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-11T06:42:54.513", "Id": "378022", "Score": "1", "body": "@AlexNetkachov Interesting solution with 12. Can you add a bit more explanation, please?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T18:14:06.077", "Id": "33531", "ParentId": "33527", "Score": "0" } }, { "body": "<p>Since you say \"Given a particular Date\" and \"next occurring Friday (or any dayOfWeek)\" I think both should be parameters to your function. As it is written, it will only return November 15 always.</p>\n\n<pre><code>function dates(date, dayOfWeek)\n</code></pre>\n\n<p>But then you should check that <em>dayOfWeek</em> is in range (0-6, thanks SridharVenkat) and probably that <em>date</em> is a valid Date object.</p>\n\n<p>If you do this, you also have to consider not modifying the date parameter and copy it instead.</p>\n\n<p>The names on the variables are clear enough, but not of the function, <em>dates</em> is too broad. <em>getNextDayOfWeek</em> says a lot about what this function does.</p>\n\n<pre><code>function getNextDayOfWeek(date, dayOfWeek)\n</code></pre>\n\n<p>The logic is correct, I think, I only tested it with a few numbers. But you instead of <code>+ ((-1) * diff))</code> you could simply do <code>- diff</code>.</p>\n\n<p>Finally, you're always outputting the result to the console. If this is more than an exercise, you should return the result, and let the user of the function do with it whatever he/she needs.</p>\n\n<p><strong>Edit</strong>: As SridharVenkat said, the range should be 0-6 not 1-7.</p>\n\n<p>Also, using modulo like AlexAtNet suggested you can reduce the code with\n<code>resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7)</code></p>\n\n<p>My (edited) proposal:</p>\n\n<pre><code>function getNextDayOfWeek(date, dayOfWeek) {\n // Code to check that date and dayOfWeek are valid left as an exercise ;)\n\n var resultDate = new Date(date.getTime());\n\n resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7);\n\n return resultDate;\n}\n</code></pre>\n\n<p>PS: Please correct me if I said something wrong of if there's more to improve.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T08:45:47.563", "Id": "53772", "Score": "1", "body": "i don't have 15 points to upvote. once i get i will do that. In dayOfWeek parameter it should be 0-6, that's how javascript works. \\" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T14:54:34.147", "Id": "53795", "Score": "0", "body": "Corrected, and also used @AlexAtNet version without the ifs" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-10T14:38:20.320", "Id": "228208", "Score": "0", "body": "If you wanting the next Friday when you're on a Friday so not the current Friday you need to change it slightly `(date.getDate() + (7 + dayOfWeek - date.getDay()+1) % 7) +1` this will make your modulo work from tomorrow so it will zero out unless your on a Friday and leave a `+1` if your are." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T18:16:10.063", "Id": "33532", "ParentId": "33527", "Score": "21" } }, { "body": "<p>You can produce a formula by looking at the values that you have and the values that you want.</p>\n\n<p>You have the current day of week, and you want to know how many days to go forward to get to a friday:</p>\n\n<pre><code>day offset\n--- ------\n 0 +5\n 1 +4\n 2 +3\n 3 +2\n 4 +1\n 5 +0\n 6 +6\n</code></pre>\n\n<p>You can use 5 - dayOfWeek to get the right value for most days:</p>\n\n<pre><code>day offset 5-d\n--- ------ ---\n 0 +5 5\n 1 +4 4\n 2 +3 3\n 3 +2 2\n 4 +1 1\n 5 +0 0\n 6 +6 -1\n</code></pre>\n\n<p>You could just add 7 when you get a negative value and you would be there, but you can also use <code>%7</code> to get there. Add another week so that you have all positive values, then use <code>%</code> to get it down to the range 0-6:</p>\n\n<pre><code>day offset 5-d 12-d (12-d)%7\n--- ------ --- ---- --------\n 0 +5 5 12 5\n 1 +4 4 11 4\n 2 +3 3 10 3\n 3 +2 2 9 2\n 4 +1 1 8 1\n 5 +0 0 7 0\n 6 +6 -1 6 6\n</code></pre>\n\n<p>So the formula for the offset would be <code>(dayOfWeek + 7 - currDayOfWeek) % 7</code>. Using <code>getDate</code> and <code>setDate</code> to change a date:</p>\n\n<pre><code>function dates() {\n var dayOfWeek = 5;//friday\n var date = new Date(2013, 10, 13);\n date.setDate(date.getDate() + (dayOfWeek + 7 - date.getDay()) % 7);\n console.log(date);\n}\n</code></pre>\n\n<p>And in a more reusable form:</p>\n\n<pre><code>function setDay(date, dayOfWeek) {\n date = new Date(date.getTime ());\n date.setDate(date.getDate() + (dayOfWeek + 7 - date.getDay()) % 7));\n return date;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T04:51:38.547", "Id": "54007", "Score": "0", "body": "Thanks for the explanation... It helped a lot. Few issues i found. 1) 'GetDate' should be 'getDate'. 2) setDate does not return a date rather a number(time), so we have to get rid of the getTime there.. updated code here -http://jsfiddle.net/aS5sh/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T06:39:24.383", "Id": "54012", "Score": "0", "body": "@SridharVenkat: Thanks. I updated the code so that it doesn't use the return value of the `setDate` method at all, as that is undocumented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-11T06:40:00.573", "Id": "378020", "Score": "0", "body": "Please check @Remy Mellet answer that has small improvement if you want a next week's date of today." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T13:23:21.477", "Id": "33648", "ParentId": "33527", "Score": "5" } }, { "body": "<p>In my case I don't want to have the current day if the day I'm asking is today. Improved solution of previous answer :</p>\n\n<pre><code> /**\n * Returns the date of the next day. If today is friday and we are asking for next friday the friday of the next week is returned.\n * @param dayOfWeek 0:Su,1:Mo,2:Tu,3:We,4:Th,5:Fr,6:Sa\n */\n getNextDayOfWeek: function(date, dayOfWeek) {\n var resultDate = new Date(date.getTime());\n resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay() - 1) % 7 +1);\n return resultDate;\n },\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-22T15:23:00.717", "Id": "173668", "ParentId": "33527", "Score": "4" } } ]
{ "AcceptedAnswerId": "33532", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T17:41:50.953", "Id": "33527", "Score": "19", "Tags": [ "javascript", "datetime" ], "Title": "Find next occurring Friday (or any dayOfWeek)" }
33527
<p>This was a revision, made when the code failed after an update (at least that is what I think happened).</p> <p>So I fixed it and now it works, but I think that this code can be written better and more efficiently, and perhaps made easier to read. Note that VBScript/VBA/VB6 isn't (aren't) my primary language(s), the closest thing I do is C#.</p> <p>I presume that the <code>If</code> statements can be whittled down a little bit, (I <em>know</em> they can).</p> <p>I am unsure of the version/flavor of VB this is, but given that it is written inside <code>&lt;script&gt;</code> tags I presume it's VBScript.</p> <pre><code>Public Function GetParameterXml() GetParameterXml = _ "&lt;Parameters&gt;" &amp;_ " &lt;Parameter Value='TYPE' Code='T' Description='Type' Type='Combo' Tooltip='Select parameters from the drop down list.'&gt;" &amp;_ " &lt;Options&gt;" &amp;_ " &lt;Option Code='1' Description='Assignee Name' Value='A' /&gt;" &amp;_ " &lt;Option Code='2' Description='Creditor Name' Value='C' /&gt;" &amp;_ " &lt;Option Code='3' Description='Debtor Name' Value='D' /&gt;" &amp;_ " &lt;/Options&gt;" &amp;_ " &lt;/Parameter&gt;" &amp;_ " &lt;Parameter Value='NAMEFORMAT' Code='T' Description='Name Format' Type='Combo' Tooltip='Select parameters from the drop down list.'&gt;" &amp;_ " &lt;Options&gt;" &amp;_ " &lt;Option Code='11' Description='First Mid Last' Value='1' /&gt;" &amp;_ " &lt;Option Code='12' Description='Last, First Mid' Value='2' /&gt;" &amp;_ " &lt;Option Code='13' Description='Last, First' Value='3' /&gt;" &amp;_ " &lt;Option Code='14' Description='Last, First, Mid' Value='4' /&gt;" &amp;_ " &lt;/Options&gt;" &amp;_ " &lt;/Parameter&gt;" &amp;_ "&lt;/Parameters&gt;" End Function Dim Parameter: Set Parameter = Parameters.Item(Bookmark,"TYPE") Dim Parameter2: Set Parameter2 = Parameters.Item(Bookmark,"NAMEFORMAT") Dim sTemp Dim oNodes: Set oNodes = Nothing Dim oNode: Set oNode = Nothing Dim PartyName() Dim ArrayIndex Dim varPartyName Dim FirstName Dim MidName Dim LastName Dim ParameterValue Dim Suffix ReturnData = "" If Parameter2 is Nothing Then ParameterValue = "1" Else ParameterValue = Parameter2.value End If ArrayIndex = 0 If Not Parameter is Nothing Then Set oNodes = xmlDoc.selectNodes("/Record/CelloXml/Integration/Case/JudgmentEvent/Judgment/Additional/SDMonetaryAward/SDMonetaryAwardParties/SDMonetaryAwardParty[PartyConnection[@Word='"&amp; uCase(parameter.Value) &amp;"']]") For each oNode in oNodes For each oNode2 in oNode.childNodes If oNode2.nodeName = "PartyName" Then ReDim Preserve PartyName(ArrayIndex) PartyName(ArrayIndex) = oNode2.text ArrayIndex = ArrayIndex + 1 End If Next Next For each varPartyName in PartyName dim FirstMiddleName LastName = Split(varPartyName, ",")(0) FirstMiddleName = Trim(Split(varPartyName,",")(1)) Suffix = Trim(Split(VarPartyName,",")(2)) MidName = Trim(Split(FirstMiddleName, " ")(1)) FirstName = Trim(Split(FirstMiddleName, " ")(0)) If ParameterValue = "1" Then If IsNull(FirstName) and IsNull(MidName) Then ReturnData = ReturnData &amp; LastName &amp; Chr(13) &amp; Chr(10) ElseIf IsNull(MidName) Then If IsNull(Suffix) Then ReturnData = ReturnData &amp; FirstName &amp; " " &amp; LastName &amp; Chr(13) &amp; Chr(10) Else ReturnData = ReturnData &amp; FirstName &amp; " " &amp; LastName &amp; " " &amp; Suffix &amp; Chr(13) &amp; Chr(10) End If Else If IsNull(Suffix) Then ReturnData = ReturnData &amp; FirstName &amp; " " &amp; MidName &amp; " " &amp; LastName &amp; Chr(13) &amp; Chr(10) Else ReturnData = ReturnData &amp; FirstName &amp; " " &amp; MidName &amp; " " &amp; LastName &amp; " " &amp; Suffix &amp; Chr(13) &amp; Chr(10) End If End If ElseIf ParameterValue = "2" Then If IsNull(FirstName) and IsNull(MidName) Then ReturnData = ReturnData &amp; LastName &amp; Chr(13) &amp; Chr(10) ElseIf IsNull(MidName) Then If IsNull(Suffix) Then ReturnData = ReturnData &amp; LastName &amp; ", " &amp; FirstName &amp; Chr(13) &amp; Chr(10) Else ReturnData = ReturnData &amp; LastName &amp; ", " &amp; FirstName &amp; " " &amp; Suffix &amp; Chr(13) &amp; Chr(10) End If Else If IsNull(Suffix) Then ReturnData = ReturnData &amp; LastName &amp; ", " &amp; FirstName &amp; " " &amp; MidName &amp; Chr(13) &amp; Chr(10) Else ReturnData = ReturnData &amp; LastName &amp; ", " &amp; FirstName &amp; " " &amp; MidName &amp; " " &amp; Suffix &amp; Chr(13) &amp; Chr(10) End If End If ElseIf ParameterValue = "3" Then If IsNull(FirstName) Then ReturnData = ReturnData &amp; LastName &amp; Chr(13) &amp; Chr(10) Else If IsNull(Suffix) Then ReturnData = ReturnData &amp; LastName &amp; ", " &amp; FirstName &amp; Chr(13) &amp; Chr(10) Else ReturnData = ReturnData &amp; LastName &amp; ", " &amp; FirstName &amp; " " &amp; Suffix &amp; Chr(13) &amp; Chr(10) End If End If ElseIf ParameterValue = "4" Then If IsNull(FirstName) and IsNull(MidName) Then ReturnData = ReturnData &amp; LastName &amp; Chr(13) &amp; Chr(10) ElseIf IsNull(MidName) Then If IsNull(Suffix) Then ReturnData = ReturnData &amp; LastName &amp; ", " &amp; FirstName &amp; Chr(13) &amp; Chr(10) Else ReturnData = ReturnData &amp; LastName &amp; ", " &amp; FirstName &amp; Suffix &amp; Chr(13) &amp; Chr(10) End If Else If IsNull(Suffix) Then ReturnData = ReturnData &amp; LastName &amp; ", " &amp; FirstName &amp; ", " &amp; MidName &amp; Chr(13) &amp; Chr(10) Else ReturnData = ReturnData &amp; LastName &amp; ", " &amp; FirstName &amp; " " &amp; Suffix &amp; ", " &amp; MidName &amp; Chr(13) &amp; Chr(10) End If End If End If FirstName = Null LastName = Null MidName = Null FirstMiddleName = Null Suffix = Null Next End If Erase PartyName If Len(ReturnData) &gt; 0 Then ReturnData = Left(ReturnData, Len(ReturnData)-2) End If </code></pre> <p>Again, this is code that I fixed and added to.</p> <p>Input from the XML for the name comes in this format:</p> <blockquote> <p>Johnson, James T, {optional-Suffix}</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T20:31:49.047", "Id": "53721", "Score": "1", "body": "Yay, a [cyclomatic complexity](http://en.wikipedia.org/wiki/Cyclomatic_complexity) party!! I'll look at this when I have a chance :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T20:34:47.173", "Id": "53722", "Score": "0", "body": "I'll just say that every single `Chr(13) & Chr(10)` in there could very well be replaced with `vbNullString` :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T21:30:59.510", "Id": "53728", "Score": "0", "body": "I think it is supposed to be a newline character. this code runs a token that populates on a word document inside of a third party application, lots of fun! would the `vbNullString` behave like a newline? I guess that might be determined by the rules of the main application too?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T21:33:58.790", "Id": "53729", "Score": "0", "body": "I didn't get very far on that link, sounds like what I have going here though, but I am a little confused. sounds like some before bed reading to me...lol" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T22:41:23.990", "Id": "53735", "Score": "1", "body": "Oh darn, what an epic typo/brainfart! I meant `vbNewLine`!! Sorry!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T22:46:36.807", "Id": "53736", "Score": "1", "body": "`vbNullString` is equivalent to `\"\"`.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T01:44:52.493", "Id": "53753", "Score": "0", "body": "Having spent a little bit more time looking at this code, I'm sorry to say, but this code can't work as is. `IsNull(\"\")` returns `False`, and `Split(\"John Doe\", \" \")(2)` blows up with an *index out of bounds* error - the basic assumptions this code makes, are erroneous... or so it seems. **Unless this is VB.net code and not VBA/VB6?**" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T13:13:12.923", "Id": "53784", "Score": "0", "body": "@retailcoder that is probably what this is then. this Script runs with or without the Middle name and/or the suffix as far as my testing has gone so far." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T13:21:31.657", "Id": "53785", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11301/discussion-between-malachi-and-retailcoder)" } ]
[ { "body": "<p>I'm assuming this is VBScript, and I'm not familiar at all with VBScript, and it seems pretty different from VBA/VB6 as far as iterating arrays (can't do <code>For Each</code> on an array in VBA/VB6) and string nullability is concerned - and VBA/VB6 isn't exactly crystal-clear as to what means what.</p>\n<p>From <a href=\"http://www.songhaysystem.com/kb/number/950165041/subject/vba\" rel=\"noreferrer\">this source</a> (dates back from 2000, quotes a dead Microsoft link - emphasis &amp; formatting mine):</p>\n<blockquote>\n<ul>\n<li><p><code>&quot;&quot;</code>: A <strong>zero-length string</strong> (commonly called an &quot;empty string&quot;) is technically a zero-length BSTR that actually uses six bytes of memory. <strong>In general, you should use the constant <code>vbNullString</code> instead</strong>, particularly when calling external DLL procedures.</p>\n</li>\n<li><p><code>Empty</code>: A variant of VarType 0 (vbEmpty) <strong>that has not yet been initialized</strong>. Test whether it is &quot;nil&quot; using the <code>IsEmpty</code> function.</p>\n</li>\n<li><p><code>Nothing</code>: <strong>Destroys an object reference</strong> using the Set statement. Test whether it is &quot;nil&quot; using the <code>Is</code> operator.</p>\n</li>\n<li><p><code>Null</code>: A variant of VarType 1 (vbNull) that means &quot;no valid data&quot; and <strong>generally indicates a database field with no value</strong>. Don't confuse this with a C NULL, which indicates zero. Test whether it is &quot;nil&quot; using the <code>IsNull</code> function.</p>\n</li>\n<li><p><code>vbNullChar</code>: A character having a value of zero. It is commonly used for adding a C NULL to a string or for filling a fixed-length string with zeroes.</p>\n</li>\n<li><p><code>vbNullString</code>: A string having a value of zero, such as a C NULL, <strong>that takes no memory</strong>. Use this string for calling external procedures looking for a null pointer to a string. To distinguish between vbNullString and &quot;&quot;, use the VBA StrPtr function: <strong><code>StrPtr(vbNullString)</code> is zero, while <code>StrPtr(&quot;&quot;)</code> is a nonzero memory address.</strong></p>\n</li>\n</ul>\n</blockquote>\n<hr />\n<p>So, it being a <em>script</em>, I'm not going to try to go and define classes here, <a href=\"http://msdn.microsoft.com/en-us/library/4ah5852c(v=vs.84).aspx\" rel=\"noreferrer\">although it seems to be supported</a>. I'm still trying to wrap my head around all those conditions!</p>\n<p>The conditions (and the fact that they are repeated in all main 4 branches) are actually hiding the intent.</p>\n<p>So I would write a little <code>Coalesce</code> function and do away with all those checks:</p>\n<pre><code> Public Function Coalesce(ByVal value)\n If IsNull(value) Then\n Coalesce = vbNullString\n Else\n Coalesce = CStr(value)\n End If\n End Function\n</code></pre>\n<p>You seem to have a fixed amount of possible values for <code>ParameterValue</code>, to me this looks like a job for some <code>Select Case</code> rather than an <code>If...ElseIf...ElseIf...</code> block - also, separate the concerns of figuring out a line's content and of appending it to the result - because it's the <code>ParameterValue</code> that determines the order of the names, whether they're present or not doesn't matter, they can all be appended - as long as we ensure to replace <code>Null</code> values with non-value <code>vbNullString</code>:</p>\n<pre><code>'note: LastName can't ever be null... unless nothing was supplied at all.\nDim lineResult\nSelect Case ParameterValue\n\n Case &quot;1&quot;: \n 'First Mid Last [Suffix]\n lineResult = Trim(Coalesce(FirstName) &amp; &quot; &quot; _\n &amp; Coalesce(MidName) &amp; &quot; &quot; _\n &amp; Coalesce(LastName) &amp; &quot; &quot; _\n &amp; Coalesce(Suffix))\n\n Case &quot;2&quot;: \n 'Last, First Mid [Suffix]\n lineResult = Trim(Coalesce(LastName) &amp; &quot;, &quot; _\n &amp; Coalesce(FirstName) &amp; &quot; &quot; _\n &amp; Coalesce(MidName) &amp; &quot; &quot; _\n &amp; Coalesce(Suffix))\n\n Case &quot;3&quot;: \n 'Last, First [Suffix] ~&gt; Middle name ignored?\n lineResult = Trim(Coalesce(LastName) &amp; &quot;, &quot; _\n &amp; Coalesce(FirstName) &amp; &quot; &quot; _\n &amp; Coalesce(Suffix))\n\n Case &quot;4&quot;: \n 'Last, First [Suffix], Mid\n lineResult = Trim(Coalesce(LastName) &amp; &quot;, &quot; _\n &amp; Coalesce(FirstName) &amp; &quot; &quot; _\n &amp; Coalesce(Suffix) &amp; &quot;, &quot; _\n &amp; Coalesce(MidName))\n\nEnd Select\n</code></pre>\n<p>This leaves us, in the worst cases, with a <code>lineResult</code> that's ended with <code>&quot;, ,&quot;</code> or <code>&quot;,&quot;</code>. Easy fix - not so neat, but hey between that and a bunch of nested <code>If</code> statements, I go with this:</p>\n<pre><code>If Right(lineResult, 2) = &quot; ,&quot; Then lineResult = Left(lineResult, Len(lineResult) - 2)\nIf Right(lineResult, 1) = &quot;,&quot; Then lineResult = Left(lineResult, Len(lineResult) - 1)\n</code></pre>\n<p>Now all we're missing is <code>lineResult = lineResult &amp; vbNewLine</code>, and then we can do <code>ReturnData = ReturnData &amp; lineResult</code>, and then we can iterate again.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T01:04:26.163", "Id": "53875", "Score": "0", "body": "Gotta say I haven't tested any of this, but I'm quite confident you'd get the exact same results as you do now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T13:21:01.447", "Id": "53902", "Score": "1", "body": "well they want me to take out some of the options for this token, so I will have a chance to change the code again, hopefully the version that this application is using will support the things that you have here, I will check into it and let you know" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T13:21:32.810", "Id": "53903", "Score": "0", "body": "otherwise it looks very nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T13:32:41.860", "Id": "53904", "Score": "1", "body": "Thanks! I think `Case \"3\"` could be dropped, it ends up with the same format as `Case \"4\"` (given #4 would have `Mid` optional) so if you don't have a `MidName` they both output the same result." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T17:31:53.880", "Id": "53927", "Score": "0", "body": "i got pushed to something else, will get back to you on this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T17:56:39.853", "Id": "53931", "Score": "0", "body": "No worries, I'm on something else too! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T20:16:13.500", "Id": "54164", "Score": "2", "body": "Very Elegant, no Bugs yet. now I know when I ask Questions about this it's VBSCRIPT!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T21:47:46.350", "Id": "54169", "Score": "0", "body": "It just occurred to me that you might have doubled-up spaces between name parts in (edge) cases 1 & 2..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:20:34.720", "Id": "54261", "Score": "0", "body": "like if the Middle name is missing? I haven't seen anything like that yet." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T01:02:47.003", "Id": "33625", "ParentId": "33535", "Score": "6" } } ]
{ "AcceptedAnswerId": "33625", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T19:02:39.260", "Id": "33535", "Score": "5", "Tags": [ "xml", "vbscript" ], "Title": "My script is about as scary as the XML it's reading" }
33535
<p>I have a piece of C++ code that transforms a vector where an element only stays one if itself and both of it's neighbors are one as well. End-points are handled as if the missing element is one. For example:</p> <pre><code>old: 1 1 0 1 1 1 0 1 1 0 new: 1 0 0 0 1 0 0 0 0 0 </code></pre> <p>The following block of code works, but I'm not sure if it is optimal. We can assume that <code>block</code> and <code>state</code> are of type <code>std::vector&lt;int&gt;</code>, both of size <code>N</code>, and only contain elements <code>0</code> or <code>1</code>:</p> <pre><code> // Handle the end-points block[0] = state[0]*state[1]; block[N-1] = state[N-2]*state[N-1]; // Set the cooperative behavior for(int i=1;i&lt;N-1;i++) block[i] = state[i-1]*state[i]*state[i+1]; </code></pre> <p>Is there a better way to do this? Should I be using some kind of trickery with <code>std::accumulate</code> and the like? Profiling show that this piece of code is in the inner-block of my simulation and takes up a sizable fraction of my runtime.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T21:01:20.273", "Id": "53725", "Score": "1", "body": "Since you're just using `0`s and `1`s, you *could* consider [`std::vector<bool>`](http://en.cppreference.com/w/cpp/container/vector_bool). On the other hand, the answers [here](http://stackoverflow.com/questions/8399417/why-vectorboolreference-doesnt-return-reference-to-bool) suggest otherwise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T21:03:37.047", "Id": "53726", "Score": "2", "body": "@Jamal space is not an issue, speed is. Some implementations of `std::vector<bool>` are problematic since it is specifically specialized. In general, I've found that I can avoid many of those headaches by using int's instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T23:21:30.950", "Id": "53742", "Score": "2", "body": "@Jamal: std::vector<bool> is not recommended. It is only kept for compatability. It has sever performance issues and does not have the same usage characteristics as other containers. It is considered a bit of a mistake. Prefer `std::bitset<>` if you want bits. But std::vector<char> is a good compromise of speed and size." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T23:23:04.050", "Id": "53743", "Score": "0", "body": "@LokiAstari: Yeah, I was hesitant about the vector, but I also wasn't sure about bitset (although not for the same reason)." } ]
[ { "body": "<p>What you have is probably good enough. If you want to try something crazy, you could always do:</p>\n\n<pre><code>boost::range::transform(boost::irange(0, N), block.begin(), [&amp;](const int i){\n int pre = i-1 &gt;= 0 ? state[i-1] : 1;\n int post = i+1 &lt; N ? state[i+1] : 1;\n return pre * state[i] * post;\n});\n</code></pre>\n\n<p>Not sure I prefer that to the simple loop that you have, but just throwing it out as a potential alternative. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T21:19:33.367", "Id": "53727", "Score": "0", "body": "Thanks, I appreciate the alternative. Wouldn't this be necessarily slower since `pre,post` have to be check `N` times rather than once?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T21:09:36.410", "Id": "33544", "ParentId": "33540", "Score": "1" } }, { "body": "<p>If speed really is an issue, I would try this rewrite of your loop:</p>\n\n<pre><code>const int *prev = &amp;state[0];\nint *pblock = &amp;block[1];\nfor (int i = 0; i &lt; N-1; ++i, ++prev, ++pblock) { // hopefully i is a compile-time constant?\n *pblock = prev[0] * prev[1] * prev[2];\n}\n</code></pre>\n\n<p>If <code>N</code> is sufficiently large, this could reduce how much you have to jump around in memory, since you're only ever looking ahead 2, instead of potentially <code>N - 1</code>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T14:57:00.997", "Id": "53796", "Score": "0", "body": "This doesn't actually speed things up, but you've given me an idea that does. I've posted it as an answer, but I'm accepting this one as both answers were useful!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T21:18:51.313", "Id": "33545", "ParentId": "33540", "Score": "1" } }, { "body": "<p>For completeness, I'm using the solution posted below which is inspired from one of @Barry's answers. The idea is to replace <code>[]</code> with a pointer to dereference. This gives about 10% speedup.</p>\n\n<pre><code> // Handle the end-points of the chain\n block[0] = state[0]*state[1];\n block[N-1] = state[N-2]*state[N-1];\n\n auto b_itr = block.begin()+1;\n auto itr0 = state.begin();\n auto itr1 = itr0+1;\n auto itr2 = itr1+1;\n auto end = state.end();\n\n while(itr2 != end) {\n (*b_itr) = (*itr0)*(*itr1)*(*itr2);\n itr0++; itr1++; itr2++; b_itr++;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T14:55:50.490", "Id": "33584", "ParentId": "33540", "Score": "0" } }, { "body": "<p>Like the way you're moving the iterators in sync. -Please check but playing around with N=2000000 and a share of 1s over 0s in the state vector between 1/8 and 1/2 gives me a comparative speed advantage of 20 to 10 times respectively, by structuring the loop:</p>\n\n<pre><code> // ... your loop result; cstate is a copy of the random_shuffle-d state vector\nblock.clear();\nblock.assign(N, 0);\n\nblock[0] = cstate[0]*cstate[1];\nblock[N-1] = cstate[N-2]*cstate[N-1];\nblock[N-2] = cstate[N-3]*cstate[N-2]*cstate[N-1];\nblock[N-3] = cstate[N-4]*cstate[N-3]*cstate[N-2];\n\nb_itr = block.begin()+1;\nitr0 = cstate.begin();\nitr1 = itr0+1;\nitr2 = itr1+1;\n//end = cstate.end();\n\nunsigned c(0); // counter in lieu of cstate.end() which may or may not be hit\n\nwhile(c &lt; N-4) {\n if(0 == (*itr2)) {\n itr0 += 3; itr1 += 3; itr2 += 3; b_itr += 3; c +=3;\n }\n else if(0 == (*itr1)) {\n itr0 += 2; itr1 += 2; itr2 += 2; b_itr += 2; c +=2;\n }\n else if(0 == (*itr0)) {\n itr0++; itr1++; itr2++; b_itr++; c++;\n }\n else {\n (*b_itr) = 1;\n itr0++; itr1++; itr2++; b_itr++; c++;\n }\n}\n</code></pre>\n\n<p>The idea is that if the leading value in state is 0, moving the pointers by 1 will result in a 0 in block next, likewise in the following step. (Replacing constantly assigning 0 or 1 with a default 0 block vector and a conditional if == 1 assignment did not make in itself a noticeable difference.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T02:11:37.747", "Id": "33814", "ParentId": "33540", "Score": "1" } } ]
{ "AcceptedAnswerId": "33545", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T20:00:00.507", "Id": "33540", "Score": "1", "Tags": [ "c++", "optimization" ], "Title": "Transforming a stl vector according to its neighbors" }
33540
<p>I am helping a friend with her Java homework and I adapted a solution I used in a similar project of my own for this. It is supposed to use loose/generous regex to make sure an email entered matches the forms abc123@xyz.net or abc.123@xyz.net.</p> <pre><code>import java.util.Scanner; public class App { Scanner scanner; public App() { this.scanner = new Scanner(System.in); } public static void main(String[] args) { App app = new App(); app.GetUsername(true); } public void GetUsername(Boolean firstRun) { if(!firstRun) { System.out.println("The username you have entered was in an incorrect format. Must match abc@xyz.net"); } else { System.out.println("Please enter a username:"); } String userInput = this.scanner.nextLine(); UsernameCheck usernameCheck = new UsernameCheck(userInput); if(usernameCheck.isValid()) { System.out.println("Welcome, " + userInput + "!"); } else { GetUsername(false); } } } </code></pre> <p>UsernameCheck.java</p> <pre><code>import java.util.regex.*; public class UsernameCheck { String username; public UsernameCheck(String username) { this.username = username; } public Boolean isValid() { return this.username.matches("[a-zA-Z0-9\\.]+@[a-zA-Z0-9\\-\\_\\.]+\\.[a-zA-Z0-9]{3}"); } } </code></pre> <p>I am most interested in hearing alternative solutions for re-prompting a user if the input they've given is invalid. This works in practice, but I am looking for the cleanest way to do it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T22:18:13.150", "Id": "53732", "Score": "0", "body": "Note: Your RegEx is not going to admit (a great many possible) eMail addresses, and will admit invalid ones. (e.g. domain names cannot have _, TLD's can be other than 3 letters, TLD's cannot be 3 digits, and the left-hand-side is significantly more forgiving than your regex.) I know this isn't related to the question you're asking, but do be aware that John_Crichton%special+guy@nasa.gov.us (or .museum) is potentially valid while JSmith@foo_bar.999 is not. (let alone addresses like postmaster@[10.20.30.40])" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T22:32:08.157", "Id": "53734", "Score": "0", "body": "try (\"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\")" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T22:55:13.353", "Id": "53738", "Score": "0", "body": "It was stated in the assignment that only the most well-known three letter TLDs would be checked for (.edu, .com, .org, etc). My main concern was the performence of the GetUsername() method. Is using the method within itself the best choice in this case? Should I just do `while(username isn't valid)` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T23:01:27.690", "Id": "53739", "Score": "0", "body": "In practical terms, I doubt that a real user will enter enough invalid addresses to smash the stack limits before getting bored and aborting the program, but Java doesn't offer tail-call optimization, so you are always in danger with those sorts of algos." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T09:19:55.203", "Id": "409759", "Score": "0", "body": "Shouldn't your friend do her own homework? How is she going to learn anything from you getting internet strangers to do it?" } ]
[ { "body": "<p>My preference for accepting user input in a blocking loop like this might look more like:</p>\n\n<pre><code> public enum Returned { OK, ERROR_EMAIL };\n</code></pre>\n\n<p>…</p>\n\n<pre><code> // Long loop here to get valid user registration info.\n /* In a transactional/event-driven (GUI, web) app this would not be\n * a loop, but with a blocking/modal (tty) program it works. */\n\n UserInfo u = new UserInfo ();\n // loop until you get valid one(s)\n while (!u.isReady()) {\n\n // for each field that must be validated, prompt and try to set it\n if (u.getName () == null) {\n System.out.print (\"Enter an eMail address:\");\n String entered = scanner.nextLine ();\n\n Returned settingName = u.setName (entered);\n\n // check each object's validity and report errors\n switch (settingName) {\n case Returned.OK:\n System.out.println (\"OK.\");\n break;\n case Returned.ERROR_EMAIL:\n System.out.println (\"That does not look like a valid eMail address.\");\n break;\n // No \"default\": if you add new error types later, you can handle them here.\n // The compiler will issue a warning about unhandled enum cases\n }\n }\n }\n</code></pre>\n\n<p>…and then in class UserInfo …</p>\n\n<pre><code> final static Pattern rfc2822 = Pattern\n .compile (\"[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\\\\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\");\n\n public Returned setName (final String address)\n {\n Returned valid = isValid(address);\n if (Returned.OK == valid) { this.name = address; }\n return valid;\n }\n\n public boolean isValid (final String address)\n {\n return ( (rfc2822.matcher(address).matches ())\n ? Returned.OK : Returned.ERROR_EMAIL );\n // you could also check for a valid MX record for the domain part…\n }\n\n public boolean isReady () {\n return name != null; // and whatever else\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T22:58:57.447", "Id": "33550", "ParentId": "33546", "Score": "2" } } ]
{ "AcceptedAnswerId": "33550", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T21:19:52.277", "Id": "33546", "Score": "3", "Tags": [ "java", "regex", "validation" ], "Title": "Simple code to check format of user inputted email address" }
33546
<p>Requires Underscore and jQuery</p> <p>I'm looking for suggestions on how to make this a little more readable and additional suggestions on flow, logic, etc. </p> <p>The game can be run in a browser by just copying and pasting the code(HTML/JS/CSS) below. </p> <p><strong>JavaScript: app/js/app.js</strong></p> <pre><code>var Utils = { rules: { isHorizontal: function (array, move) { return array[0] === move[0]; }, isVertical: function (array, move) { return array[1] === move[1]; }, isDiagonalDown: function (array) { return array[0] === array[1]; }, isDiagonalUp: function (array, boardSize) { return (array[0] + array[1]) === (boardSize - 1); } }, isDuplicate: function (moves, move) { var duplicateAttempt = false; for (var x = 0, l = moves.length; x &lt; l; x++) { if ((moves[x][0] === move[0]) &amp;&amp; (moves[x][1] === move[1])) { duplicateAttempt = true; } } return duplicateAttempt; }, nextPlayerIndex: function (prevPlayer, players) { if (prevPlayer === null) { return Utils.randomPlayerIndex(players); } else { return (prevPlayer === players.length - 1) ? 0 : prevPlayer + 1; } }, randomPlayerIndex: function (players) { return Math.floor(Math.random() * (players.length)); } }; var Markup = { template: function (players, size) { var playerList = function () { var list = '&lt;ul&gt;'; _.each(players, function (player) { list = list + '&lt;li&gt;' + player.symbol + ' / ' + player.name; }); return list; }, table = '&lt;table&gt;', thead = '&lt;thead&gt;&lt;tr&gt;&lt;th colspan="' + size + '"&gt; ' + playerList() + ' &lt;tbody&gt;' row = '&lt;tr&gt;', cell = '&lt;td style="width: ' + (100 / size).toFixed(2) + '%;"&gt;'; table = table + thead; for (var x = 0; x &lt; size; x++) { table = table + row; for (var y = 0; y &lt; size; y++) { table = table + cell; } } return $(table); }, off: function (gameboard) { gameboard.off('click', 'td').find('table').addClass('complete'); }, getCell: function (index, gameboard) { return $('tbody tr', gameboard).eq(index[0]).children().eq(index[1]); }, markCell: function (index, symbol, gameboard) { var cell = Markup.getCell(index, gameboard); cell.html(symbol ? symbol : 'x').addClass('played'); }, highlightCells: function (array, gameboard) { _.each(array, function (index) { var cell = Markup.getCell(index, gameboard); cell.addClass('winning-cell'); }); }, markNextPlayer: function (gameboard, game) { $('thead li', gameboard).removeClass('turn').eq(game.currentPlayer).addClass('turn'); } }; var Game = function (players, size) { this.data = { players: [], size: size || 3, allMoves: [], ended: false, prevPlayer: null, currentPlayer: null, winningMoves: {}, winCondition: [], status: {} }; _.each(players, function (player) { _.extend(player, { moves: [], isWinner: false }); this.data.players.push(player); }, this); this.data.currentPlayer = Utils.randomPlayerIndex(this.data.players); }; _.extend(Game.prototype, { play: function (player, move) { var g = this.data, p = g.players[g.currentPlayer]; g.winningMoves = { horizontal: [], vertical: [], diagonalDown: [], diagonalUp: [] }; g.status.wrongPlayer = g.currentPlayer !== player; g.status.isDuplicate = Utils.isDuplicate(g.allMoves, move); if (g.status.wrongPlayer) { return g; } if (g.status.isDuplicate) { return g; } g.allMoves.push(move); p.moves.push(move); if (p.moves.length &gt;= g.size) { _.each(p.moves, function (pmove) { this.checkRules(pmove, move); }, this); g.winCondition = this.findWinner(g.winningMoves, g.size); p.isWinner = true; } if (g.allMoves.length === (g.size * g.size) &amp;&amp; !g.winCondition) { _.each(g.players, function (pl) { pl.isWinner = null; }); g.winCondition = []; } g.prevPlayer = g.currentPlayer; g.currentPlayer = Utils.nextPlayerIndex(g.prevPlayer, g.players); return g; }, checkRules: function (playerMoves, lastMove) { if (Utils.rules.isHorizontal(playerMoves, lastMove)) { this.data.winningMoves.horizontal.push(playerMoves); } if (Utils.rules.isVertical(playerMoves, lastMove)) { this.data.winningMoves.vertical.push(playerMoves); } if (Utils.rules.isDiagonalDown(playerMoves)) { this.data.winningMoves.diagonalDown.push(playerMoves); } if (Utils.rules.isDiagonalUp(playerMoves, this.data.size)) { this.data.winningMoves.diagonalUp.push(playerMoves); } }, findWinner: function (moves, size) { var winner = []; _.each(moves, function (move) { if (move.length &gt;= size) { winner = move; } }, this); return winner; } }); $(function () { var gameboard = $('.gameboard'), players = [ { name: 'John Doe', symbol: 'x' }, { name: 'Peter Brown', symbol: 'o' } ], startGame = function (gameboard, players) { var game = new Game(players, 3); gameboard.append(Markup.template(game.data.players, game.data.size)); Markup.markNextPlayer(gameboard, game.data); gameboard.on('click', 'td', function () { var move = [$(this).parent()[0].sectionRowIndex, this.cellIndex], play = game.play(game.data.currentPlayer, move); if (play.status.wrongPlayer) { console.log('Wrong player'); return; } if (play.status.isDuplicate) { console.log('Position already played'); return; } Markup.markCell(move, play.players[play.prevPlayer].symbol, gameboard); if (_.isArray(play.winCondition) &amp;&amp; play.winCondition.length) { Markup.highlightCells(play.winCondition, gameboard); Markup.off(gameboard); } if (!play.winCondition.length) { Markup.markNextPlayer(gameboard, play); } }); }, clearGame = function (gameboard) { $('table', gameboard).remove(); gameboard.off('click'); }; $('#startNewGame').click(function () { clearGame(gameboard); startGame(gameboard, players); }); }()); </code></pre> <p><strong>HTML: /index.html</strong></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Tic Tac Toe&lt;/title&gt; &lt;link href="app/css/app.css" rel="stylesheet" media="screen" /&gt; &lt;/head&gt; &lt;body&gt; &lt;button id="startNewGame"&gt;Start New Game&lt;/button&gt; &lt;div class="gameboard"&gt;&lt;/div&gt; &lt;script src="http://code.jquery.com/jquery.js"&gt;&lt;/script&gt; &lt;script src="http://underscorejs.org/underscore-min.js"&gt;&lt;/script&gt; &lt;script src="app/js/app.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>CSS: /app/css/app.css</strong></p> <pre><code>table { border: 0 solid #ccc; margin: 1% auto; width: 60%; height:40em; } table.complete td:hover { background-color:#707070; } table th { font-family:Arial, Verdana; height:3em; background-color:#ffd800; padding: 0 1em; } table td { border: 0 solid #ccc; text-align:center; font-size: 10em; line-height:0; background-color: #707070; color: #fff; text-transform:uppercase; } table td.played:hover { background-color:#707070; } table td:hover { background-color:#878686; } table td.winning-cell:hover { background-color:#000; } ul { list-style:none; margin:0; padding: 0; } ul li { float:left; width:50%; text-align:left; color:#fff6c6; } li.turn { color:#000; } .winning-cell { background-color:#000; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T22:52:15.590", "Id": "53737", "Score": "0", "body": "I took the liberty of copying your code (completely as-is) into [this jsfiddle](http://jsfiddle.net/NuDPq/) for people to try out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T13:47:26.410", "Id": "53787", "Score": "0", "body": "Thanks Flambino, I'll go make the necessary updates to make sure it works properly. I'll add a jsFiddle next time around." } ]
[ { "body": "<p>You code is looks good. I want to suggest a few coding style improvements:</p>\n\n<ul>\n<li>remove unnecessary punctuators (example: <code>(players.length)</code> in <code>return Math.floor(Math.random() * (players.length));</code>);</li>\n<li><code>if</code>s with one statements are not consistent (sometimes one line, sometimes several lines)</li>\n<li><code>var</code> is frequently recommended to be placed on top of the function scope because it actually works this way (defines variable in function scope, not in statement scope).</li>\n</ul>\n\n<p>Other notes:</p>\n\n<ul>\n<li>I recommend to remove the class <code>Utils</code>. It is not a good name for the container of the game rules. Other methods also may be inlined or moved to better location.</li>\n<li>I see that you try to separate different parts of the code (Markup, Game, etc). I suggest to put a little bit more effort in this and apply MVC pattern (see my article about it: <a href=\"http://alexatnet.com/articles/model-view-controller-mvc-javascript\" rel=\"nofollow\">http://alexatnet.com/articles/model-view-controller-mvc-javascript</a> ). It is not necessary to strictly follow the article but it may be useful to try to understand the MVC concept.</li>\n</ul>\n\n<p><code>isDuplicate</code> method:</p>\n\n<ol>\n<li>isDuplicate can be shortened by directly returning the value.</li>\n<li>l is usually not good looking name for the variable, because it easy can be mixed up with the 1, especially with some fonts. For example, <code>x &lt; l</code> can be read as <code>x &lt; 1</code>.</li>\n<li>it is not necessary to save move.length to l. it is optimized well and does not make significant impact (especially in this case).</li>\n</ol>\n\n<p>So it may be rewritten as follows:</p>\n\n<pre><code>isDuplicate: function (moves, move) {\n for (var x = 0; x &lt; moves.length; x++) {\n if ((moves[x][0] === move[0]) &amp;&amp; (moves[x][1] === move[1])) {\n return true;\n }\n }\n return false;\n},\n</code></pre>\n\n<p><code>nextPlayerIndex</code> method:</p>\n\n<ol>\n<li>the else is redundant, because return breaks the <code>if</code> statement.</li>\n<li><p>it may be shortened as follows:</p>\n\n<pre><code>return null === prevPlayer ? Utils.randomPlayerIndex(players) :\n (prevPlayer + 1) % players.length;\n</code></pre></li>\n<li><p>May be removed, because it looks like <code>prevPlayer</code> is never null.</p></li>\n</ol>\n\n<p><code>Markup</code> class:</p>\n\n<p>Use string concatenation for generating the HTML code is not very good, because it may case troubles if the data contains the markup. It not happens now, but may be in the future.</p>\n\n<p>The rest of code looks good enough, but probably will be modified a lot if you will follow the recommendations and apply the MVC pattern to your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T13:48:26.120", "Id": "53788", "Score": "0", "body": "Hey Alex, amazing feedback. I'm reading your article now to find ways of restructuring the code to be more MVC like. The other suggestions are fantastic as well. Thanks!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T14:17:48.290", "Id": "53791", "Score": "0", "body": "var is frequently recommended to be placed on top of the function scope because it actually works this way (defines variable in function scope, not in statement scope). --- Did you have an example in my code to point at? Are you suggesting removing the var declarations in the for-loop-statements?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T14:32:26.057", "Id": "53793", "Score": "0", "body": "Are you suggesting removing the var declarations in the for-loop-statements? --- and move all of them to the top of the function. Yes. This is how it actually works and it does not gives you the false feeling of using two variables while it is actually one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T14:34:56.970", "Id": "53794", "Score": "0", "body": "Right on! I'll refactor those parts as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T21:32:42.637", "Id": "53941", "Score": "0", "body": "I can review you code when you done with the changes if you wish: http://alexatnet.com/projects/code-review-4u Cheers!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T00:02:35.177", "Id": "33553", "ParentId": "33547", "Score": "1" } } ]
{ "AcceptedAnswerId": "33553", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T22:06:01.550", "Id": "33547", "Score": "1", "Tags": [ "javascript", "jquery", "game", "html", "css" ], "Title": "Tic-Tac-Toe JavaScript readability and additional suggestions" }
33547
<p>I have recently written this Minesweeper game in Python:</p> <pre><code>import random class Cell(object): def __init__(self, is_mine, is_visible=False, is_flagged=False): self.is_mine = is_mine self.is_visible = is_visible self.is_flagged = is_flagged def show(self): self.is_visible = True def flag(self): self.is_flagged = not self.is_flagged def place_mine(self): self.is_mine = True class Board(tuple): def __init__(self, tup): super().__init__() self.is_playing = True def __str__(self): board_string = ("Mines: " + str(self.remaining_mines) + "\n " + "".join([str(i) for i in range(len(self))])) for (row_id, row) in enumerate(self): board_string += "\n" + str(row_id) + " " for (col_id, cell) in enumerate(row): if cell.is_visible: if cell.is_mine: board_string += "M" else: board_string += str(self.count_surrounding(row_id, col_id)) elif cell.is_flagged: board_string += "F" else: board_string += "X" board_string += " " + str(row_id) board_string += "\n " + "".join([str(i) for i in range(len(self))]) return board_string def show(self, row_id, col_id): if not self[row_id][col_id].is_visible: self[row_id][col_id].show() if (self[row_id][col_id].is_mine and not self[row_id][col_id].is_flagged): self.is_playing = False elif self.count_surrounding(row_id, col_id) == 0: [self.show(surr_row, surr_col) for (surr_row, surr_col) in self.get_neighbours(row_id, col_id) if self.is_in_range(surr_row, surr_col)] def flag(self, row_id, col_id): if not self[row_id][col_id].is_visible: self[row_id][col_id].flag() else: print("Cannot add flag, cell already visible.") def place_mine(self, row_id, col_id): self[row_id][col_id].place_mine() def count_surrounding(self, row_id, col_id): count = 0 for (surr_row, surr_col) in self.get_neighbours(row_id, col_id): if (self.is_in_range(surr_row, surr_col) and self[surr_row][surr_col].is_mine): count += 1 return count def get_neighbours(self, row_id, col_id): SURROUNDING = ((-1, -1), (-1, 0), (-1, 1), (0 , -1), (0 , 1), (1 , -1), (1 , 0), (1 , 1)) neighbours = [] for (surr_row, surr_col) in SURROUNDING: neighbours.append((row_id + surr_row, col_id + surr_col)) return neighbours def is_in_range(self, row_id, col_id): return 0 &lt;= row_id &lt; len(self) and 0 &lt;= col_id &lt; len(self) @property def remaining_mines(self): remaining = 0 for row in self: for cell in row: if cell.is_mine: remaining += 1 if cell.is_flagged: remaining -= 1 return remaining @property def is_solved(self): for row in self: for cell in row: if not(cell.is_visible or cell.is_flagged): return False return True def create_board(size, mines): board = Board(tuple([tuple([Cell(False) for i in range(size)]) for j in range(size)])) available_pos = list(range((size-1) * (size-1))) for i in range(mines): new_pos = random.choice(available_pos) available_pos.remove(new_pos) (row_id, col_id) = (new_pos % 9, new_pos // 9) board.place_mine(row_id, col_id) return board def get_move(board): INSTRUCTIONS = ("First, enter the column, followed by the row. To add or " "remove a flag, add \"f\" after the row (for example, 64f " "would place a flag on the 6th column, 4th row). Enter " "your move: ") move = input("Enter your move (for help enter \"H\"): ") if move == "H": move = input(INSTRUCTIONS) while not is_valid(move, board): move = input("Invalid input. Enter your move (for help enter \"H\"): ") if move == "H": move = input(INSTRUCTIONS) return (int(move[1]), int(move[0]), True if move[-1] == "f" else False) def is_valid(move_input, board): if move_input == "H" or (len(move_input) not in (2, 3) or not move_input[:1].isdigit() or int(move_input[0]) not in range(len(board)) or int(move_input[1]) not in range(len(board))): return False if len(move_input) == 3 and move_input[2] != "f": return False return True def main(): SIZE = 10 MINES = 9 board = create_board(SIZE, MINES) print(board) while board.is_playing and not board.is_solved: (row_id, col_id, is_flag) = get_move(board) if not is_flag: board.show(row_id, col_id) else: board.flag(row_id, col_id) print(board) if board.is_solved: print("Well done! You solved the board!") else: print("Uh oh! You blew up!") if __name__ == "__main__": main() </code></pre> <p>I am currently aware that when counting <code>remaining_mines</code>, the property function runs each time, whereas it would have been more efficient only adding and subtracting from the mine count when a mine or flag is placed.</p> <p>When I implemented this, however, it looked quite messy, so I chose readability over performance. Was this the right decision? I also think the <code>for a in b: for c in a:</code> which are repeated throughout the code could be cleaned up. Finally, I wasn't sure whether to use a list comprehension or a normal loop in the final <code>elif</code> of <code>Board.show()</code>.</p> <p>Have you got any answers to my questions, or any general tips on how to improve the performance or readability?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-31T20:28:23.120", "Id": "165921", "Score": "0", "body": "Nice code, you could make it more detailed for it to be easier for the user to play, this can be done with something called `pygame` check it out (pygame.org), download a couple of projects off there and look at its code. Then try to use pygame to make your minesweeper even better!" } ]
[ { "body": "<p>From a user interface point of view, it would be good to have :</p>\n\n<ul>\n<li><p>letters for columns and numbers for rows (or the opposite)</p></li>\n<li><p>a clear area for empty cells.</p></li>\n<li><p>something to prevent you from winning just be flagging every single cell.</p></li>\n<li><p>have a way to click on all non-flagged cells around a cell (try left-click and right-click in the same time on the Windows minesweeper, it's really convenient to blow up cells that are known to be safe).</p></li>\n</ul>\n\n<p>Here's what I'd consider a better version of your code using some of the Python good stuff : list comprehension, things like that.</p>\n\n<pre><code>#!/usr/bin/python3\n\nimport random\n\nclass Cell(object):\n def __init__(self, is_mine, is_visible=False, is_flagged=False):\n self.is_mine = is_mine\n self.is_visible = is_visible\n self.is_flagged = is_flagged\n\n def show(self):\n self.is_visible = True\n\n def flag(self):\n self.is_flagged = not self.is_flagged\n\n def place_mine(self):\n self.is_mine = True\n\n\nclass Board(tuple):\n def __init__(self, tup):\n super().__init__()\n self.is_playing = True\n\n def mine_repr(self,row_id, col_id):\n cell = self[row_id][col_id]\n if cell.is_visible:\n if cell.is_mine:\n return \"M\"\n else:\n surr = self.count_surrounding(row_id, col_id)\n return str(surr) if surr else \" \"\n elif cell.is_flagged:\n return \"F\"\n else:\n return \"X\"\n\n def __str__(self):\n board_string = (\"Mines: \" + str(self.remaining_mines) + \"\\n \" +\n \"\".join([str(i) for i in range(len(self))]))\n for (row_id, row) in enumerate(self):\n board_string += (\"\\n\" + str(row_id) + \" \" + \n \"\".join(self.mine_repr(row_id, col_id) for (col_id, _) in enumerate(row)) +\n \" \" + str(row_id))\n board_string += \"\\n \" + \"\".join([str(i) for i in range(len(self))])\n return board_string\n\n def show(self, row_id, col_id):\n cell = self[row_id][col_id]\n if not cell.is_visible:\n cell.show()\n\n if (cell.is_mine and not\n cell.is_flagged):\n self.is_playing = False\n elif self.count_surrounding(row_id, col_id) == 0:\n for (surr_row, surr_col) in self.get_neighbours(row_id, col_id):\n if self.is_in_range(surr_row, surr_col):\n self.show(surr_row, surr_col) \n\n def flag(self, row_id, col_id):\n cell = self[row_id][col_id]\n if not cell.is_visible:\n cell.flag()\n else:\n print(\"Cannot add flag, cell already visible.\")\n\n def place_mine(self, row_id, col_id):\n self[row_id][col_id].place_mine()\n\n def count_surrounding(self, row_id, col_id):\n return sum(1 for (surr_row, surr_col) in self.get_neighbours(row_id, col_id)\n if (self.is_in_range(surr_row, surr_col) and\n self[surr_row][surr_col].is_mine))\n\n def get_neighbours(self, row_id, col_id):\n SURROUNDING = ((-1, -1), (-1, 0), (-1, 1),\n (0 , -1), (0 , 1),\n (1 , -1), (1 , 0), (1 , 1))\n return ((row_id + surr_row, col_id + surr_col) for (surr_row, surr_col) in SURROUNDING)\n\n def is_in_range(self, row_id, col_id):\n return 0 &lt;= row_id &lt; len(self) and 0 &lt;= col_id &lt; len(self)\n\n @property\n def remaining_mines(self):\n remaining = 0\n for row in self:\n for cell in row:\n if cell.is_mine:\n remaining += 1\n if cell.is_flagged:\n remaining -= 1\n return remaining\n\n @property\n def is_solved(self):\n return all((cell.is_visible or cell.is_mine) for row in self for cell in row)\n\ndef create_board(size, mines):\n board = Board(tuple([tuple([Cell(False) for i in range(size)])\n for j in range(size)]))\n available_pos = list(range((size-1) * (size-1)))\n for i in range(mines):\n new_pos = random.choice(available_pos)\n available_pos.remove(new_pos)\n (row_id, col_id) = (new_pos % 9, new_pos // 9)\n board.place_mine(row_id, col_id)\n return board\n\ndef get_move(board):\n INSTRUCTIONS = (\"First, enter the column, followed by the row. To add or \"\n \"remove a flag, add \\\"f\\\" after the row (for example, 64f \"\n \"would place a flag on the 6th column, 4th row). Enter \"\n \"your move: \")\n\n move = input(\"Enter your move (for help enter \\\"H\\\"): \")\n if move == \"H\":\n move = input(INSTRUCTIONS)\n\n while not is_valid(move, board):\n move = input(\"Invalid input. Enter your move (for help enter \\\"H\\\"): \")\n if move == \"H\":\n move = input(INSTRUCTIONS)\n\n return (int(move[1]), int(move[0]), move[-1] == \"f\")\n\ndef is_valid(move_input, board):\n if move_input == \"H\" or (len(move_input) not in (2, 3) or\n not move_input[:1].isdigit() or\n int(move_input[0]) not in range(len(board)) or\n int(move_input[1]) not in range(len(board))):\n return False\n\n if len(move_input) == 3 and move_input[2] != \"f\":\n return False\n\n return True\n\ndef main():\n SIZE = 10\n MINES = 9\n board = create_board(SIZE, MINES)\n print(board)\n while board.is_playing and not board.is_solved:\n (row_id, col_id, is_flag) = get_move(board)\n if not is_flag:\n board.show(row_id, col_id)\n else:\n board.flag(row_id, col_id)\n print(board)\n\n if board.is_solved:\n print(\"Well done! You solved the board!\")\n else:\n print(\"Uh oh! You blew up!\")\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T13:45:03.773", "Id": "33582", "ParentId": "33548", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T22:11:15.493", "Id": "33548", "Score": "6", "Tags": [ "python", "game", "minesweeper" ], "Title": "Minesweeper in Python" }
33548
<p>I have the following declaration in my String.h file:</p> <pre><code>private: char* nstring; int nlength; }; </code></pre> <p>The following are three constructors I've implemented in String.cpp. I would like these to be reviewed.</p> <pre><code>// Default constructor for this class. Initializes an empty string. string::string() { nlength = 1; // for "\0" terminating character at the end of the char array nstring = new char[nlength]; nstring[nlength - 1] = '\0'; } // Constructor for String class. Initializes a string based on the given C string. string::string(const char* input) { nlength = strlen(input) + 1; nstring = new char[nlength]; for (int i = 0; i &lt; (nlength - 1); i++) { nstring[i] = input[i]; } nstring[(nlength - 1)] = '\0'; } // Copy constructor for String class. // Initializes a string from an already existing string. // The contents of the existing string should be copied over to this string. string::string(const string&amp; S) { nlength = S.nlength; nstring = new char[nlength]; for (int i = 0; i &lt; (nlength - 1); i++) { nstring[i] = S.nstring[i]; } nstring[(nlength - 1)] = '\0'; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T23:02:07.557", "Id": "53868", "Score": "4", "body": "Its not the constructor that it is hard. But the interaction of the compiler generated methods. Constructor (default - copy)/Destructor/Assignment (and now Move in C++11). These all have to work together to make memory management work correctly." } ]
[ { "body": "<p>Your lengths are off by 1 everywhere. An empty string has length 0 not 1, <code>\"Hello\"</code> has length 5 not 6, etc. </p>\n\n<p>Your constructor from the <code>const char*</code> can just assign every character in the loop (since we know the <code>nlength</code>th character of <code>input</code> will be <code>\\0</code>, right? Even better would be to use <code>memcpy</code>:</p>\n\n<pre><code>nlength = strlen(input); \nnstring = new char[nlength + 1];\nmemcpy(nstring, input, nlength + 1);\n</code></pre>\n\n<p>Also you have to be careful on the copy constructor. What happens in this code?</p>\n\n<pre><code>string hello(\"hello\");\nhello = hello;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T00:20:29.887", "Id": "53745", "Score": "0", "body": "Thank you! I was wondering: why is `memcpy` better than the `for` loop?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T00:29:35.053", "Id": "53747", "Score": "0", "body": "I'm using c++11 and I can use the memcpy method. Is there a header I need to include?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T00:44:21.707", "Id": "53750", "Score": "2", "body": "I disagree with @Barry: There’s nothing wrong with the lengths as written, as long as `nlength` is not returned from the `size()` method of the string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T22:52:16.610", "Id": "53863", "Score": "0", "body": "Your example \"**What happens in this code?**\" is not copy construction; but rather assignment. Which is easy to implement using the copy and swap idiom." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T22:53:25.723", "Id": "53864", "Score": "0", "body": "@Barry: cppreference is actually terrible resource with lots of errors. But it is OK for quickly checking things like this." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T00:13:15.410", "Id": "33556", "ParentId": "33555", "Score": "5" } }, { "body": "<p>The big question here is why exactly you’re writing a string class. </p>\n\n<ul>\n<li>If you’re doing this for practical use, you’d probably be better off with <code>std::string</code>, or writing a subclass thereof.</li>\n<li>If you really need some specialized functionality, you might still be better off with making <code>nstring</code> a <code>std::vector&lt;char&gt;</code> and leaving the memory management to the library.</li>\n<li>If you want to manage your own memory, you need to be concerned about exception safety. <s>Right now, if any of the calls to <code>new char[]</code> throws an exception, you’re leaving your string instances in an inconsistent state.</s> ETA: While the general point stands, @LokiAstari in comments correctly points out that this is not a concern in this particular class, as there is only a single allocation in the constructor.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T01:41:17.163", "Id": "53752", "Score": "0", "body": "+1. If you go with the vector, the third point is unneeded. I do hope the OP is okay with a vector, knowing the exception-handling." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T22:55:22.887", "Id": "53865", "Score": "1", "body": "If `new` throws an exception (and it is not caught like the code) in the constructor then the object is never created and does not exist so there is not state to be inconsistent with." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T21:19:01.783", "Id": "53993", "Score": "0", "body": "@LokiAstari, you’re right; I’ve edited my response." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T00:54:34.677", "Id": "33559", "ParentId": "33555", "Score": "3" } }, { "body": "<p><s>When dealing with length, prefer <a href=\"http://en.cppreference.com/w/cpp/types/size_t\" rel=\"nofollow noreferrer\"><code>std::size_t</code></a>. This is an unsigned integer type that is also the return type of the <code>sizeof</code> operator. It is not good to use <code>int</code> because you cannot guarantee that any length will fit. Your code will break if the user constructs an object that is too large. There's also <a href=\"https://stackoverflow.com/questions/3259413/should-you-always-use-int-for-numbers-in-c-even-if-they-are-non-negative/3261019#3261019\">this issue</a>. Accordingly, your loop counter type throughout the class should be <code>std::size_t</code>.</s></p>\n\n<p><strong>CORRECTION:</strong> @LokiAstari has pointed out that <em>this is now wrong</em>, according to Bjarne Stroustrup (the creator of C++) and other top C++ experts.</p>\n\n<p>The main consensuses here are that:</p>\n\n<ul>\n<li>mismatching <code>signed</code>/<code>unsigned</code> is a source of bugs</li>\n<li>prefer <code>signed</code> unless the extra bit is needed for larger values</li>\n<li>the STL was wrong about this all along</li>\n</ul>\n\n<p>More information can be found here:</p>\n\n<ul>\n<li><a href=\"http://channel9.msdn.com/Events/GoingNative/2013\" rel=\"nofollow noreferrer\">Going Native</a></li>\n<li><a href=\"http://channel9.msdn.com/Events/GoingNative/2013/Interactive-Panel-Ask-Us-Anything\" rel=\"nofollow noreferrer\">Interactive Panel: Ask Us Anything</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T23:00:00.860", "Id": "53866", "Score": "1", "body": "Until very recently I also applied the above rule in my code (because I got it from the behavior of the standard library). But while at \"[Going Native](http://channel9.msdn.com/Events/GoingNative/2013)\" all the big guys in the C++ community said that it was a bad idea. You should use signed types for everything (apart for ints that you are using to hold bit flags). They basically said that the got it wrong when designing the standard library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T23:00:40.817", "Id": "53867", "Score": "1", "body": "See: Bjorn describe the issue and then Herb apologize about the standard: See: http://channel9.msdn.com/Events/GoingNative/2013/Interactive-Panel-Ask-Us-Anything" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T23:08:22.053", "Id": "53869", "Score": "0", "body": "@LokiAstari: So *this* must be yet another reason being my computer architecture professor's words..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T23:14:37.300", "Id": "53870", "Score": "0", "body": "Personally I can't say its bad advice. I still adjusting to the what was said at the conference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T23:17:17.190", "Id": "53871", "Score": "0", "body": "@LokiAstari: I hope this doesn't automatically invalidate too many of my answers (including this one). Now, did they say anything about `std::size_type`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T20:36:25.413", "Id": "53991", "Score": "0", "body": "@LokiAstari, would you mind summarizing the argument made against unsigned types ? (I wonder what the Latin is for “Argument by pointing to an untranscribed 80 minute video\" ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T20:58:12.540", "Id": "53992", "Score": "0", "body": "@microtherion: In the meantime, I've contacted my professor for his take on this. I too would really like to know the reasoning behind this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T02:43:38.957", "Id": "53998", "Score": "0", "body": "@microtherion: I have been playing by Jamal's argument that you should use unsigned types for a while. So it is still a kicker in the pants for me (and I am still trying to contemplate it a lot as well). It is worth watching the whole video anyway. But I will try and write a blog argument on the article in the next week. Ping me here next week if I have not gotten around to it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T03:05:44.490", "Id": "54001", "Score": "1", "body": "@microtherion: The general discussion on ints tarts at 41:05 The specific bit about unsigned starts at 42:54 Herb starts his apology at 44:25 and wraps up at 46:00. The basic argument is that mixing signed/unsigned introduces errors. But the two problems it (using unsigned) tries to solve don't really exist. Example: `setSize(unsigned int s)` Now call it like this: `setSize(-1);` Works perfectly well but probably does not do what you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T03:13:48.847", "Id": "54002", "Score": "0", "body": "@LokiAstari: *The basic argument is that mixing signed/unsigned introduces errors*. Is this worse than standard mismatch warnings (the ones commonly found in a for-loop)? I'm still trying to watch that part, but the buffering is taking a while." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T03:19:46.113", "Id": "54003", "Score": "1", "body": "(and I think we should take this to chat)" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T02:53:52.823", "Id": "33560", "ParentId": "33555", "Score": "2" } } ]
{ "AcceptedAnswerId": "33556", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T00:09:31.057", "Id": "33555", "Score": "2", "Tags": [ "c++", "strings", "constructor" ], "Title": "Review of three constructors for a String class" }
33555
<p>I have implemented a DOM parser. I would like any comments for optimizing, improving, and making the code coherent to best coding practices.</p> <pre><code>final class Node { private final String nodeName; private final String nodeValue; private final NodeTypeEnum nodeType; private final Map&lt;String, String&gt; attributeMap; private List&lt;Node&gt; childNodeList; public Node(String nodeName, String nodeValue, NodeTypeEnum nodeType) { this(nodeName, nodeValue, nodeType, new HashMap&lt;String, String&gt;()); } public Node(String nodeName, String nodeValue, NodeTypeEnum nodeType, Map&lt;String, String&gt; attributeMap) { if (nodeType == null) { throw new NullPointerException("Node type cannot be null."); } if (attributeMap == null) { throw new NullPointerException(); } this.nodeName = nodeName; this.nodeValue = nodeValue; this.nodeType = nodeType; this.attributeMap = attributeMap; } // basically a Tag public String getNodeName() { return nodeName; } // the value of element ie between the ankle brackets. public String getNodeValue() { return nodeValue; } // node type: now thinkong if this needs public NodeTypeEnum getNodeType() { return nodeType; } public String getAttribute(String name) { return attributeMap.get(name); } public List&lt;Node&gt; getChildNodes() { return childNodeList; } /** * Returns only elements-nodes, not the text-nodes */ public List&lt;Node&gt; getElementsByTagName(String tagName) { final List&lt;Node&gt; listNode = new ArrayList&lt;Node&gt;(); populateElementsByTagName(getChildNodes().iterator(), tagName, listNode); return listNode; } private void populateElementsByTagName(Iterator&lt;Node&gt; itr, String tagName, List&lt;Node&gt; listNode) { assert itr != null; assert tagName != null; assert listNode != null; // tags with same name are on the same level thus if-else is a good optimization. while (itr.hasNext()) { final Node node = itr.next(); /** * http://stackoverflow.com/questions/629029/using-getters-within-class-methods/629038#629038 */ if (node.getNodeType() == NodeTypeEnum.TEXT_NODE) continue; if (node.getNodeName().equals(tagName)) { listNode.add(node); } else { populateElementsByTagName(node.getChildNodes().iterator(), tagName, listNode); } } } public String getTextContent() { return populateTextContext(getChildNodes().iterator()).toString(); } private StringBuilder populateTextContext(Iterator&lt;Node&gt; itr) { final StringBuilder sb = new StringBuilder(); while (itr.hasNext()) { Node n = itr.next(); if (n.nodeType == NodeTypeEnum.TEXT_NODE) { sb.append(n.nodeValue + "\n"); } else { sb.append(populateTextContext(n.getChildNodes().iterator()).toString()); } } return sb; } public void setChildNodeList(List&lt;Node&gt; childNodeList) { this.childNodeList = childNodeList; } } public class DOMScratch { private final String filePath; private Node root; public DOMScratch(String filePath) { if (filePath == null) { throw new NullPointerException("File path cannot be null"); } this.filePath = filePath; } // we want to throw IO exception, and not continue further processing. public void pareXMLDoc() throws IOException { BufferedReader br = null; try { br = new BufferedReader(new FileReader(filePath)); root = readAndParse(br).get(0); } finally { br.close(); } } /** * In essence a DFSish algo. */ private List&lt;Node&gt; readAndParse(BufferedReader br) throws IOException { final List&lt;Node&gt; nodeList = new ArrayList&lt;Node&gt;(); String line = null; while ((line = br.readLine()) != null) { final Node node = parseLine(line); if (node == null) { return nodeList; } // last tag encountered. nodeList.add(node); if (node.getChildNodes() != null) { continue; } // all textnodes, which are child of an element should be at same level. node.setChildNodeList(readAndParse(br)); // is this better design ? } return nodeList; } private Node parseLine(String line) throws IOException { assert line != null; String trimmedLine = line.trim(); char[] ch = trimmedLine.toCharArray(); if (ch[1] == '/') {return null; } // &lt;City coast=East&gt;NewYorkCity&lt;/City&gt; String[] subElement = line.split("&lt;"); // str[1] = City&gt;SanDiego, and str[2] = /City&gt; which is to be discarded. /** * subElement[1] = City coast=East&gt;NewYork * subElement[2] = /City&gt; */ String[] tagAttributeText = subElement[1].split("&gt;"); /** * tagAndAttributeMap[0] = City coast="East" * tagAndAttributeMap[1] = NewYork */ String[] tagAttribute = tagAttributeText[0].split(" "); /** * tagAttribute[0] = City * tagAttribute[1] = coast="East" */ final Map&lt;String, String&gt; attributeMap = new HashMap&lt;String, String&gt;(); Node node; if (tagAttribute.length &gt; 1) { String[] keyValue = tagAttribute[1].split("="); attributeMap.put(keyValue[0], keyValue[1]); node = new Node(tagAttribute[0], null, NodeTypeEnum.ELEMENT_NODE, attributeMap); } else { node = new Node(tagAttribute[0], null, NodeTypeEnum.ELEMENT_NODE); } if (tagAttributeText.length &gt; 1) { List&lt;Node&gt; nodeList = new ArrayList&lt;Node&gt;(); nodeList.add(new Node(null, tagAttributeText[1], NodeTypeEnum.TEXT_NODE)); node.setChildNodeList(nodeList); } return node; } public Node getRootElement() { return root; } public static void main(String[] args) { DOMScratch dom = new DOMScratch("/Users/ameya.patil/Desktop/xml.txt"); try { dom.pareXMLDoc(); } catch (IOException e) { e.printStackTrace(); } Node node = dom.getRootElement(); System.out.println(node.getNodeName()); System.out.print(node.getTextContent()); System.out.println(node.getAttribute("rank")); List&lt;Node&gt; nodeList = node.getElementsByTagName("NewYork"); for (Node nl : nodeList) { System.out.println(nl.getElementsByTagName("City").get(0).getTextContent()); } } } </code></pre>
[]
[ { "body": "<p>You've tagged it \"XML\" so I suppose your intent is to parse anything that conforms to XML 1.0? If not, you should say what language you are intending to parse. At the moment, you're not remotely close to parsing general XML, for example you'll fail to handle \"&lt;\" in a CDATA section or comment, or \" \" within an attribute value.</p>\n\n<p>Frankly, it looks to me as if you have no knowledge at all of parser writing, and are trying to work it out from first principles. The result looks rather like my first attempt to build a brick wall, that is to say, a total bodge. I would strongly suggest you get some basic computer science textbooks and read them, or enrol on a suitable course.</p>\n\n<p>Sorry to be so brutal. Asking for criticism is the first sign of a good programmer, so you'll get there in the end.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T08:09:25.090", "Id": "33568", "ParentId": "33558", "Score": "3" } }, { "body": "<p>Do not put the word Enum in an enum type name. NodeTypeEnum should be just <code>NodeType</code>. The constants of that enum should not have NODE in their names; the class name already implies that each constant represents a type of node.</p>\n\n<p>Javadoc is for packages, classes, methods and fields. Multi-line comments inside code should start with <code>/*</code>, not <code>/**</code>.</p>\n\n<p>There are StringBuilder.append methods for all reference and primitive types. Calling <code>toString()</code> on an object before passing it to StringBuilder.append is redundant, regardless of the object's type.</p>\n\n<p>Unless you specifically want the library to work with Java versions older than Java 7, use <code>try (BufferedReader br = new BufferedReader(…))</code> so <code>br</code> is closed automatically and safely. Your pareXMLDoc [sic] method, as written, would throw a NullPointerException if the file were not found, because <code>br</code> would still be null. The try-with-resources syntax is the easy way to remove any such concerns.</p>\n\n<p>I realize your <code>main</code> method is just for testing, but ignoring the IOException is not helpful. If a document can't be parsed, you don't want to continue, you want to stop. Either wrap the IOException in a RuntimeException, or declare <code>main</code> with <code>throws IOException</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T14:51:21.123", "Id": "33740", "ParentId": "33558", "Score": "2" } } ]
{ "AcceptedAnswerId": "33740", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T00:49:36.427", "Id": "33558", "Score": "2", "Tags": [ "java", "parsing", "xml", "dom" ], "Title": "DOM parser implemented from scratch" }
33558
<p><code>dem_rows</code> and <code>dem_cols</code> contain float values for a number of things i can identify in an image, but I need to get the nearest pixel for each of them, and than to make sure I only get the unique points, and no duplicates. </p> <p>The problem is that this code is ugly and as far as I get it, as unpythonic as it gets. If there would be a pure-numpy-solution (without for-loops) that would be even better. </p> <pre><code># next part is to make sure that we get the rounding done correctly, and than to get the integer part out of it # without the annoying floatingpoint-error, and without duplicates fielddic={} for i in range(len(dem_rows)): # here comes the ugly part: abusing the fact that i overwrite dictionary keys if I get duplicates fielddic[int(round(dem_rows[i]) + 0.1), int(round(dem_cols[i]) + 0.1)] = None # also very ugly: to make two arrays of integers out of the first and second part of the keys field_rows = numpy.zeros((len(fielddic.keys())), int) field_cols = numpy.zeros((len(fielddic.keys())), int) for i, (r, c) in enumerate(fielddic.keys()): field_rows[i] = r field_cols[i] = c </code></pre>
[]
[ { "body": "<p>I'm not sure what you are doing, exactly, but looping over <code>range(len(...))</code> is never very pythonic. Since you only use the index to look up values, you should just take the pairs using <code>zip</code>.</p>\n\n<p>Also, that <code>round() + 0.1</code> thing is unnecessary. Floats represent all integers in their accurate area exactly. If you are outside the accurate area (i.e. an exponent larger than the number of mantissa bits), that addition will not change the value of the float either. Thus, you can simply cast the result of <code>round()</code> to an integer.</p>\n\n<p>If you need to take the unique items of something, the best way is to not use a dict, but a set.</p>\n\n<pre><code>int_rows = map(lambda x: int(round(x)), dem_rows)\nint_cols = map(lambda x: int(round(x)), dem_cols)\ns = set(zip(int_rows, int_cols))\n</code></pre>\n\n<p>Then iterate over the set, or unzip it into two sequences for constructing the arrays.</p>\n\n<p>Note: In python 2.x map and zip create lists, so you may want to use itertools.izip and imap. In python 3.x they are fine as is.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T09:35:17.970", "Id": "53758", "Score": "0", "body": "but i cant cast round() to an array, so i am still stuck with an ugly loop there- since dem_rows are floats and if i take the set of the zip, i just end up with the same thing, and i want to get rid of the for-loops)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T09:38:28.520", "Id": "53759", "Score": "0", "body": "You can map the elements to ints, I'll update the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T09:48:45.783", "Id": "53760", "Score": "0", "body": "and than how would it be best to iterate over the set or unzip and reconstruct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T09:54:23.217", "Id": "53761", "Score": "0", "body": "You can turn it back into two sequences using `u_rows, u_cols = zip(*s)`. I'm not sure if you can pass those directly to numpy's array constructors or if you need to use `tuple()` first in python 3.x where zip returns iterators." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T09:55:51.807", "Id": "53762", "Score": "0", "body": "i am using 2.7 still" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T09:57:43.267", "Id": "53763", "Score": "0", "body": "In that case you can simply use `zip` there, since it creates tuples. Although you may want to test with `itertools.izip` first, as that may be faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T11:35:41.683", "Id": "53764", "Score": "0", "body": "I have found an even better way i think to do the casting to integers, with numpy (i edited it into my question). Though i selected your answer since you pointed me in the direction of zip-set-unzip" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T09:20:42.743", "Id": "33563", "ParentId": "33562", "Score": "3" } }, { "body": "<p>This is very unpythonic, however very common for Python newbies</p>\n\n<pre><code> for i in range(len(something)):\n do_someting_with(i) \n</code></pre>\n\n<p>You can iterate over items in the following way:</p>\n\n<pre><code>for item in something:\n do_something_with(item)\n</code></pre>\n\n<p>or if you need also the index:</p>\n\n<pre><code>for idx, item in enumerate(something):\n do_something_with(item)\n do_something_with_idx(idx)\n</code></pre>\n\n<p>If you expect a list to comeout you can use list comperhansiom:</p>\n\n<pre><code>result = [ do_someting_with(item) for item in something ]\n</code></pre>\n\n<p>Or you can use some functional programming style:</p>\n\n<pre><code>result = map( do_someting_with, something ) \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T09:51:41.260", "Id": "33564", "ParentId": "33562", "Score": "1" } }, { "body": "<p>Ok, i think i have found the best solution myself, with a little help from Otus, for the zip-set-unzip part, though i think my way of getting it to integers is more pythonic?</p>\n\n<pre><code>r1 = numpy.array(numpy.round(dem_rows), int)\nc1 = numpy.array(numpy.round(dem_cols), int)\nfield_rows, field_cols = zip(*set(zip(r1, c1)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-13T08:32:29.370", "Id": "203871", "Score": "0", "body": "This solution was copied from Rev 1 of the question. If @usethedeathstar would repost this as a self-answer, then we can remove this post." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-13T08:30:54.710", "Id": "110646", "ParentId": "33562", "Score": "0" } } ]
{ "AcceptedAnswerId": "33563", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T09:03:44.483", "Id": "33562", "Score": "3", "Tags": [ "python", "image", "numpy", "floating-point" ], "Title": "Distinct nearest pixels for floating-point coordinates" }
33562
<p>I am solving <a href="http://www.spoj.com/problems/ADV04B1" rel="nofollow">this problem</a> on SPOJ Upper Right King (Hard):</p> <blockquote> <p>There is a king in the lower left corner of the \$ n \times n \$ chess board. The king can move one step right, one step up or one step up-right. How many ways are there for him to reach the upper right corner of the board? Give the answer modulo 1000003.</p> </blockquote> <p>The numbers to be output are the <a href="http://en.wikipedia.org/wiki/Delannoy_number#Central_Delannoy_numbers" rel="nofollow">central Delannoy numbers</a>.</p> <p>I've written a solution in Python with a time complexity of \$ O(n(\log m)^2) \$. But it's showing "time limit exceeded". Can anyone help me out with this?</p> <pre><code>import math MAX = 10000002 MOD = 1000003 # Extended euclidean algorithm for modular inverse def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: return 0 else: return x % m t = raw_input() t = long(t) fact = [] for i in range(0,MAX): fact.append(0) fact[0]=1 fact[1]=1 for i in range(2,MAX): fact[i] = (i%MOD * fact[i-1]%MOD)%MOD while t: n = raw_input() n = long(n) n = n-1 Sum = 1 prod = ((n+1)%MOD * (n)%MOD)%MOD increment = n+1 decrement = n Sum = (Sum%MOD + prod%MOD)%MOD for k in range(0,n-1): temp_prod = (prod%MOD * (increment+1)%MOD * (decrement-1)%MOD)%MOD prod = temp_prod fct = fact[k+2] fat2 = (fct%MOD * fct%MOD)%MOD # print fat2,modinv(fat2,MOD) result = (temp_prod%MOD * modinv(fat2,MOD))%MOD Sum = (Sum%MOD + result%MOD)%MOD increment = increment + 1 decrement = decrement - 1 print "%ld" %(Sum) t = t-1 </code></pre> <p>How can I reduce the complexity of this problem in order to have it accepted?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T14:00:58.900", "Id": "53790", "Score": "0", "body": "[See this code](http://oeis.org/A001850/a001850.py.txt) by Nick Hobson." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T06:26:37.037", "Id": "53886", "Score": "0", "body": "The above code won't work for large constraints mentioned in problem statement. any ways, i got it accepted after so many optimizations.thanks for your time." } ]
[ { "body": "<h2>Flatten your method body</h2>\n\n<pre><code>def egcd(a, b):\n if a == 0:\n return (b, 0, 1)\n else:\n g, y, x = egcd(b % a, a)\n return (g, x - (b // a) * y, y)\n</code></pre>\n\n<p>can be re-written as:</p>\n\n<pre><code>def egcd(a, b):\n if a == 0:\n return (b, 0, 1)\n g, y, x = egcd(b % a, a)\n return (g, x - (b // a) * y, y)\n</code></pre>\n\n<p>because returning halts the function.</p>\n\n<h2>Use in-line 'ternary' to reduce verbosity</h2>\n\n<pre><code>def modinv(a, m):\n g, x, y = egcd(a, m)\n if g != 1:\n return 0\n else:\n return x % m\n</code></pre>\n\n<p>should become</p>\n\n<pre><code>def modinv(a, m):\n g, x, y = egcd(a, m)\n return 0 if g != 1 else x % m\n</code></pre>\n\n<h2>Say something meaningful when asking for input</h2>\n\n<pre><code>t = raw_input()\n</code></pre>\n\n<p>The user sees nothing, only an hanging interpreter.</p>\n\n<h2>Use a main function</h2>\n\n<ol>\n<li>Python code runs faster in functions</li>\n<li>You can use an if <strong>name</strong> ... block to avoid execution when the module is imported.</li>\n</ol>\n\n<h2>Convert directly (minor)</h2>\n\n<p>Do not waste lines:</p>\n\n<pre><code>n = raw_input()\nn = long(n)\n</code></pre>\n\n<p>should become</p>\n\n<p>n = long(raw_input()) # &lt;- also add a meaningful prompt</p>\n\n<h2>Follow naming conventions (minor)</h2>\n\n<p>You follow the naming conventions pretty well, just one imprecision:</p>\n\n<pre><code>Sum = 1\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>sum = 1\n</code></pre>\n\n<h2>Use proper spacing (minor)</h2>\n\n<p>For example this line:</p>\n\n<pre><code>prod = ((n+1)%MOD * (n)%MOD)%MOD\n</code></pre>\n\n<p>is hard to read because all the symbols are squashed together.</p>\n\n<h2>Modularize more (important)</h2>\n\n<p>You defined two functions, that is very good, but you could do more to reduce the 35 lines of top level imperative code that is too much.</p>\n\n<p>Usually each function (including <code>main</code>) should be no more than 10-15 lines of code.</p>\n\n<h2>Use doctests to for automatic testing</h2>\n\n<p>In Math code, automatically testing your functions each time you run the programme can be invaluable, just use something like:</p>\n\n<pre><code>import doctest\n\ndef egcd(a, b):\n \"\"\"\n Meaningful description here...\n\n &gt;&gt;&gt; egcd(4132, 434)\n (2, -48, 457)\n \"\"\"\n\n if a == 0:\n return (b, 0, 1)\n\n g, y, x = egcd(b % a, a)\n return (g, x - (b // a) * y, y)\n\n\n\ndoctest.testmod()\n</code></pre>\n\n<p>and the code will be tested automatically.</p>\n\n<h2>Tell why</h2>\n\n<p>I can see many calculations in your code, but why? Following which algorithm, please write this inside the docstrings of your functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-14T17:09:35.767", "Id": "156829", "Score": "0", "body": "A couple of points: 1. Adding a prompt is wrong here: [SPOJ makes strict requirements](http://www.spoj.com/problems/ADV04B1/) on the program's output, so adding the prompt will cause the program to fail. 2. \"Python code runs faster in functions\" needs an explanation, and anyway it's only true of CPython, and for this problem we'll probably use PyPy instead." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-12T18:12:07.493", "Id": "86678", "ParentId": "33575", "Score": "2" } }, { "body": "<h3>1. Review</h3>\n\n<p>I won't do a detailed review of your code, because as you'll see this answer is quite long enough already, but I'll just note that I found it very hard to figure out what it was doing. I think that the formula you are using is $$ D(n) = \\sum_{0 ≤ k ≤ n} { n \\choose k } { n + k \\choose k} = \\sum_{0 ≤ k ≤ n} { (n + k)(n + k - 1)\\dotsm(n - k + 1) \\over (k!)^2 }. $$ But this is not remotely obvious from the code. A few comments would have made a big difference to the understandability.</p>\n\n<h3>2. A better algorithm</h3>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/Delannoy_number#Central_Delannoy_numbers\" rel=\"nofollow\">Wikipedia article</a> on the central Delannoy numbers gives a three-term recurrence relationship: $$ nD(n) = 3(2n - 1)D(n - 1) - (n - 1)D(n - 2). $$ The means that it's easy to write a function that efficiently generates the numbers:</p>\n\n<pre><code>from itertools import count\n\ndef delannoy():\n \"\"\"Generate the central Delannoy numbers.\"\"\"\n x, y = 1, 3\n for n in count(2):\n yield x\n x, y = y, (((6 * n - 3) * y - (n - 1) * x) // n)\n</code></pre>\n\n<p>However, for the SPOJ problem we need the numbers modulo \\$ m = 1000003 \\$, and to do this we need to be able to do division modulo \\$ m \\$, which requires finding the <a href=\"https://en.wikipedia.org/wiki/Modular_multiplicative_inverse\" rel=\"nofollow\">multiplicative inverse</a> of \\$ n \\$ modulo \\$ m \\$. The fastest way to do this is via the <a href=\"https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm\" rel=\"nofollow\">extended Euclidean algorithm</a>, and I see that you used the <a href=\"https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm#Python\" rel=\"nofollow\">implementation from the \"Algorithm Implementation\" wikibook</a>. That leads to this solution:</p>\n\n<pre><code>from itertools import count, islice\n\ndef egcd(a, b):\n \"\"\"Return g, x, y, where g is is greatest common divisor of a and b,\n and x and y are integers such that ax + by = 1.\n\n \"\"\"\n if a == 0:\n return (b, 0, 1)\n else:\n g, y, x = egcd(b % a, a)\n return (g, x - (b // a) * y, y)\n\ndef modinv(a, m):\n \"\"\"Return the multiplicative inverse of a modulo m, if it exists.\"\"\"\n gcd, x, y = egcd(a, m)\n if gcd != 1:\n raise ValueError(\"no inverse of {} modulo {}\".format(a, m))\n else:\n return x % m\n\ndef delannoy(m):\n \"\"\"Generate the central Delannoy numbers modulo m.\"\"\"\n x, y = 1, 3\n for n in count(2):\n yield x\n x, y = y, (((6 * n - 3) * y - (n - 1) * x) * modinv(n, m)) % m\n\ndef main():\n d = list(islice(delannoy(1000003), 1000000))\n T = int(input())\n for _ in range(T):\n n = int(input())\n print(d[n - 1])\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Unfortunately this is not fast enough: with the biggest possible test case (\\$ T = 10000 \\$), this takes about 1.9 seconds on my machine under PyPy, and the time limit at SPOJ is 1.183 seconds.</p>\n\n<p>The only place where we can clearly save time is in the computation of the modular inverses. There are several observations that will help here:</p>\n\n<ol>\n<li><p>We need inverses modulo \\$ m \\$ for all \\$ 1 ≤ i ≤ n \\$, so we might as well compute them all at once.</p></li>\n<li><p>Function calls are quite expensive in Python, so we should switch to the iterative version of the extended Euclidean algorithm, and inline it.</p></li>\n<li><p>It happens to be the case that \\$ m = 1000003\\$ is prime, so we know that <code>modinv(a, m)</code> will always succeed for \\$ a &lt; m \\$. So the computation of the GCD and the associated test can be omitted.</p></li>\n<li><p>We can avoid computation of three-quarters of the modular inverses. That's because if we have computed \\$ i^{-1} ≡ j \\mod m \\$ then we immediately know $$ \\eqalign{ j^{-1} &amp;≡ i &amp;\\pmod m \\\\ (-i)^{-1} &amp;≡ -j &amp;\\pmod m \\\\ (-j)^{-1} &amp;≡ -i &amp;\\pmod m } $$ too.</p></li>\n</ol>\n\n<p>Applying all of these improvements leads to this implementation:</p>\n\n<pre><code>from itertools import count, islice\n\ndef invmod(p):\n \"\"\"Return a list of inverses modulo the prime number p.\"\"\"\n # Cache function to avoid global lookup\n _divmod = divmod\n inv = [0] * p\n for i in range(1, p // 2 + 1):\n if inv[i]:\n continue\n\n # Specialization of Extended Euclidean algorithm for the case\n # where we know that p is prime and i &lt; p, so the GCD is 1.\n j, k, a, b = 0, 1, p, i\n while b:\n a, (q, b) = b, _divmod(a, b)\n j, k = k, j - q * k\n\n # Having found that j is the inverse of i, we immediately know\n # the inverses of j, -i and -j.\n inv[i] = j\n inv[j] = i\n inv[-i] = -j\n inv[-j] = -i\n return inv\n\ndef delannoy(n, m):\n \"\"\"Return a list of the first n central Delannoy numbers, modulo m.\"\"\"\n inv = invmod(m)\n def d():\n x, y = 1, 3\n for i in count(2):\n yield x\n x, y = y, (((6 * i - 3) * y - (i - 1) * x) * inv[i]) % m\n return list(islice(d(), n))\n\ndef main():\n d = delannoy(1000000, 1000003)\n T = int(input())\n for _ in range(T):\n n = int(input())\n print(d[n - 1])\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>And this runs in just over 1 second under PyPy, so it's good to go.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-12T18:23:01.327", "Id": "86681", "ParentId": "33575", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T11:26:48.763", "Id": "33575", "Score": "6", "Tags": [ "python", "mathematics", "combinatorics", "time-limit-exceeded", "chess" ], "Title": "Central Delannoy numbers" }
33575
<p>Trying to write a substring function in Clojure. I am sure there is a more idiomatic way. Can anyone enlighten me? </p> <p>Otherwise, here is my version. Thoughts?</p> <pre><code>(defn substring? "is 'sub' in 'str'?" [sub str] (if (not= (.indexOf str sub) -1) true false)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T13:01:06.020", "Id": "53783", "Score": "0", "body": "hmmm...just discovered - (.contains \"abcdefghi\" \"abc\"), anyway that doesn't interop with Java (purely out of curiosity!)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T00:24:00.857", "Id": "53874", "Score": "1", "body": "a `re-find` might be the simplest way. The old `contrib.string` used `.contains` as well so it was probably the best tool for the job." } ]
[ { "body": "<p>As you wrote in your comments, (.contains \"str\" \"sub\") is perfectly fine. it is indeed java interop - it runs the method contains on String object \"str\".</p>\n\n<p>two more comments, first, passing str as a var name isnt so good, since str is a function, so you should consider giving it a different name. Second, in your implementation, its quite redundant to write</p>\n\n<pre><code>(defn substring? [sub st]\n (if (not= (.indexOf st sub) -1) \n true \n false))\n</code></pre>\n\n<p>You could simply write </p>\n\n<pre><code>(defn substring? [sub st]\n (not= (.indexOf st sub) -1))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T22:46:12.497", "Id": "35141", "ParentId": "33577", "Score": "10" } } ]
{ "AcceptedAnswerId": "35141", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T12:33:55.770", "Id": "33577", "Score": "9", "Tags": [ "strings", "clojure" ], "Title": "Clojure - substring? function" }
33577
<p>I'm using <a href="http://www.websupergoo.com/abcpdf-1.htm" rel="nofollow noreferrer">ABCPDF</a> (Version 8) to update an existing PDF document and I believe its API is hurting me in this situation and was curious whether anyone had any comments on how this looks as it appears ugly to me.</p> <p>The situation: I am replacing pages in PDF documents that are all generated by an in-house process so I can rely on their format being consistent and the following code is tasked with updating annotation links on the Table of Contents page(s) to point to the replace pages instead of the old pages. Since there can be multiple replacement operations, I decided to put the collection of these link annotations into a dictionary instead of looping through all of them for each replacement operation.</p> <p>As my comments in the code mention, I only was able to piece this together by debugging a lot and examining the properties of different ABCPDF objects.</p> <p>Here's the relevant code:</p> <pre><code>//use less than or equal to here because a one page TOC will have a matching start and end page number private Dictionary&lt;int, Action&lt;int&gt;&gt; _linkUpdates; WebSuperGoo.ABCPDF8.Doc pdfDoc; for (var pageNumber = startPageNumber; pageNumber &lt;= endPageNumber; pageNumber++) { pdfDoc.PageNumber = pageNumber; var annotCount = pdfDoc.GetInfoInt(pdfDoc.Page, "Annot Count"); //this is really ugly code that looks for link annotations (i.e. links in the TOC) that reference our old page Id //it depends on some nasty PDF data structures in ABCPDF and assumes they will always appear the same way //it took me a few hours of debugging to figure out how to get at this stuff and modify it, not pleasant for (var i = 1; i &lt;= annotCount; i++) { //if at any level we come up empty, just get out of this annotation and try the next one var annotId = pdfDoc.GetInfoInt(pdfDoc.Page, string.Format("Annot {0}", i)); var annotationMaster = (Annotation)pdfDoc.ObjectSoup[annotId]; if (annotationMaster.SubType != "Link") { continue; } var annotItem = annotationMaster.Resolve(Atom.GetItem(annotationMaster.Atom, 0)) as DictAtom; if (annotItem == null) { continue; } var destination = annotItem["D"] as ArrayAtom; if (destination == null) { continue; } var destinationPage = destination[0] as RefAtom; if (destinationPage == null) { continue; } _linkUpdates.Add(destinationPage.ID, updatedPageId =&gt; { destinationPage.ID = updatedPageId; Atom.SetItem(destination, 0, destinationPage); } ); } } </code></pre> <p>I included the declarations of <code>_linkUpdates</code> and <code>doc</code> for reference. So after I have this collection populated, when I have an update to make, I can simply do this:</p> <pre><code>if (_linkUpdates.ContainsKey(oldPageId)) { _linkUpdates[oldPageId](newPageId); } </code></pre> <p>I fully understand that this logic is heavily dependent on an understanding of how ABCPDF works, but since there's a fairly active community on <a href="https://stackoverflow.com/questions/tagged/abcpdf">SO</a>, I figured this might get some responses, perhaps from somebody who knows of an easier way of getting at/updating these link annotations.</p> <p>So, to summarize the areas I am interested in feedback on are:</p> <ol> <li>The prevalence of continues in my inner for loop</li> <li>The choice of using a dictionary with an Action value to update the related ABCPDF object</li> </ol> <p>This does work fine, and I am operating in an environment where I will have at most 70 possible link annotations to consider.</p>
[]
[ { "body": "<p>Could you you create your own <code>IEnumerable</code> that wraps all this up very well behind an interface?</p>\n\n<p>Then you can just do a <code>foreach</code> loop over the elements and not have to worry about the continues. </p>\n\n<p>It would iterate over <code>(Annotation)pdfDoc.ObjectSoup[annotId]</code>'s </p>\n\n<p>that is the way I would go about doing this.</p>\n\n<pre><code>public class Test : IEnumerable&lt;RefAtom&gt;\n{\n private readonly IEnumerator&lt;RefAtom&gt; _inner;\n\n public Test(pdfDocType annotations)\n {\n\n _inner = new inn(annotations);\n }\n\n IEnumerator&lt;RefAtom&gt; IEnumerable&lt;RefAtom&gt;.GetEnumerator()\n {\n return _inner;\n }\n\n public IEnumerator GetEnumerator()\n {\n return _inner;\n }\n\n private class inn : IEnumerator&lt;RefAtom&gt;\n {\n private pdfDocType _annotations;\n private RefAtom _current;\n private int _max;\n private int _count;\n public inn(pdfDocType annotations)\n {\n _max = annotations.GetInfoInt(annotations.Page, \"Annot Count\");\n _annotations = annotations;\n _count = 0;\n }\n\n public void Dispose(){}\n\n public bool MoveNext()\n {\n if (_max &gt; _count)\n {\n //do logic stuff\n //set current\n\n }\n return false;\n }\n\n public void Reset()\n {\n _count = 0;\n }\n\n public RefAtom Current { get; private set; }\n\n object IEnumerator.Current\n {\n get { return Current; }\n }\n }\n\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:09:42.183", "Id": "53832", "Score": "0", "body": "I'm not quite following you here, could you post a small code sample to illustrate what you mean?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:49:15.503", "Id": "53838", "Score": "0", "body": "Thanks for the update, that does make sense and would at least hide away the ugliness behind the IEnumerable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:50:25.050", "Id": "53841", "Score": "0", "body": "yeah I'm never a big fan of for statements, also you could even pass a func into the 'inn' class that does the calculation of determining if you can use it making this more usable for other applications" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:55:23.747", "Id": "53842", "Score": "1", "body": "If you want to create a custom `IEnumerable`, there is a much easier way than this: use `yield return`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T19:33:07.397", "Id": "53845", "Score": "0", "body": "@svick Can you elaborate on this some more I'm not sure I understand how yield will get you an IEnumerable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T19:36:03.133", "Id": "53846", "Score": "0", "body": "@CSgoose I don't understand, the whole point of `yield return` is to create an `IEnumerable` easily." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T19:45:34.000", "Id": "53847", "Score": "0", "body": "@svick you're right I guess you just don't need to inner IEnumerator class, guess I learned something today." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T12:30:35.513", "Id": "53897", "Score": "0", "body": "I've given it some thought and I think this solution best meets what I am looking for. If I had enough reputation on code exchange, I'd actually vote for it too..." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:24:32.817", "Id": "33595", "ParentId": "33579", "Score": "1" } }, { "body": "<p>If you do this often, you could write an extension method for <code>object</code> that takes a function, which is executed only when the input is not <code>null</code>. You could then use it in a fluent manner to navigate multiple times:</p>\n\n<pre><code>public static class Navigator\n{\n public static TOutput Navigate&lt;TInput, TOutput&gt;(\n this TInput input, Func&lt;TInput, TOutput&gt; navigationFunction)\n where TOutput : class\n {\n if (input == null)\n return null;\n\n return navigationFunction(input);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var destinationPage = \n (annotationMaster.Resolve(Atom.GetItem(annotationMaster.Atom, 0)) as DictAtom)\n .Navigate(annotItem =&gt; annotItem[\"D\"] as ArrayAtom)\n .Navigate(destination =&gt; destination[0] as RefAtom);\n\nif (destinationPage == null)\n continue;\n</code></pre>\n\n<p>Notice that I also removed the braces. This is a matter of personal opinion (and sometimes company policy), but I think that they're not always necessary, especially when the body of the condition is this simple.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:48:23.640", "Id": "53836", "Score": "0", "body": "I like this idea, although for this one-off scenario, might be overkill." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T21:05:51.037", "Id": "53852", "Score": "0", "body": "Just put it somewhere in your assembly and declare it `internal` instead of `public`. Or keep it public and find other uses for it. I think I'm going to steal it for my codebase - there's all kinds of situations where it'd be useful..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:57:53.167", "Id": "33609", "ParentId": "33579", "Score": "2" } } ]
{ "AcceptedAnswerId": "33595", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T13:25:34.497", "Id": "33579", "Score": "3", "Tags": [ "c#", "pdf" ], "Title": "Lots of Continues in an Inner Loop and Dictionary of Actions" }
33579
<pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;QR code generator&lt;/title&gt; &lt;style&gt; body { font-family: arial, sans-serif; } section { margin: 50px auto; max-width: 350px; text-align: center; } textarea { width: 100%; height: 50px; margin-bottom: 10px; } #size { max-width: 64px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;section&gt; &lt;h1&gt;QR code generator&lt;/h1&gt; &lt;p&gt;Enter an URL or some text bellow and hit the Generate button (&lt;kbd&gt;Ctrl&lt;/kbd&gt;+&lt;kbd&gt;Enter&lt;/kbd&gt;)!&lt;/p&gt; &lt;textarea id="textarea" autofocus&gt;&lt;/textarea&gt; &lt;label for="size"&gt;Size (px):&lt;/label&gt; &lt;input id="size" type="number" value="150" min="50" max="500" step="50"&gt; &lt;button onclick="genQRcode()"&gt;Generate&lt;/button&gt; &lt;div id="content" style="display: none;"&gt; &lt;p&gt;&lt;img id="qrcode" src="" /&gt;&lt;/p&gt; &lt;label for="qrcode-url"&gt;QR Code URL:&lt;/label&gt; &lt;input id="qrcode-url" type="text" onclick="this.select()"&gt; &lt;/div&gt; &lt;/section&gt; &lt;script&gt; var textarea = document.getElementById("textarea"), content = document.getElementById("content"); function genQRcode() { var data = encodeURIComponent(textarea.value), size = document.getElementById("size").value, chart = "http://chart.googleapis.com/chart?cht=qr&amp;chs=" + size + "x" + size + "&amp;choe=UTF-8&amp;chld=L|0&amp;chl=" + data; if (data === "") { alert("Please enter a valid data!"); textarea.focus(); content.style.display = "none"; } else { content.style.display = ""; document.getElementById("qrcode").src = chart; document.getElementById("qrcode-url").value = chart; } } document.addEventListener("keydown", function(e) { if (e.ctrlKey &amp;&amp; e.keyCode == 13) { genQRcode(); } }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:17:05.283", "Id": "53815", "Score": "0", "body": "Minor nit: \"bellow\" => \"below\". ;-)" } ]
[ { "body": "<p>This code looks fine to me.</p>\n\n<p>If you are interested in nitpicking then : </p>\n\n<ul>\n<li>Style information should be in a css file</li>\n<li>JavaScript should be in a js file</li>\n<li>Your image tag should have an alt</li>\n<li>It should show some indication that you are leveraging a Google API ?</li>\n<li>Assigning events like this <code>&lt;button onclick=\"genQRcode()\"&gt;</code> is obsolete</li>\n<li><code>Please enter a valid data</code> is not proper English ( \"Please enter valid data\" )</li>\n<li>You should consider adding the listener to the textarea, not the document</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T13:49:58.990", "Id": "53789", "Score": "0", "body": "Hi thanks for the answer. But why \"Please enter a valid data\" isn't proper English. can you correct this?\n*English isn't my primary language..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:16:18.950", "Id": "53814", "Score": "1", "body": "@udd: In English, \"data\" is plural. (Well [more or less](http://ell.stackexchange.com/questions/11356/sample-collection-params-vs-samples-collection-params/11357#11357).) It would probably be better to say what sort of data (URL, free text, etc.) you plan to encode. Also, you don't really validate the data beyond making sure it's not a zero-length string, so \"valid\" is a touch misleading. (But this is all on the nitpicking level. Well done.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T11:12:09.260", "Id": "53896", "Score": "0", "body": "@JonEricson, it would be more precise to say that *data* is either plural or uncountable. In modern usage it seems to be [uncountable more often than plural](http://en.wiktionary.org/wiki/data#Usage_notes)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T13:43:35.160", "Id": "33581", "ParentId": "33580", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T13:29:09.743", "Id": "33580", "Score": "2", "Tags": [ "javascript", "html" ], "Title": "QR Code generator" }
33580
<p>i am looking for a faster and more efficient way of this code. What the code does is simply compares message context of (user, application, service and operation) and compares it with some rules.</p> <pre><code>private boolean match(Context messageContext, ContextRule contextRule) { if(contextRule.getMessageContext().getUser().equals(ContextRuleEvaluator.WILDCARD) || (contextRule.getMessageContext().getUser().equals(messageContext.getUser()))) { if(contextRule.getMessageContext().getApplication().equals(ContextRuleEvaluator.WILDCARD) || (contextRule.getMessageContext().getApplication().equals(messageContext.getApplication()))) { if(contextRule.getMessageContext().getService().equals(ContextRuleEvaluator.WILDCARD) || (contextRule.getMessageContext().getService().equals(messageContext.getService()))) { if(contextRule.getMessageContext().getOperation().equals(ContextRuleEvaluator.WILDCARD) || (contextRule.getMessageContext().getOperation().equals(messageContext.getOperation()))) { return true; } } } } return false; } </code></pre> <p>Edit: Context and ContextRule are an interfaces </p> <pre><code>public interface Context { public String getUser(); public void setUser(String user); public String getApplication(); public void setApplication(String application); public String getService(); public void setService(String service); public String getOperation(); public void setOperation(String operation); } public interface ContextRule { public Context getMessageContext(); public int getAllowedConcurrentRequests(); } </code></pre> <p>Any suggestions appreciated :)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T15:22:38.433", "Id": "53799", "Score": "0", "body": "Please a little bit more information. What is `Context` and `ContextRule`. What doe all these functions return?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T15:32:23.937", "Id": "53800", "Score": "0", "body": "@Bobby as per your request i have edited the post" } ]
[ { "body": "<p>First of all, your formatting seems messy, please fix it.</p>\n\n<hr>\n\n<p>Did you rip it out or is there really zero documentation in there (JavaDoc)? Consider adding some, it will make your life and that of others easier.</p>\n\n<hr>\n\n<p>First step would be to add an overload to <code>match()</code> which accepts two strings, like this:</p>\n\n<pre><code>private boolean match(Context messageContext, ContextRule contextRule) {\n return match(contextRule.getMessageContext().getUser(), messageContext.getUser())\n &amp;&amp; match(contextRule.getMessageContext().getApplication(), messageContext.getApplication())\n &amp;&amp; match(contextRule.getMessageContext().getService(), messageContext.getService())\n &amp;&amp; match(contextRule.getMessageContext().getOperation(), messageContext.getOperation());\n}\n\nprivate boolean match(String value, String contextValue) {\n return value.equals(ContextRuleEvaluator.WILDCARD) || value.equals(contextValue);\n}\n</code></pre>\n\n<p>This makes it already <em>a lot</em> easier to read. Naming of the variables is a little bit suboptimal, that's because I could not come up with better names right now.</p>\n\n<hr>\n\n<p>Ultimately you should see if you can't extend and change <code>Context</code> to contain a <code>match()</code> function. This would require to change <code>Context</code> into an abstract class, so it might not be possible.</p>\n\n<pre><code>public abstract class Context {\n\n public abstract String getUser();\n\n public abstract void setUser(String user);\n\n public abstract String getApplication();\n\n public abstract void setApplication(String application);\n\n public abstract String getService();\n\n public abstract void setService(String service);\n\n public abstract String getOperation();\n\n public abstract void setOperation(String operation);\n\n /**\n * Matches this context against the given Context.\n *\n * @param context\n * @return\n */\n public boolean match(Context context) {\n return match(getUser(), context.getUser())\n &amp;&amp; match(getApplication(), context.getApplication())\n &amp;&amp; match(getService(), context.getService())\n &amp;&amp; match(getOperation(), context.getOperation());\n }\n\n private boolean match(String value, String otherValue) {\n return value.equals(ContextRuleEvaluator.WILDCARD) || value.equals(otherValue);\n }\n}\n</code></pre>\n\n<p>That would allow you to do this in your code:</p>\n\n<pre><code>return contextRule.getMessageContext().match(messageContext);\n</code></pre>\n\n<p>Which is very readable, even if you don't pack it into a function but call it directly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T16:20:52.660", "Id": "53805", "Score": "0", "body": "Yup no javadocs :(. Thank you for your suggestions anyway :) this seems to be better then current block" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T16:00:18.893", "Id": "33589", "ParentId": "33586", "Score": "5" } }, { "body": "<p>One way that you could clean up the comparisons is to look at using an object to represent each of the different checks that you need to make. See <code>com.google.common.collect.ComparisonChain</code> for a slightly different application of the same idea.</p>\n\n<p>Basic idea being that you have an interface that exposes each of your checks, returning an instance of itself. The interface also has a \"result\" method at the end, that returns true or false.</p>\n\n<p>Under the covers, you have two implementations of this object. One of them evaluates \"false\", and always returns a copy of itself. The other evaluates to \"true\", and returns itself if the comparison is true, and the other guy if the comparison is false.</p>\n\n<p>So your client code looks like</p>\n\n<pre><code>boolean result = MagicCompareThing.create()\n .match(lhs.getUser(),rhs.getUser())\n .match(lhs.getApplication(),rhs.getApplication())\n .match(lhs.getService(),rhs.getService())\n .match(lhs.getOperation(),rhs.getOperation())\n .result();\n</code></pre>\n\n<p>The strong resemblance to @Bobby's pattern is deliberate.</p>\n\n<pre><code>interface MagicCompareThing {\n boolean result();\n MagicCompareThing &lt;T&gt; match (T lhs, T rhs);\n\n static MagicCompareThing create() {\n return MagicCompareThing.TRUE;\n }\n\n private static final MagicCompareThing FALSE = new MagicCompareThing {\n boolean result () { return false; }\n MagicCompareThing &lt;T&gt; match(T lhs, T rhs) { return this; }\n } \n\n private static final MagicCompareThing TRUE = new MagicCompareThing {\n boolean result () { return true; }\n MagicCompareThing &lt;T&gt; match (T lhs, T rhs) {\n if ( ContextRuleEvaluator.WILDCARD.equals(lhs) ) {\n return this;\n }\n if (lhs.equals(rhs)) {\n return this;\n }\n return FALSE;\n }\n }\n}\n</code></pre>\n\n<p>Fundamentally, what this code is doing is noticing that the complicated ordering of comparisons is really just a state machine - false always transitions to itself, and true transitions both ways depending on the outcome of each comparison in turn.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T21:21:16.770", "Id": "53855", "Score": "1", "body": "Interesting concept. I've never seen such a comparison chain before (resembles the builder pattern a little), interesting." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T19:24:30.450", "Id": "33616", "ParentId": "33586", "Score": "4" } } ]
{ "AcceptedAnswerId": "33589", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T15:10:40.170", "Id": "33586", "Score": "2", "Tags": [ "java" ], "Title": "Multiple if conditions in one block - looking for faster and more efficient code" }
33586
<p>I am writing a simple image rotation script. Users press either the prev or next button to view the previous or next images. It works well, but the code looks over the top. Is there a way I can reduce the amount of code used?</p> <p><strong>index.php</strong></p> <pre><code>&lt;div id="container"&gt; &lt;img src="pic1" id="pic1" class="top-pic" alt="" /&gt; &lt;img src="pic2" id="pic2" alt="" /&gt; &lt;img src="pic3" id="pic3" alt="" /&gt; &lt;img src="pic4" id="pic4" alt="" /&gt; &lt;/div&gt; &lt;input type="button" name="prev" id="prev" value="prev" /&gt; &lt;input type="button" name="next" id="next" value="next" /&gt; </code></pre> <p><strong>jQuery</strong></p> <pre><code>$('#next').click(function(){ if($('#pic1').hasClass('top-pic')){ $('#pic1').removeClass('top-pic'); $('#pic2').addClass('top-pic'); }else if($('#pic2').hasClass('top-pic')){ $('#pic2').removeClass('top-pic'); $('#pic3').addClass('top-pic'); }else if($('#pic3').hasClass('top-pic')){ $('#pic3').removeClass('top-pic'); $('#pic4').addClass('top-pic'); }else if($('#pic4').hasClass('top-pic')){ $('#pic4').removeClass('top-pic'); $('#pic1').addClass('top-pic'); } }); $('#prev').click(function(){ if($('#pic1').hasClass('top-pic')){ $('#pic1').removeClass('top-pic'); $('#pic4').addClass('top-pic'); }else if($('#pic4').hasClass('top-pic')){ $('#pic4').removeClass('top-pic'); $('#pic3').addClass('top-pic'); }else if($('#pic3').hasClass('top-pic')){ $('#pic3').removeClass('top-pic'); $('#pic2').addClass('top-pic'); }else if($('#pic2').hasClass('top-pic')){ $('#pic2').removeClass('top-pic'); $('#pic1').addClass('top-pic'); } }); </code></pre>
[]
[ { "body": "<p>You need to abstract your code from the design, at the moment, adding another picture is going to yield !!!fun!!! (if I'm allowed to use my dwarven vocabulary). At the moment adding another picture would require that you copy and paste code and extend that if further. This is obviously not desirable.</p>\n\n<p>By keeping track of what picture is currently highlighted with a simple integer (for saving the index) you should be able to reduce all this. Warning, this is untested:</p>\n\n<pre><code>var idx = 1;\n\n$('#next').click(function(){\n nextPic(1); // Hightlight the next\n});\n\n$('#prev').click(function(){\n nextPic(-1); // Highlight the previous\n});\n\nfunction nextPic(var step) {\n var nextIdx = idx + step;\n if($('#pic' + nextIdx).length === 0) {\n // Check if the element does not exist.\n if(nextIdx &lt;= 0) {\n // If we are below or at zero, we need to wrap to the top.\n // So we count all imgs of the container.\n nextIdx = $('#container img').length;\n } else {\n // wrap around to the first.\n nextIdx = 1;\n }\n }\n\n $('#pic' + idx).removeClass('top-pic');\n $('#pic' + nextIdx).addClass('top-pic');\n\n idx = nextIdx;\n}\n</code></pre>\n\n<p>This way you don't even need to change the code if you add more pictures, and it should even work if you add or remove pictures on the fly (given you don't remove the currently selected one).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:56:14.527", "Id": "53824", "Score": "0", "body": "Argh, sorry. I -1'd because I (wrongly) thought I saw a bug, but got distracted by a phone call, and now my vote's locked. If you edit your question in any minor way, I think should be able to undo it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T21:18:03.943", "Id": "53854", "Score": "0", "body": "@Flambino: Done, and don't worry about it even if you can't undo it, those two points won't damage my reputation too much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T21:21:45.090", "Id": "53856", "Score": "0", "body": "And I've cancelled my downvote. Even if it's only two points, it's the principle of the thing :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T16:25:23.863", "Id": "33591", "ParentId": "33590", "Score": "3" } }, { "body": "<p>You can use jQuery's <a href=\"http://api.jquery.com/next/\" rel=\"nofollow\"><code>.next()</code></a> and <a href=\"http://api.jquery.com/prev/\" rel=\"nofollow\"><code>.prev()</code></a></p>\n\n<pre><code>function nextPic() {\n var current = $(\"#container .top-pic\");\n var next = current.next(\"img\");\n if( next.length === 0 ) {\n next = $(\"#container img:first\");\n }\n current.removeClass(\"top-pic\");\n next.addClass(\"top-pic\");\n}\n\nfunction prevPic() {\n var current = $(\"#container .top-pic\");\n var prev = current.prev(\"img\");\n if( prev.length === 0 ) {\n prev = $(\"#container img:last\");\n }\n current.removeClass(\"top-pic\");\n prev.addClass(\"top-pic\");\n}\n\n$('#next').click(nextPic);\n$('#prev').click(prevPic);\n</code></pre>\n\n<p>Or, avoiding the duplication:</p>\n\n<pre><code>function switchTopPic(direction) {\n var map = { prev: 'last', next: 'first' },\n current = $(\"#container .top-pic\"),\n target = current[direction](\"img\");\n if( target.length === 0 ) {\n target = $(\"#container img\")[map[direction]]();\n }\n current.removeClass(\"top-pic\");\n target.addClass(\"top-pic\");\n}\n\n$('#next').click(function () { switchTopPic(\"next\") });\n$('#prev').click(function () { switchTopPic(\"prev\") });\n</code></pre>\n\n<p>Or given the markup in the question, the last little bit could just be:</p>\n\n<pre><code>$('#next, #prev').click(function () { switchTopPic(this.id) });\n</code></pre>\n\n<p>Either way, it should handle an arbitrary number of images (including none at all), and it doesn't require a <code>top-pic</code> to be set ahead of time. All state information is kept in the markup, and does not require the image IDs to be sequential (they don't even need an ID at all).</p>\n\n<p><strong>Edit:</strong> <a href=\"http://jsfiddle.net/p36tK/\" rel=\"nofollow\">Here's a jsfiddle</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:03:32.080", "Id": "33592", "ParentId": "33590", "Score": "6" } }, { "body": "<p>It's rather contrived, but this is what I've come up with:</p>\n\n<pre><code>$('#next, #prev').click(function(){\n $imageCount = $('#container img').length;\n $current = $('#container .top-pic');\n $current.removeClass('top-pic');\n $currentIdNumber = parseInt($current.attr('id').substr(3));\n $newId = '#pic' + (this.id == 'next' ? $currentIdNumber % $imageCount + 1 : ($currentIdNumber + $imageCount - 2) % $imageCount + 1);\n $('#container ' + $newId).addClass('top-pic');\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/Y8ZKW/\" rel=\"nofollow\"><em>jsfiddle example</em></a></p>\n\n<p>I could make it shorter still, but that won't improve the readability of the already difficult to read suggestion. ;-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:17:20.003", "Id": "33594", "ParentId": "33590", "Score": "2" } }, { "body": "<p>I came up with this solution, it avoids duplication and it should be doing the least amount of dom queries and if checks. I think it is important to not only stay <strong>dry</strong> when you have similar logic like previous vs next but also with selectors that jquery will use to get element references.</p>\n\n<pre><code>var first = $('#container img').first(),\n last = $('#container img').last(),\n topPicClass = '.top-pic';\n\n\nfunction createOnClick(navFn, endNavEl) {\n return function() {\n var cur = $(topPicClass),\n next = cur[navFn]();\n\n if(next.length === 0) {\n next = endNavEl;\n }\n\n cur.removeClass(topPicClass);\n next.addClass(topPicClass);\n }\n}\n\n$('#next').click(createOnClick('next', first));\n$('#prev').click(createOnClick('prev', last));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:35:12.233", "Id": "33600", "ParentId": "33590", "Score": "1" } }, { "body": "<p>In two chains:</p>\n\n<pre><code>$('#next').click(function () {\n $('#container .top-pic').removeClass().next()\n .add($('#container img:first')).last().addClass('top-pic');\n});\n$('#prev').click(function () {\n $('#container .top-pic').removeClass().prev()\n .add($('#container img:last')).eq(0).addClass('top-pic');\n});\n</code></pre>\n\n<p>Please let me know if this code requires additional explanation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T03:47:14.130", "Id": "33632", "ParentId": "33590", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T16:03:25.020", "Id": "33590", "Score": "2", "Tags": [ "javascript", "jquery", "image" ], "Title": "Simple image rotation script" }
33590
<p>I presented a code solution to a startup as part of their interview polity.</p> <p>The problem statement is to find the frequency of words occurring in a sentence. I got the code rejected saying, "Evaluating code is always subjective, but people generally leave a "fingerprint" with their design approach and the nature of their code (comments, tests, multiple solution paths, validation). The hiring manager has a high bar, and has rejected many working solutions because he didn't like the approach or the number of trees used or linear scaling vs. ^2 scaling."</p> <p>I have pasted my solution. The hiring manager specified not to use collection API. I would like some opinions as to how I would have improved the code.</p> <pre><code>import java.io.*; import java.util.*; class FreqWord { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System. in )); String str[] = new String[30]; StringTokenizer st; int i = 0, j, k, ctr, size = 0; System.out.println(" Enter the String :"); String str1 = br.readLine(); st = new StringTokenizer(str1, " \n"); while (st.hasMoreTokens()) { str[i] = st.nextToken(); size++; i++; } System.out.println("\n-------------"); System.out.println("\nWord" + "\t" + "freq"); System.out.println("\n-------------"); for (i = 0; i &lt; size; i++) { ctr = 0; for (j = i; j &lt; size; j++) { if (str[j].equals(str[i])) ctr++; } for (k = i - 1; k &gt;= 0; k--) { if (str[k].equals(str[i])) { ctr = 0; break; } } if (ctr != 0) { System.out.println(str[i] + "\t" + ctr); } } System.out.println("\n------------"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:12:07.347", "Id": "53811", "Score": "2", "body": "Proper indentation would be a good start." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:12:23.447", "Id": "53812", "Score": "3", "body": "I hope you didn't present it like that. Please, please, please format and indent your code appropriately. No-one is going to take the time to look through your code and make suggestions if you can't be bothered to make it presentable in the first place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:15:50.543", "Id": "53813", "Score": "0", "body": "Does \"not to use collection api\" include Guava? `Multiset` could do this in a few lines of code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:29:44.137", "Id": "53817", "Score": "1", "body": "I'm confused by the requirements between your title (not using `if`, `for`, or `while`) and hiring manager limitation (not using `Collections`. Plus your code has both `if` and `while`. So, what is the exact and complete task here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:33:49.077", "Id": "53818", "Score": "0", "body": "It seems that using `split()` method can simplify the code a bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:02:33.467", "Id": "53827", "Score": "0", "body": "I took the liberty of copying your code, and it does not work... I am editing my answer too" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T21:34:12.580", "Id": "53858", "Score": "0", "body": "I am perplexed by the title of this post: \"Optimal code without using for, while and if\". What tools would you be left with — `case` statements and recursion?" } ]
[ { "body": "<p>I am not a fan of this type of interview process... but ... you can assume that you need to differentiate yourself from the other candidates in some way.</p>\n\n<p>Your solution may work, but does not show much in the way of 'clever' algorithms. You do the minimum to get the answer right, but not in the best way.</p>\n\n<p>Things I think you could do better are:</p>\n\n<ol>\n<li>Do not load the entire document in to memory. It may be large. Instead, use a mechanism for counting the words in a streaming way. It will save memory.</li>\n<li>What about handling mixed-case words \"The quick brown fox jumped over the sleeping dog\" has the word 'the' twice, note the words 'The' and 'the' once each.</li>\n<li>Consider a faster method for processing the data than a linnear scan through the words. A binary search and adding data to a sorted array would differentiate you.</li>\n</ol>\n\n<p>EDIT: I took the liberty of copying and running the code, and it does not work. I changed the code to be: </p>\n\n<pre><code>BufferedReader br = new BufferedReader(new\n InputStreamReader(new FileInputStream(new File(\"src/FreqWord.java\"))));\n</code></pre>\n\n<p>and this produced the result:</p>\n\n<pre><code> Enter the String :\n\n-------------\n\nWord freq\n\n-------------\nimport 1\njava.io.*; 1\n\n------------\n</code></pre>\n\n<p>This is obviously not correct, so I will take a moment and write what I consider to be a 'good' solution. This will also answer the comment below about the Binary Search.</p>\n\n<p>EDIT 2: Here's an answer that demonstrates the three issues I mentioned (just the main method), and as a bonus it gets the right answer.... :</p>\n\n<pre><code>public static void main(String[] args) throws IOException {\n // show you know the Java7 language changes...\n try (BufferedReader br = new BufferedReader(new InputStreamReader(\n new FileInputStream(new File(\"src/FreqWord.java\"))))) {\n int wordcount = 0; // the number of unique words we have\n\n String [] wordvalues = new String[32];\n int [] counts = new int[32];\n\n String line = null;\n // Using regular expressions is a differentiator\n final Pattern pattern = Pattern.compile(\"\\\\w+\");\n while ((line = br.readLine()) != null) {\n // Only keep one line at a time in memory.\n Matcher matcher = pattern.matcher(line);\n while (matcher.find()) {\n // use toLowerCase() to show a grasp of the problem\n String word = matcher.group().toLowerCase();\n // use BinarySearch to order the words, which is faster than a scan.\n int ip = Arrays.binarySearch(wordvalues, 0, wordcount, word);\n if (ip &lt; 0) {\n // word we have not yet seen.\n ip = -ip - 1;\n if (wordcount == wordvalues.length) {\n // grow the word array by about 25% each time we need to.\n wordvalues = Arrays.copyOf(wordvalues, wordcount + 1 + (wordcount &gt;&gt;&gt;2));\n counts = Arrays.copyOf(counts, wordvalues.length);\n }\n // insert the word in sorted order.\n System.arraycopy(wordvalues, ip, wordvalues, ip+1, wordcount-ip);\n System.arraycopy(counts, ip, counts, ip+1, wordcount-ip);\n wordvalues[ip] = word;\n wordcount++;\n }\n counts[ip]++;\n }\n }\n // output the words in alphabetical order.\n System.out.println(\"\\n-------------\");\n System.out.println(\"\\nWord\" + \"\\t\" + \"freq\");\n System.out.println(\"\\n-------------\");\n for (int i = 0; i &lt; wordcount; i++) {\n System.out.println(wordvalues[i] + \"\\t\" + counts[i]);\n }\n System.out.println(\"\\n------------\");\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:35:03.847", "Id": "53819", "Score": "0", "body": "You may have a point here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:56:53.060", "Id": "53825", "Score": "0", "body": "I agree with most of your suggestions. Although I am not sure how using a binary search would help here since, according to the javadoc: *\"If the range contains multiple elements equal to the specified object, there is no guarantee which one will be found\"*. (http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#binarySearch%28java.lang.Object[],%20int,%20int,%20java.lang.Object%29)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:30:18.793", "Id": "53835", "Score": "0", "body": "I have updated with an example of how I think Binary Search is useful.... which should make it clear." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:33:22.463", "Id": "33599", "ParentId": "33593", "Score": "10" } }, { "body": "<p>I think that one of the problems here is related to what the hiring manager said:</p>\n\n<blockquote>\n <p>comments, tests, multiple solution paths, validation</p>\n</blockquote>\n\n<p>are missing. You need to make your code more readable ...</p>\n\n<p>Moreover, it isn't a good OOP practice to put all your business logic in your main method: use the OO features! Your code will become more readable, understandable and clean (especially if you use good names of variables and methods). </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:43:23.733", "Id": "33602", "ParentId": "33593", "Score": "6" } }, { "body": "<p>Without <code>for</code>, <code>while</code> and <code>if</code> you have only <code>do-while</code> and <code>switch</code>. I doubt that using only them will improve your code quality.</p>\n\n<p>Your code has <code>O(N*N)</code> (N=number of words) running time and uses assumption that there exist no sentence longer than 30 words. Both things makes your design rather poor. </p>\n\n<ol>\n<li><p>Here is a very simple way to acheive <code>O(NlogN)</code> complexity. You should copy all words into array, which runs in <code>O(N)</code>, sort the words array <code>+O(NlogN)</code> and count adjacent duplicates <code>+O(N) = O(NlogN)</code> complexity</p></li>\n<li><p>You should reallocate and copy array if its default capacity is overflowed. Always allocate 2 times more space than previously and you will need only <code>O(logN)</code> reallocations and <code>O(NlogN)</code> object copying operations.</p></li>\n<li><p>And if you can quickly implement balanced search tree <em>or hash map</em> (which is much simpler) on the interview - of course, do it. With it you can store much less temporary data (unique words, their counts and node references only).</p></li>\n<li><p>If you really believe in \"<code>Map</code> is not <code>Collection</code>\" argument - of course, just use <code>HashMap</code> instead of all the tricks :)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:44:05.380", "Id": "33603", "ParentId": "33593", "Score": "1" } }, { "body": "<p>You are writing Java code which is supposed to be OO in a procedural fashion.</p>\n\n<p>No thought was put into class design, or separating logic from output.</p>\n\n<p>There are 0 comments in the code, variable names are cryptic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:44:18.840", "Id": "33604", "ParentId": "33593", "Score": "1" } }, { "body": "<p>I would try to split the sentence into individual words using a regex and then sort the resulting array. This would make counting words much more easy.</p>\n\n<p>Here`s an example of what I have in mind:</p>\n\n<pre><code>// Splitting on punctuation and whitespace\nString[] words = sentence.split(\"[\\\\p{Punct}\\\\s]+\");\nArrays.sort(words);\n\n// count initialized to 1 since if the array length is greater \n// then 0, then there is at least one word...\nint count = 1;\nfor (int i = 0; i &lt; words.length; i++) {\n if (i+1 &lt; words.length &amp;&amp; words[i].equalsIgnoreCase(words[i+1])) {\n count++;\n }\n else {\n System.out.println(words[i] + \": \" +count);\n count = 1;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:47:32.457", "Id": "33607", "ParentId": "33593", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:10:42.550", "Id": "33593", "Score": "3", "Tags": [ "java", "interview-questions" ], "Title": "Optimal code without using for, while and if" }
33593
<p>I keep using a pattern in ruby over and over again.</p> <p>Here are some examples:</p> <pre><code> def get_row_numbers_for_id(id_to_search_for) @results = [] (0...row_count).each do |row| get_row(row).css('td').each do |cell| @results &lt;&lt; row unless row.nil? if (cell['id'] == id_to_search_for) &amp;&amp; !(cell.to_html =~ /continued/i) end end @results end </code></pre> <p>And</p> <pre><code>def cell_content_array @cells = [] @doc.css('td p span').each do |cell| @cells &lt;&lt; cell.content end @cells end </code></pre> <p>I'm initializing an array, using some sort of loop that shoves stuff onto it, and returning it. I know there is a better way to do this.</p> <p>What are some preferred Ruby ways to do this? All answers welcome.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T01:37:53.010", "Id": "53996", "Score": "0", "body": "A small thing, David: 'results' and 'cells' don't need to be instance variables; local variables would be within the scopes of the respective blocks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T19:17:10.863", "Id": "54154", "Score": "0", "body": "what if you want to use an attr_acessor, reader or writer?" } ]
[ { "body": "<p>What you're looking for is Array#map or Enumerable#collect.</p>\n\n<p>The 2nd method can be written as</p>\n\n<pre><code>def cell_content_array\n @doc.css('td p span').map { |span| span.content }\nend\n</code></pre>\n\n<p>Or, as we're simply extracting <code>content</code>, it can be further simplified to:</p>\n\n<pre><code>def cell_content_array\n @doc.css('td p span').map(&amp;:content)\nend\n</code></pre>\n\n<p>Your first method is pretty cryptic (<code>row unless row.nil? if ...</code> - what?), but if I understand it correctly, this should do</p>\n\n<pre><code>def get_row_numbers_for_id(id_to_search_for)\n rows.select do |row|\n cells = row.css(\"td##{id_to_search_for}\") # find only cells with the right id\n cells.any? &amp;&amp; cells.none? { |cell| cell.to_html =~ /continued/i }\n end\nend\n</code></pre>\n\n<p>I'm assuming here, that you can extract a <code>rows</code> method that gives you all the relevant rows, so you can avoid the <code>(0...row_count)</code>. You can of course use <code>(0...row_count).map { ... }</code> instead, but it's nicer, I think, to place that bit of logic elsewhere, even if it is just one line.</p>\n\n<p>Also, I don't know the rest of your code, but (provided <code>@doc</code> doesn't change after instantiation) you might want to use the <code>||=</code> operator in the <code>cell_content_array</code> method to cache the result to an instance variable. That way, it won't you don't need to run the CSS selector and mapping again on subsequent calls.</p>\n\n<pre><code>def cell_content_array\n @cell_content ||= @doc.css('td p span').map(&amp;:content)\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:52:00.743", "Id": "33608", "ParentId": "33598", "Score": "5" } } ]
{ "AcceptedAnswerId": "33608", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T17:28:19.833", "Id": "33598", "Score": "-2", "Tags": [ "ruby" ], "Title": "Initializing an array, using some sort of loop that shoves stuff onto it, and returning it" }
33598
<p>I put together a sample of how I am using the Unit of Work &amp; Repository pattern based on my understanding. Can anyone please let me know if I am implementing this the correct way? If I am not, how can I improve it?</p> <p>I have an EF model with two entities: Topic and Subtopic. The EF model is called CommonGood.</p> <p>Unit of Work:</p> <pre><code> /// &lt;summary&gt; /// Implementation of a UnitOfWork class /// &lt;/summary&gt; public static class UnitOfWork { /// &lt;summary&gt; /// Gets the default context /// &lt;/summary&gt; /// &lt;returns&gt;A new instance of the default context&lt;/returns&gt; public static CommonGoodEntities GetContext() { return new CommonGoodEntities(); } } </code></pre> <p>IGenericRepository:</p> <pre><code>public interface IRepository&lt;T&gt; { /// &lt;summary&gt; /// Gets all entities /// &lt;/summary&gt; /// &lt;returns&gt;All entities&lt;/returns&gt; IEnumerable&lt;T&gt; GetAll(); /// &lt;summary&gt; /// Gets all entities matching the predicate /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;The filter clause&lt;/param&gt; /// &lt;returns&gt;All entities matching the predicate&lt;/returns&gt; IEnumerable&lt;T&gt; GetAll(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); /// &lt;summary&gt; /// Set based on where condition /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;The predicate&lt;/param&gt; /// &lt;returns&gt;The records matching the given condition&lt;/returns&gt; IQueryable&lt;T&gt; Where(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); /// &lt;summary&gt; /// Finds an entity matching the predicate /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;The filter clause&lt;/param&gt; /// &lt;returns&gt;An entity matching the predicate&lt;/returns&gt; IEnumerable&lt;T&gt; Find(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); /// &lt;summary&gt; /// Determines if there are any entities matching the predicate /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;The filter clause&lt;/param&gt; /// &lt;returns&gt;True if a match was found&lt;/returns&gt; bool Any(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); /// &lt;summary&gt; /// Returns the first entity that matches the predicate /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;The filter clause&lt;/param&gt; /// &lt;returns&gt;An entity matching the predicate&lt;/returns&gt; T First(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); /// &lt;summary&gt; /// Returns the first entity that matches the predicate else null /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;The filter clause&lt;/param&gt; /// &lt;returns&gt;An entity matching the predicate else null&lt;/returns&gt; T FirstOrDefault(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); /// &lt;summary&gt; /// Adds a given entity to the context /// &lt;/summary&gt; /// &lt;param name="entity"&gt;The entity to add to the context&lt;/param&gt; void Add(T entity); /// &lt;summary&gt; /// Deletes a given entity from the context /// &lt;/summary&gt; /// &lt;param name="entity"&gt;The entity to delete&lt;/param&gt; void Delete(T entity); /// &lt;summary&gt; /// Attaches a given entity to the context /// &lt;/summary&gt; /// &lt;param name="entity"&gt;The entity to attach&lt;/param&gt; void Attach(T entity); } </code></pre> <p>GenericRepository:</p> <pre><code>public class GenericRepository&lt;T&gt; : IRepository&lt;T&gt; where T : class { /// &lt;summary&gt; /// The database context for the repository /// &lt;/summary&gt; private DbContext _context; /// &lt;summary&gt; /// The data set of the repository /// &lt;/summary&gt; private IDbSet&lt;T&gt; _dbSet; /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="GenericRepository{T}" /&gt; class. /// &lt;/summary&gt; /// &lt;param name="context"&gt;The context for the repository&lt;/param&gt; public GenericRepository(DbContext context) { this._context = context; this._dbSet = this._context.Set&lt;T&gt;(); } /// &lt;summary&gt; /// Gets all entities /// &lt;/summary&gt; /// &lt;returns&gt;All entities&lt;/returns&gt; public IEnumerable&lt;T&gt; GetAll() { return this._dbSet; } /// &lt;summary&gt; /// Gets all entities matching the predicate /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;The filter clause&lt;/param&gt; /// &lt;returns&gt;All entities matching the predicate&lt;/returns&gt; public IEnumerable&lt;T&gt; GetAll(System.Linq.Expressions.Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return this._dbSet.Where(predicate); } /// &lt;summary&gt; /// Set based on where condition /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;The predicate&lt;/param&gt; /// &lt;returns&gt;The records matching the given condition&lt;/returns&gt; public IQueryable&lt;T&gt; Where(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return this._dbSet.Where(predicate); } /// &lt;summary&gt; /// Finds an entity matching the predicate /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;The filter clause&lt;/param&gt; /// &lt;returns&gt;An entity matching the predicate&lt;/returns&gt; public IEnumerable&lt;T&gt; Find(System.Linq.Expressions.Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return this._dbSet.Where(predicate); } /// &lt;summary&gt; /// Determines if there are any entities matching the predicate /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;The filter clause&lt;/param&gt; /// &lt;returns&gt;True if a match was found&lt;/returns&gt; public bool Any(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return this._dbSet.Any(predicate); } /// &lt;summary&gt; /// Returns the first entity that matches the predicate /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;The filter clause&lt;/param&gt; /// &lt;returns&gt;An entity matching the predicate&lt;/returns&gt; public T First(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return this._dbSet.First(predicate); } /// &lt;summary&gt; /// Returns the first entity that matches the predicate else null /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;The filter clause&lt;/param&gt; /// &lt;returns&gt;An entity matching the predicate else null&lt;/returns&gt; public T FirstOrDefault(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return this._dbSet.FirstOrDefault(predicate); } /// &lt;summary&gt; /// Adds a given entity to the context /// &lt;/summary&gt; /// &lt;param name="entity"&gt;The entity to add to the context&lt;/param&gt; public void Add(T entity) { this._dbSet.Add(entity); } /// &lt;summary&gt; /// Deletes a given entity from the context /// &lt;/summary&gt; /// &lt;param name="entity"&gt;The entity to delete&lt;/param&gt; public void Delete(T entity) { this._dbSet.Remove(entity); } /// &lt;summary&gt; /// Attaches a given entity to the context /// &lt;/summary&gt; /// &lt;param name="entity"&gt;The entity to attach&lt;/param&gt; public void Attach(T entity) { this._dbSet.Attach(entity); } } </code></pre> <p>Controller:</p> <pre><code>public class HomeController : Controller { /// &lt;summary&gt; /// The context used for the controller /// &lt;/summary&gt; private DbContext _context; /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="HomeController"/&gt; class. /// &lt;/summary&gt; public HomeController() { this._context = UnitOfWork.GetContext(); } public JsonResult GetTopics() { var topics = new GenericRepository&lt;Topic&gt;(this._context).GetAll().ToList(); return this.Json(topics, JsonRequestBehavior.AllowGet); } /// &lt;summary&gt; /// Disposes of the context if the currently disposing /// &lt;/summary&gt; /// &lt;param name="disposing"&gt;A value indicating whether or not the application is disposing&lt;/param&gt; protected override void Dispose(bool disposing) { if (disposing) { this._context.Dispose(); } base.Dispose(disposing); } } </code></pre> <p>Essentially I want to make sure I am accessing data in the proper way and making sure I am not overlooking anything.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T19:50:57.370", "Id": "53848", "Score": "1", "body": "While accepting answers is an excellent idea, you should give it some more time, perhaps 2-3 days, to let the votes roll in and keep your question appealing to other answerers. Prematurely accepted answers tend to get low views and low votes, and that's bad because sometimes they're gems!" } ]
[ { "body": "<p>You're getting there. Here's a pattern that I've used that works really well. I don't like generic \"find\" and \"save\" methods because they tend to be really complicated in order to work with everything and I find you end up pulling your hair out when you want to do something special.</p>\n\n<p>Here's the base repository class. We want concrete implementations so we throw <code>abstract</code> on there</p>\n\n<pre><code>public abstract class BaseRepository\n{\n\n protected UnitOfWork _uow;\n\n public BaseRepository(UnitOfWork unitOfWork) {\n _uow = unitOfWork;\n }\n\n protected MyEntities DB {\n get { return _uow.DB; }\n }\n\n}\n</code></pre>\n\n<p>Heres the Unit of work implementation. An option here is having your UnitOfWork implement <code>IDisposable</code></p>\n\n<pre><code>public class UnitOfWork\n{\n private MyEntities _db;\n\n public MyEntities DB {\n get { return _db; }\n }\n\n public UnitOfWork() {\n _db = new MyEntities (); \n }\n\n public void SaveChanges() {\n _db.SaveChanges();\n }\n\n}\n</code></pre>\n\n<p>The implementation of a repository. I generally make a repository separating different entities, but there are several logical ways of separating them. In this repository you write a method that corresponds to a requirement for something like \"GetAllDocuments\" or \"GetPerson\". You then call the entities context and work on it directly. This provides the separation of the Data Access Layer with the Business Layer.</p>\n\n<pre><code>public class MyRepository : BaseRepository\n{\n public MyRepository (UnitOfWork unitOfWork)\n : base(unitOfWork)\n {\n }\n\n public MyObject GetObject(int objectID)\n {\n return DB.Objects.FirstOrDefault(n =&gt; n.ObjectID == ObjectID);\n }\n}\n</code></pre>\n\n<p>A base controller holds the unit of work</p>\n\n<pre><code>public class BaseController : Controller\n{\n private UnitOfWork _uow;\n\n protected UnitOfWork UOW {\n get {\n if (_uow == null) {\n _uow = new UnitOfWork();\n }\n return _uow;\n }\n }\n}\n</code></pre>\n\n<p>Instantiate the repository you want to work out of in the constructor of the controller, passing in the unit of work variable that comes from the base controller.</p>\n\n<pre><code>public class HomeController : BaseController\n{\n MyRepository _myrepo;\n\n public HomeController()\n {\n _myrepo = new MyRepository(UOW);\n }\n}\n</code></pre>\n\n<p>Now in any of your methods, you have access to your database through business requirements without touching EF implementation</p>\n\n<pre><code>public ActionResult Index()\n{\n _myRepo.GetObject(myInt);\n\n return View();\n}\n</code></pre>\n\n<p>You can use multiple repos in the same controller by simply instantiating another repo. Since the unit of work is the same they are the same context, so you can work with both at the same time.</p>\n\n<pre><code>MyRepository _myrepo;\nMyOtherRepository _myOtherRepo;\n\npublic HomeController()\n{\n _myrepo = new MyRepository(UOW);\n _myOtherRepo = new MyOtherRepository(UOW);\n}\n</code></pre>\n\n<p>Because of the way controllers work, a cool consequence of all this is that your contexts are \"short lived\". Once your GET or POST method returns, the context is destroyed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T14:15:46.107", "Id": "53907", "Score": "0", "body": "A nice addition to this would be Ninject too, good answer though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T14:14:28.280", "Id": "64876", "Score": "1", "body": "Any chance you could expand on this answer by showing the relationship between the projects/classes where the different code resides and how it is accessed. To better understand how projects such as these are structured." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T14:17:39.527", "Id": "64877", "Score": "0", "body": "I would like to see this example extended for IoC <3!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T02:15:34.877", "Id": "103120", "Score": "0", "body": "@shoe: is there a way you can have your repository on github? i have been searching for a good repository/uow pattern" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T03:30:24.343", "Id": "103129", "Score": "0", "body": "@Abu I will see if I can create a few projects with a few designs that I've implemented over time and put them on my github page." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-25T17:45:16.337", "Id": "104078", "Score": "0", "body": "Pls let me know when u get chance to create project. I am in the process of picking the design." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-26T00:18:13.043", "Id": "104151", "Score": "0", "body": "@AbuHamzah See https://github.com/shoe788/Basic-MVC-5-Repository-Pattern" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-31T14:47:47.883", "Id": "105326", "Score": "0", "body": "@Shoe: thank you for the github link, I'm modifying and make it more generic and post you the github for feedback" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:39:12.467", "Id": "33613", "ParentId": "33611", "Score": "6" } } ]
{ "AcceptedAnswerId": "33613", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:15:55.857", "Id": "33611", "Score": "6", "Tags": [ "c#", "asp.net-mvc-4" ], "Title": "Unit of Work with Repository Pattern MVC 5 & EF 6" }
33611
<p>This is bit long, but I need to explain something before I can ask for actual reviews/advice.</p> <p>I have to test generated C code from Matlab Simulink model. I can create a executable binary from those. I need to test this application using tests developed using Python scripting.</p> <p>I came up with following approach: inter-process communication using shared memory.</p> <p>I planned to write a DLL or a shared object, which enables the communication between the tests scripts and the application. This DLL will be used via both Python scripts and application to interact with each other</p> <p>Here's my DLL code, which uses <code>boost::interprocess</code> shared memory.</p> <pre><code>int create_shmem(const char* shmem_name, long long length ) { try{ // remove_shmem(shmem_name); boost::interprocess::shared_memory_object shm (boost::interprocess::create_only, shmem_name, boost::interprocess::read_write); //Set size shm.truncate(length); return 1; } catch(...){ std::cerr &lt;&lt; "Error Creating Shared Memory : " &lt;&lt; shmem_name &lt;&lt; std::endl; } return 0; } int remove_shmem(const char* shmem_name ) { try { boost::interprocess::shared_memory_object::remove(shmem_name); return 1; } catch(...){ std::cerr &lt;&lt; "Error Removing Shared Memory : "&lt;&lt; shmem_name &lt;&lt; std::endl; } return 0; } int write_shmem(const char* shmem_name, char* shmem) { try{ boost::interprocess::shared_memory_object shm (boost::interprocess::open_only, //Open if already created shmem_name, boost::interprocess::read_write); //Map the whole shared memory in this process boost::interprocess::mapped_region region (shm, boost::interprocess::read_write ); std::memcpy(region.get_address(), shmem, region.get_size()); return 1; } catch(...){ std::cerr &lt;&lt; "Error Writing to Shared Memory " &lt;&lt; shmem_name &lt;&lt; std::endl; } return 0; } int read_shmem( const char* shmem_name, char *shmem ) { //Open already created shared memory object. // Same process might not be calling it, so create new object try{ boost::interprocess::shared_memory_object shm ( boost::interprocess::open_only, shmem_name, boost::interprocess::read_only); //Map the whole shared memory in this process boost::interprocess::mapped_region region (shm, boost::interprocess::read_only ); //CAUTION : No check is performed std::memcpy(shmem, reinterpret_cast&lt;char*&gt; (region.get_address()), region.get_size()); return 1; } catch(...){ std::cerr &lt;&lt; "Error Reading from Shared Memory " &lt;&lt; shmem_name &lt;&lt; std::endl; } return 0; } </code></pre> <p>The application needs simulation of around 1.5K different signals of different data types all packed in a C <code>struct</code>. </p> <p>My initial though is to created a shared memory and write the simulated signals on to it which the application can fetch and accordingly shows the output by writing back to same shared memory which is again read from test scripts.</p> <p>Any help/advice regarding underlying issues/failure and improvement will be much appreciated.</p> <p>I can post my <code>ctypes</code> Python interface if required.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-02T12:24:34.557", "Id": "243168", "Score": "0", "body": "One thing: the `multiprocessing` module already natively supports shared memory." } ]
[ { "body": "<p>It is short and to the point. Looks fine.</p>\n\n<blockquote>\n <p>used via both Python scripts and application to interact with each other</p>\n</blockquote>\n\n<p>You didn't describe the interaction, in English nor in code. Maybe the two sides routinely manipulate lots of data structures (1500 signals didn't quite sound like \"a lot\") that the other side uses less than 1% of the time, so your code or the <a href=\"https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes\" rel=\"nofollow noreferrer\">multiprocessing support</a> that ppperry highlighted would be appropriate. But the interaction is going to require condition variables or mutexes or higher level coordination such as queues. Since you've not specified the performance characteristics, I would just start with a TCP connection, or pub-sub, and go from there, see how things shake out. Localhost TCP offers very high bandwidth, and low latency. Profiling might reveal a need for shmem, but I'm skeptical, and it's better to cross that bridge after it's clear that you need to.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-15T14:36:53.220", "Id": "175729", "ParentId": "33612", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:34:11.643", "Id": "33612", "Score": "7", "Tags": [ "python", "c++", "boost" ], "Title": "Signal simulation through Python scripts using shared memory for testing a C application" }
33612
<p>The overall intent is to consolidate individual sales transactions to total debits/credits summing up the totals by year and month--retaining a running balance from start to end. This code uses multiple <code>#temp</code> tables. I am interested in having this code reviewed in order to find a more efficient way to achieve this.</p> <p>The <code>create table</code> and <code>insert</code> statements are for the convenience of the code reviewer, should s/he choose to execute the code.</p> <pre><code>CREATE TABLE SumTest( POSDate datetime NULL, debit money NULL, credit money NULL, RollingBalance money NULL, expires datetime NULL, ExpiringDebitBalance_2013 money, ExpiringDebitBalance_2014 money ); -- mimic actual sales transactions insert into sumtest (POSDate,debit,credit,expires) values ('Jan 5 2013 12:00AM','670.00','22.00','Dec 31 2014 12:00AM'); insert into sumtest (POSDate,debit,credit,expires) values ('Jan 6 2013 12:00AM','821.00','0.00','Dec 31 2014 12:00AM'); insert into sumtest (POSDate,debit,credit,expires) values ('Mar 8 2013 12:00AM','62.00','700.00','Dec 31 2014 12:00AM'); insert into sumtest (POSDate,debit,credit,expires) values ('Mar 11 2013 12:00AM','78.00','29.00','Dec 31 2014 12:00AM'); insert into sumtest (POSDate,debit,credit,expires) values ('Mar 11 2013 12:00AM','900.00','87.00','Dec 31 2014 12:00AM'); insert into sumtest (POSDate,debit,credit,expires) values ('Apr 16 2013 12:00AM','0.00','440.00',NULL); insert into sumtest (POSDate,debit,credit,expires) values ('Aug 18 2013 12:00AM','0.00','50.00',NULL); insert into sumtest (POSDate,debit,credit,expires) values ('Aug 19 2013 12:00AM','470.00','200.00','Dec 31 2014 12:00AM'); insert into sumtest (POSDate,debit,credit,expires) values ('Dec 31 2012 12:00AM','1000.00','200.00','Dec 31 2013 12:00AM'); insert into sumtest (POSDate,debit,credit,expires) values ('Dec 22 2013 12:00AM','200.00','0.00','Dec 31 2014 12:00AM'); insert into sumtest (POSDate,debit,credit,expires) values ('Dec 20 2013 12:00AM','500.00','0.00','Dec 31 2014 12:00AM'); insert into sumtest (POSDate,debit,credit,expires) values ('Nov 10 2012 12:00AM','200.00','0.00','Dec 31 2013 12:00AM'); insert into sumtest (POSDate,debit,credit,expires) values ('Nov 11 2012 12:00AM','150.00','0.00','Dec 31 2013 12:00AM'); insert into sumtest (POSDate,debit,credit,expires) values ('Nov 15 2012 12:00AM','0.00','100.00',NULL); create table #work ( POSYear int NULL, POSMonth int NULL, debit money NULL, credit money NULL, RollingBalance money NULL, expires datetime ) -- start with ditching the time insert into #work (POSYear,POSMonth,debit,credit,expires) select datepart(Year, POSDate) as POSYear ,datepart(Month, POSDate) as POSMonth ,debit ,credit ,expires from sumtest -- dump an ordered set by year,month with a rolling balance of all points/redemptions ;with distilled as (select POSYear, POSMonth, TotalDebit = sum(debit), TotalCredit = sum(credit), expires from #work group by POSYear,POSMonth,expires ) select POSYear, POSMonth, TotalDebit, TotalCredit, RollingBalance = sum(totaldebit + (totalcredit)*-1) over ( order by POSYear, POSMonth), expires into #work2 from distilled order by POSYear,POSMonth,TotalDebit,TotalCredit -- filter out credits lines that dont have an expiration date select x.POSYear, x.POSMonth, sum(x.TotalDebit) as TotalDebit, sum(x.TotalCredit) as TotalCredit, x.RollingBalance, EXPYear = datepart(Year, y.expires), EXPMonth = datepart(Month, y.expires) into #work3 from #work2 x inner join #work2 y on x.posyear = y.posyear and x.posmonth = y.posmonth where y.expires is not null group by x.posyear,x.posmonth,x.rollingbalance,y.expires order by posyear,posmonth -- add back in lines that are single credits, w/o debits INSERT INTO #work3 (POSYear,POSMonth,TotalDebit,TotalCredit,RollingBalance,EXPYear,EXPMonth) select POSYear, POSMonth, TotalDebit, TotalCredit, RollingBalance, case when expires is null then (POSYear + 1) end as EXPYear, case when expires is null then 12 end as EXPMonth from #work2 where (POSYear + POSMonth) NOT IN ( select POSYear + POSMonth from #work3) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T15:23:40.087", "Id": "54603", "Score": "0", "body": "i can't even get this to build on SQLFiddle.com. there are a bunch of places where the column names don't match, etc please look over your post and make sure that it is correct" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T16:42:42.740", "Id": "54618", "Score": "0", "body": "[FIDDLE](http://www.sqlfiddle.com/#!3/3b4a0/1) I changed some things, if you could get this to work please post the new fiddle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T04:51:43.100", "Id": "57907", "Score": "0", "body": "If running totals is the central theme of this snippet, you might want to take a look at this [detailed analysis of various calculation methods](http://www.sqlperformance.com/2012/07/t-sql-queries/running-totals \"Best approaches for running totals\")." } ]
[ { "body": "<p>it is good Coding Practice to Capitalize all of the Reserved SQL words so that it is easier to tell them apart. </p>\n\n<p>words like <code>SELECT</code>, <code>FROM</code>, <code>WHERE</code>, <code>WITH</code>, <code>INTO</code>, <code>GROUP BY</code>, <code>ORDER BY</code>, <code>CREATE TABLE</code>, <code>INSERT INTO</code>, <code>END</code>, <code>CASE</code>, <code>AS</code>, <code>IS NULL</code>, <code>THEN</code></p>\n\n<p>I know this is Kind of Nitpicking, but you should get into the habit of doing it, even though SQL is not Case Sensitive on these.</p>\n\n<p>I know this isn't the review that you were looking for, but it seems you have an issue that you need to fix before we can review this code</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T14:49:37.247", "Id": "53913", "Score": "0", "body": "Oh boy!:-\\ That's the best we can do? I thought \"working code\" was the operative phrase. What I have works--what I don't have is code that is good. I'm willing to admit that so I can move forward with a better approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T19:25:31.613", "Id": "53934", "Score": "0", "body": "I will take a closer look at it later, if I get the chance before I leave for the day, as long as the code functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T03:01:12.790", "Id": "53951", "Score": "0", "body": "@Malachi actually if this is written is SSMS or VisualStudio, or even NotePad++, keywords are highlighted in bright blue so IMHO they're already easy to tell apart. I like lowercase SQL, I find it's much easier on the eyes. As always what really matters is consistency: there's no reason for `CREATE TABLE` and `NULL` (vs `create table` and `null`) if you're going to `insert into` some `values` (or `select from`)... especially if you're later going to `create table`. That said I find the CR syntax highlighting could be improved." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T04:32:29.773", "Id": "53952", "Score": "0", "body": "I posted this on meta: [Could syntax highlighting be improved?](http://meta.codereview.stackexchange.com/questions/935/could-syntax-highlighting-be-improved)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T14:05:06.333", "Id": "54112", "Score": "0", "body": "I didn't necessarily mean in CR alone, I meant in the IDE, but that is a good point as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T01:48:00.400", "Id": "57897", "Score": "0", "body": "@Malachi so, where's the rest?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T02:01:18.377", "Id": "57900", "Score": "0", "body": "@Malachi nevermind, got it :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T14:00:01.457", "Id": "33651", "ParentId": "33621", "Score": "2" } }, { "body": "<p>You should always make sure <strong>nothing breaks if you accidentally execute your script twice</strong>.</p>\n\n<p>Your script should begin with verifying whether table <code>SumTest</code> exists (and <code>DROP</code> it if it does), <em>before</em> creating it.</p>\n\n<p>Temporary tables <code>#work</code>, <code>#work2</code> and <code>#work3</code> are never dropped. Not a biggie, but if you run the script twice you'll get an error saying <code>there is already an object named '#work' in the database</code>. <strong>Dropping your <code>#temp</code> tables is a good habit to take.</strong></p>\n\n<p>As for the naming, well, @Malachi's answer says one thing, I'll say another: <strong>be consistent. it's all that matters.</strong> - if you drag-and-drop columns and tables from the SSMS object explorer into your query, then by all means stick to <code>UPPERCASE</code>. Personally I find uppercase SQL is annoying to read, it's like all those keywords are jumping at you. Do what you will. I mean, chose whether you prefer <code>UPPERCASE</code> or <code>lowercase</code>, and <strong>stick to your plan</strong>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T02:01:07.500", "Id": "35655", "ParentId": "33621", "Score": "2" } } ]
{ "AcceptedAnswerId": "35655", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T21:28:39.480", "Id": "33621", "Score": "1", "Tags": [ "sql", "sql-server", "t-sql", "finance" ], "Title": "Maintaining a total balance of debit/credit sales transactions" }
33621
<p>I have a backup job that walks across a huge directory with potentially millions of files. Python's os.walk() works just fine.</p> <p>Now, I have implemented a feature to ignore files based in a black list of patterns. I just want it to behave like a .gitignore file.</p> <p>Currently I do this:</p> <pre><code>import os from fnmatch import fnmatch some_dir = '/' ignore_list = ['*.tmp', 'tmp/', '*.py'] for dirname, _, filenames in os.walk(some_dir): for filename in filenames: should_ignore = False for pattern in ignore_list: if fnmatch(filename, pattern): should_ignore = True if should_ignore: print 'Ignore', filename continue </code></pre> <p>It works, but I failed to write it in terms of iterators.</p> <p>Can this routine be written in terms of python iterators? Can it be improved in terms of iterators or generators?</p>
[]
[ { "body": "<p>You can simplify the loop by using a generator expression like this:</p>\n\n<pre><code>for filename in filenames:\n if any(fnmatch(filename, pattern) for pattern in ignore_list):\n print 'Ignore', filename\n continue\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T09:48:09.673", "Id": "33642", "ParentId": "33624", "Score": "4" } } ]
{ "AcceptedAnswerId": "33642", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T00:23:22.093", "Id": "33624", "Score": "1", "Tags": [ "python", "iterator", "generator" ], "Title": "Filtering a long list of files through a set of ignore patterns using iterators" }
33624
<p>My homework was to organize semaphores into a pyramid. The task was accomplished, but I ended up with this long ugly conditional and was wondering if anyone can see a better way/algorithm to accomplish the same thing.</p> <pre><code>if (me==0) { wait_sem(semaphore[1]); wait_sem(semaphore[2]); signal_sem(semaphore[0]); } if (me==1) { wait_sem(semaphore[3]); wait_sem(semaphore[4]); } if (me==2) { wait_sem(semaphore[4]); wait_sem(semaphore[5]); } if (me==3) { wait_sem(semaphore[6]); wait_sem(semaphore[7]); } if (me==4) { wait_sem(semaphore[7]); wait_sem(semaphore[8]); } if (me==5) { wait_sem(semaphore[8]); wait_sem(semaphore[9]); } if (me==6) { wait_sem(semaphore[10]); wait_sem(semaphore[11]); } if (me==7) { wait_sem(semaphore[11]); wait_sem(semaphore[12]); } if (me==8) { wait_sem(semaphore[12]); wait_sem(semaphore[13]); } if (me==9) { wait_sem(semaphore[13]); wait_sem(semaphore[14]); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T00:26:45.737", "Id": "53876", "Score": "2", "body": "You could use a `switch`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T00:31:05.583", "Id": "53877", "Score": "0", "body": "Yeah. A `switch` is a good choice." } ]
[ { "body": "<p>Switch statements are quite helpful in such cases. They are also more efficient than your series of <code>if</code> statements which has to check all of them even after it finds the one it is looking for. The <code>switch</code> will immediately branch to the correct one and skip all the others. Is that helpful?</p>\n\n<pre><code>switch(me)\n{\n case 0:\n wait_sem(semaphore[1]);\n wait_sem(semaphore[2]);\n signal_sem(semaphore[0]);\n break;\n\n case 1:\n wait_sem(semaphore[3]);\n wait_sem(semaphore[4]);\n break;\n\n //etc.\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T00:39:46.827", "Id": "33627", "ParentId": "33626", "Score": "1" } }, { "body": "<p>I wouldn't even use a <code>switch</code> here:</p>\n\n<pre><code>wait_sem(semaphore[me*2+1]);\nwait_sem(semaphore[me*2+2]);\nif (me==0) {\n signal_sem(semaphore[0]); \n}\n</code></pre>\n\n<p>Edit: I see the sequence is not quite linear. If you can come up with an easy mapping between <code>me</code> and the indices, this will work (but with a different formula). Otherwise, a <code>switch</code> statement may be the easiest way.</p>\n\n<p>You can also bury the <code>switch</code> inside a map by mapping the input ints to the two indices (<code>std::map&lt;int, std::pair&lt;int, int&gt; &gt;</code>). It essentially does the same thing, but you can hide the ugly in a header file.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T01:21:10.840", "Id": "53878", "Score": "0", "body": "Potential maintenance issues here..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T01:23:28.727", "Id": "53879", "Score": "0", "body": "For `me==9` you should wait for 13 and 14, not 19 and 20" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T01:27:30.407", "Id": "53880", "Score": "0", "body": "Sorry this migrated right as I was editing, then I had to create an account. Avoiding extraneous code is a good thing, but it probably will not work here." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T01:17:46.823", "Id": "33628", "ParentId": "33626", "Score": "4" } }, { "body": "<p>You always wait on two semaphores and sometimes signal one semaphore. By calculating the index of the semaphores to wait on, you can shorten the code:</p>\n\n<pre><code>assert(me &gt;= 0);\n\nif (me &lt; 10) {\n // Find the unique n s.t. T_n &lt;= me &lt; T_{n+1} where {T_n}_n are the triangular numbers\n int n = (int)(0.5 * (sqrt(1+8*me)-0.99));\n // then calculate nextPos := me + (T_{n+1} - T_n)\n int nextPos = me + n + 1;\n wait_sem(semaphore[nextPos]);\n wait_sem(semaphore[nextPos + 1]);\n}\n\nif (me == 0) {\n signal_sem(semaphore[0]); \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T01:38:36.113", "Id": "33629", "ParentId": "33626", "Score": "0" } }, { "body": "<p>I think using <code>if</code> is ok, but please note that using <code>else if</code> clauses are also important for your code's performance.</p>\n\n<p>Here is another way to do the job. Someone told me that data structures are easier to comprehend than control flows, so let's turn your <code>if</code> statements into <code>data tables</code></p>\n\n<pre><code>typedef struct\n{\n int a;\n int b;\n}MY_TYPE;\n\nMY_TYPE me[10] =\n{\n {1, 2},\n {3, 4},\n {4, 5},\n {6, 7},\n {7, 8},\n {8, 9},\n {10, 11},\n {11, 12},\n {12, 13},\n {13, 14},\n};\n</code></pre>\n\n<p>Then you can use it like this:</p>\n\n<pre><code> int i = 0;\n for (i = 0; i &lt; 10; i++)\n {\n wait_sem(semaphore[me[i].a]);\n wait_sem(semaphore[me[i].b]);\n if (i == 0)\n {\n signal_sem(semaphore[i]);\n }\n }\n</code></pre>\n\n<p>I believe the <code>if/else</code> clause in <code>for</code> could be encapsulated by other utility functions, so maybe you can try it yourself :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T12:44:54.087", "Id": "54580", "Score": "0", "body": "Nice solution. As the structure is used nowhere else and is not modified, I would make it `const` and simplify it a bit by removing the `typedef` and `MY_TYPE` so that `me[10]` is just an anonymous `struct`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T05:58:19.520", "Id": "59193", "Score": "0", "body": "I like this: similar to my answer, but better given the non-regular nature of the number boundaries. +1." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T01:39:07.747", "Id": "33630", "ParentId": "33626", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T00:24:44.873", "Id": "33626", "Score": "6", "Tags": [ "c", "homework", "thread-safety" ], "Title": "Organizing semaphores into a pyramid" }
33626
<p>This program takes a huge data set as input, processes it, calculates and then writes the output to an array. Most calculations may be quite simple, such as summation. In the input file, there are about 100 million rows and 3 columns.</p> <ol> <li>first column is the name of the gene (total 100 millions)</li> <li>second column is the specific value</li> <li>third column is another value of each gene</li> </ol> <p>The problem I face is a long runtime. How can I reduce it?</p> <p>I need to write all new values (from <code>GenePair</code> to <code>RM_pval</code> with header) I calculated from the new file.</p> <pre><code>fi = open ('1.txt') fo = open ('2.txt','w') import math def log(x): return math.log(x) from math import sqrt import sys sys.path.append('/tools/lib/python2.7/site-packages') import numpy import scipy import numpy as np from scipy.stats.distributions import norm for line in fi.xreadlines(): tmp = line.split('\t') GenePair = tmp[0].strip() PCC_A = float(tmp[1].strip()) PCC_B = float(tmp[2].strip()) ZVAL_A = 0.5 * log((1+PCC_A)/(1-PCC_A)) ZVAL_B = 0.5 * log((1+PCC_B)/(1-PCC_B)) ABS_ZVAL_A = abs(ZVAL_A) ABS_ZVAL_B = abs(ZVAL_B) Var_A = float(1) / float(21-3) #SAMPLESIZE - 3 Var_B = float(1) / float(18-3) #SAMPLESIZE - 3 WT_A = 1/Var_A #float WT_B = 1/Var_B #float ZVAL_A_X_WT_A = ZVAL_A * WT_A #float ZVAL_B_X_WT_B = ZVAL_B * WT_B #float SumofWT = (WT_A + WT_B) #float SumofZVAL_X_WT = (ZVAL_A_X_WT_A + ZVAL_B_X_WT_B) #float #FIXED MODEL meanES = SumofZVAL_X_WT / SumofWT #float Var = float(1) / SumofWT #float SE = math.sqrt(float(Var)) #float LL = meanES - (1.96 * SE) #float UL = meanES - (1.96 * SE) #float z_score = meanES / SE #float p_val = scipy.stats.norm.sf(z_score) #CAL ES_POWER_X_WT_A = pow(ZVAL_A,2) * WT_A #float ES_POWER_X_WT_B = pow(ZVAL_B,2) * WT_B #float WT_POWER_A = pow(WT_A,2) WT_POWER_B = pow(WT_B,2) SumofES_POWER_X_WT = ES_POWER_X_WT_A + ES_POWER_X_WT_B SumofWT_POWER = WT_POWER_A + WT_POWER_B #COMPUTE TAU tmp_A = ZVAL_A - meanES tmp_B = ZVAL_B - meanES temp = pow(SumofZVAL_X_WT,2) Q = SumofES_POWER_X_WT - (temp /(SumofWT)) if PCC_A !=0 or PCC_B !=0: df = 0 else: df = 1 c = SumofWT - ((pow(SumofWT,2))/SumofWT) if c == 0: tau_square = 0 else: tau_square = (Q - df) / c #calculation Var_total_A = Var_A + tau_square Var_total_B = Var_B + tau_square WT_total_A = float(1) / Var_total_A WT_total_B = float(1) / Var_total_B ZVAL_X_WT_total_A = ZVAL_A * WT_total_A ZVAL_X_WT_total_B = ZVAL_B * WT_total_B Sumoftotal_WT = WT_total_A + WT_total_B Sumoftotal_ZVAL_X_WT= ZVAL_X_WT_total_A + ZVAL_X_WT_total_B #RANDOM MODEL RM_meanES = Sumoftotal_ZVAL_X_WT / Sumoftotal_WT RM_Var = float(1) / Sumoftotal_WT RM_SE = math.sqrt(float(RM_Var)) RM_LL = RM_meanES - (1.96 * RM_SE) RM_UL = RM_meanES + (1.96 * RM_SE) RM_z_score = RM_meanES / RM_Var RM_p_val = scipy.stats.norm.sf(RM_z_score) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T08:16:18.833", "Id": "53887", "Score": "2", "body": "You import `numpy` but don't take advantage of its vectorized operations. See [What is NumPy?](http://docs.scipy.org/doc/numpy/user/whatisnumpy.html) to get some ideas." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T10:11:28.863", "Id": "53892", "Score": "1", "body": "Your program doesn't seem to produce any output. Why is that? Have you cut out the bit that does the output? Or have you not written it yet?" } ]
[ { "body": "<p>The first thing for solving a problem like this is to find out what the actual bottleneck is. In your case the two most likely parameters are disk IO or CPU power.</p>\n\n<p><strong>Disk IO</strong></p>\n\n<ul>\n<li>Make sure the data sits on local drives and not on a network share or USB stick or similar.</li>\n<li>Make sure your disks are reasonably fast (SSDs might help).</li>\n<li>Put your input file and your output file on two different hard drives.</li>\n<li><a href=\"http://docs.python.org/3/library/mmap.html\" rel=\"nofollow noreferrer\"><code>mmap</code></a> might gain you some speed in reading and/or writing the data. At least <a href=\"https://stackoverflow.com/questions/8151684/how-to-read-lines-from-mmap-file-in-python\">in this case</a> it seemed to make a difference.</li>\n</ul>\n\n<p><strong>CPU</strong></p>\n\n<ul>\n<li>There are several calculations you perform for each line in the input file but those numbers seem to be static (unless the script you posted is incomplete)\n\n<ul>\n<li><code>Var_A = float(1) / float(21-3) #SAMPLESIZE - 3</code> looks like a constant to me which can be calculated once.</li>\n<li>Similar <code>Var_B</code></li>\n<li>From these two a bunch of other variables are calculated which would also be static: <code>WT_A</code>, <code>WT_B</code>, <code>SumofWT</code>, <code>Var</code>, <code>SE</code>, <code>WT_POWER_A</code>, <code>WT_POWER_B</code>, <code>SumofWT_POWER</code>, <code>c</code></li>\n<li>Might not make a huge impact but still seems redundant</li>\n</ul></li>\n<li>As each line seems to be independently calculated this code would be a prime example for parallelization. I have not much experience with python and parallel programming but the <a href=\"http://docs.python.org/3.2/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor\" rel=\"nofollow noreferrer\"><code>ProcessPoolExecutor</code></a> seems like a good start. Bascially utilize as many processes as you have cores and split your input into chunks to be distributed to the processes. You'd have to collect the results (and presumably make sure you write them out in the correct order) so this will make your code a bit more complicated but has the potential to speed up your calculations close to a factor of <code>N</code> (assuming <code>N</code> is the number of CPU cores) provided disk IO is not killing you.\n\n<ul>\n<li>You could also split the input, distribute it to other computers in the office and get the processing done there and collect the results.</li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T07:38:10.997", "Id": "33638", "ParentId": "33633", "Score": "1" } } ]
{ "AcceptedAnswerId": "33638", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T05:44:04.490", "Id": "33633", "Score": "2", "Tags": [ "python", "performance", "numpy", "statistics" ], "Title": "How to reduce runtime of gene data processing program?" }
33633
<p>I was trying another approach of sorting a linked list. Aside from the available methods, I've decided to take each node from the linked list and place it into an array. With that, I would be able to compare the data variables easily. I applied <code>quickSort()</code> on the array, and this is what I have. I would appreciate any feedback/comments on my code.</p> <pre><code> public static void main(String[] args) { MyLinkedList list = new MyLinkedList(); Student s = new Student(1, "John", 20, "Italy", "2011"); list.addStudent(s); Student s2 = new Student(2, "Mark", 19, "UAE", "2010"); list.addStudent(s2); Student s3 = new Student(3, "Sally", 35, "UAE", "2000"); list.addStudent(s3); System.out.println("Students in the list: "); list.print(); Node[] n = list.convertA(list); quickSort(n, 0, (n.length-1)); System.out.println("Sorted list is:"); for(int q =0;q&lt;n.length;q++){ System.out.println(n[q] + " "); } } public static int partition(Node arr[], int left, int right) { int i = left, j = right; Node tmp; Node pivot = arr[(left + right) / 2]; while (i &lt;= j) { while (arr[i].getStudent().getAge() &lt; pivot.getStudent().getAge()) { i++; } while (arr[j].getStudent().getAge() &gt; pivot.getStudent().getAge()) { j--; } if (i &lt;= j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } } return i; } public static void quickSort(Node arr[], int left, int right) { int index = partition(arr, left, right-1); if (left &lt; index - 1) { quickSort(arr, left, index - 1); } if (index &lt; right) { quickSort(arr, index, right); } } </code></pre>
[]
[ { "body": "<p>First of all I don't know why are you trying to <em>reinvent the wheel?</em> Java has a strong and beautiful API with many methods and there is also <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort%28T%5B%5D,%20java.util.Comparator%29\" rel=\"nofollow noreferrer\">a method</a> for sorting an custom array. Which is more faster than <em>quicksort</em>. However I think this is for your own practice.</p>\n\n<ul>\n<li>Your <code>convertA</code> method is not good, cause you are passing the reference as argument as well. So either make the method static or use the existing method <code>toArray()</code>.</li>\n<li><p>You are converting a student list to an <code>Node</code> array, why? change <code>Node</code> array to <code>Student</code> array. So this</p>\n\n<pre><code>arr[i].getStudent().getAge()\n</code></pre>\n\n<p>will change to</p>\n\n<pre><code>arr[i].getAge() \n</code></pre></li>\n<li><p>there is a possible bug you are calculating <code>(left + right) / 2</code> which may cause an overflow, though Java <code>int</code> range is very big you will face the overflow very rarely, but if you want to fix this; change to <code>(right - left) / 2 + left</code>.</p></li>\n</ul>\n\n<p>Check How Other Have Done The Quicksort :</p>\n\n<p><a href=\"https://codereview.stackexchange.com/questions/6939/quick-sort-implementation?rq=1\">From CodeReview 1</a></p>\n\n<p><a href=\"https://codereview.stackexchange.com/questions/4022/java-implementation-of-quick-sort?rq=1\">From CodeReview 2</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/15154158/why-collections-sort-uses-merge-sort-instead-of-quicksort\">Why you should use the API method?</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T12:25:50.433", "Id": "33645", "ParentId": "33634", "Score": "1" } } ]
{ "AcceptedAnswerId": "33645", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T05:58:08.117", "Id": "33634", "Score": "1", "Tags": [ "java", "linked-list", "quick-sort" ], "Title": "Review of linked list and quick sort" }
33634
<p>Simplification of code would be appreciated.</p> <pre><code>var textarea = document.getElementById("textarea"), statusBar = document.getElementById("status-bar"), inputFile = document.getElementById("input-file"), appname = "notepad", isModified = false, showStatusBar = true, filename; function changeDocTitle(newFilename) { // Change doc title filename = newFilename; document.title = filename + " - " + appname; } function dontSave() { // Confirm dont save if (confirm("You have unsaved changes that will be lost.")) { isModified = false; return true; } } function newNote(text, name) { // New if (!isModified || dontSave()) { textarea.value = text || ""; changeDocTitle(name || "untitled.txt"); } textarea.focus(); } function openNote() { // Open if (!isModified || dontSave()) { inputFile.click(); } textarea.focus(); } function rename() { // Rename var newFilename = prompt("Name this note:", filename); if (newFilename !== null) { if (newFilename === "") { changeDocTitle("untitled.txt"); } else { changeDocTitle(newFilename.lastIndexOf(".txt") == -1 ? newFilename + ".txt" : newFilename); } return true; } } function saveNote() { // Save if (rename()) { var blob = new Blob([textarea.value.replace(/\n/g, "\r\n")], { type: "text/plain;charset=utf-8" }); saveAs(blob, filename); isModified = false; } textarea.focus(); } function updatestatusBar() { // Update statusBar var text = textarea.value, chars = text.length, words = text.split(/\S+/g).length - 1, lines = text.split("\n").length; statusBar.value = lines + " lines, " + words + " words, " + chars + " characters"; } function showStatusBarFunc() { textarea.style.height = "calc(100% - 18px)"; statusBar.style.display = ""; showStatusBar = true; updatestatusBar(); } function hideStatusBarFunc() { textarea.style.height = ""; statusBar.style.display = "none"; showStatusBar = false; } function toggleStatusBar() { if (showStatusBar) { hideStatusBarFunc(); } else { showStatusBarFunc(); } } textarea.addEventListener("input", function() { isModified = true; if (showStatusBar) { updatestatusBar(); } }); inputFile.addEventListener("change", function() { // Load file var file = inputFile.files[0], reader = new FileReader(); reader.onload = function() { newNote(reader.result, file.name); }; reader.readAsText(file); }); document.addEventListener("keydown", function(e) { // Shortcuts if (e.altKey &amp;&amp; e.shiftKey) { // Alt+Shift newNote(); } if (e.ctrlKey) { // Ctrl+ switch (e.keyCode) { case 79: // O e.preventDefault(); openNote(); break; case 83: // S e.preventDefault(); saveNote(); break; case 66: // B e.preventDefault(); toggleStatusBar(); break; case 191: // / e.preventDefault(); alert("Help note for " + appname + " will be added soon!"); break; } } if (e.keyCode == 9) { // Tab e.preventDefault(); var sStart = textarea.selectionStart, text = textarea.value; textarea.value = text.substring(0, sStart) + "\t" + text.substring(textarea.selectionEnd); textarea.selectionEnd = sStart + 1; } }); onunload = function() { // Save localStorage if (isModified) { localStorage.setItem("text", textarea.value); localStorage.setItem("name", filename); } else { // localStorage.clear(); localStorage.removeItem("text"); } localStorage.setItem("showStatusBar", showStatusBar); }; onload = function() { // Load localStorage if (localStorage.getItem("text")) { newNote(localStorage.getItem("text"), localStorage.getItem("name")); isModified = true; } else { newNote(); } showStatusBar = JSON.parse(localStorage.getItem("showStatusBar")); if (showStatusBar) { showStatusBarFunc(); } else { hideStatusBarFunc(); } }; </code></pre>
[]
[ { "body": "<p>The code is good. The only comment I have is that the data and its representation are highly coupled so it may be good idea to invest some time in separating them. But it will make sense only if this application will grow and evolve. Now it is very neat and good looking.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T06:40:36.203", "Id": "33693", "ParentId": "33637", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T06:47:53.410", "Id": "33637", "Score": "2", "Tags": [ "javascript" ], "Title": "Review of status bar code" }
33637
<p>I wrote this method that does the job and passes the assertion tests for a large java backend project but I'm not all happy with the way it reads, perhaps you can tell me how to refactor and/or improve this method?</p> <pre><code>public Set&lt;ProductOfferingJsonDto&gt; getJsonProductOfferings() { Set&lt;ProductOfferingJsonDto&gt; set = new HashSet&lt;ProductOfferingJsonDto&gt;(); ProductOfferingJsonDto pjson = null; Iterator iter = productOfferings.iterator(); while(iter.hasNext()){ ProductOfferingDto pdto = (ProductOfferingDto) iter.next(); if(pdto instanceof BundledProductOfferingDto) { Set&lt;ProductOfferingDto&gt; tmp = ((BundledProductOfferingDto) pdto).getProductOfferings(); Iterator piter = tmp.iterator(); Set&lt;ProductOfferingJsonDto&gt; tmpset = new HashSet&lt;ProductOfferingJsonDto&gt;(); while(piter.hasNext()){ SimpleProductOfferingDto piterdto = (SimpleProductOfferingDto) piter.next(); tmpset.add(new SimpleProductOfferingJsonDto(piterdto.getId(), piterdto.getName(), piterdto.getDescription(), piterdto.getStatus(), piterdto.getBrand(), piterdto.getValidFor(), piterdto.getProductSpecification(), piterdto.getDescriptorId(), piterdto.getTags(), piterdto.getProductOfferingPrice())); } BundledProductOfferingDto bpod = (BundledProductOfferingDto) pdto; pjson = new BundledProductOfferingJsonDto(bpod.getId(), bpod.getName(), bpod.getDescription(), bpod.getStatus(), bpod.getBrand(), bpod.getValidFor(), tmpset, bpod.getDescriptorId(), bpod.getTags(), bpod.getProductOfferingPrice()); } if(pjson != null) { set.add((ProductOfferingJsonDto) pjson); } } return set; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T13:57:45.977", "Id": "53906", "Score": "0", "body": "What's the problem of this code? Why you thing it is hard to reader and need refactor? You need a goal for reflector code, so other people can help you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T17:56:04.450", "Id": "53930", "Score": "0", "body": "@ZijingWu I think the code is difficult to understand what it does. I wanted to make it with smaller units that are more clear what they do. I'm converting between backend object and object suitable for JSON. The goal is to add a flad for leaf at leaf nodes and generated unique IDs over classes while IDs now are unique only within a class, therefore I'm making specific objects for the json requirement." } ]
[ { "body": "<p>You could add a factory method for SimpleProductOfferingJsonDto and BundledProductOfferingJsonDto which only takes a piterdto and a bpod object.</p>\n\n<p>It could look something like:</p>\n\n<pre><code>public Set&lt;ProductOfferingJsonDto&gt; getJsonProductOfferings() {\nSet&lt;ProductOfferingJsonDto&gt; set = new HashSet&lt;ProductOfferingJsonDto&gt;();\nProductOfferingJsonDto pjson = null;\nIterator iter = productOfferings.iterator();\nwhile(iter.hasNext()){\n ProductOfferingDto pdto = (ProductOfferingDto) iter.next();\n if(pdto instanceof BundledProductOfferingDto) {\n Set&lt;ProductOfferingDto&gt; tmp = ((BundledProductOfferingDto) pdto).getProductOfferings();\n Iterator piter = tmp.iterator();\n Set&lt;ProductOfferingJsonDto&gt; tmpset = new HashSet&lt;ProductOfferingJsonDto&gt;();\n while(piter.hasNext()){\n SimpleProductOfferingDto piterdto = (SimpleProductOfferingDto) piter.next();\n tmpset.add(new NewJSONSPOD(piterdto));\n}\n BundledProductOfferingDto bpod = (BundledProductOfferingDto) pdto;\n pjson = new NewJSONBPOD(bpod);\n if(pjson != null) {\n set.add((ProductOfferingJsonDto) pjson);\n }\n}\nreturn set;\n\npublic static BundledProductOfferingJsonDto NewJSONBPOD(BundledProductOfferingDto bpod) {\n return new BundledProductOfferingJsonDto(bpod.getId(), bpod.getName(), bpod.getDescription(), bpod.getStatus(),\n bpod.getBrand(), bpod.getValidFor(),\n tmpset,\n bpod.getDescriptorId(), bpod.getTags(), bpod.getProductOfferingPrice());\n}\n\npublic static SimpleProductOfferingJsonDto NewJSONSPOD(SimpleProductOfferingDto piterdto) {\n return new SimpleProductOfferingJsonDto(piterdto.getId(), piterdto.getName(), piterdto.getDescription(), piterdto.getStatus(),\n piterdto.getBrand(), piterdto.getValidFor(),\n piterdto.getProductSpecification(),\n piterdto.getDescriptorId(), piterdto.getTags(), piterdto.getProductOfferingPrice()));\n}\n</code></pre>\n\n<p>You might want to change some names etc, but you get the gist of it</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T08:05:51.530", "Id": "33640", "ParentId": "33639", "Score": "3" } }, { "body": "<p>I would move the construction of the JSON objects into factory methods like this:</p>\n\n<pre><code>public class BundledProductOfferingJsonDto\n{\n ....\n public static BundledProductOfferingJsonDto fromDto(BundledProductOfferingDto dto, Set&lt;ProductOfferingJsonDto&gt; productOfferings)\n {\n return new BundledProductOfferingJsonDto(dto.getId(), dto.getName(), dto.getDescription(), dto.getStatus(),\n dto.getBrand(), dto.getValidFor(),\n productOfferings,\n dto.getDescriptorId(), dto.getTags(), dto.getProductOfferingPrice());\n }\n}\n</code></pre>\n\n<p>Similar for <code>SimpleProductOfferingJsonDto</code></p>\n\n<p>Also, is there a reason why your are using the <code>while</code> loops with the iterators instead of for example <code>for (ProductOfferingDto piter : tmp)</code>?</p>\n\n<p>The method could then read something like this:</p>\n\n<pre><code>public Set&lt;ProductOfferingJsonDto&gt; getJsonProductOfferings() {\n Set&lt;ProductOfferingJsonDto&gt; set = new HashSet&lt;ProductOfferingJsonDto&gt;();\n ProductOfferingJsonDto pjson = null;\n for (ProductOfferingDto pdto : productOfferings) {\n if (pdto instanceof BundledProductOfferingDto) {\n Set&lt;ProductOfferingDto&gt; tmp = ((BundledProductOfferingDto) pdto).getProductOfferings();\n Set&lt;ProductOfferingJsonDto&gt; tmpset = new HashSet&lt;ProductOfferingJsonDto&gt;();\n for (ProductOfferingDto piter : tmp) {\n SimpleProductOfferingDto piterdto = (SimpleProductOfferingDto)piter;\n tmpset.add(SimpleProductOfferingJsonDto.fromDto(piterdto));\n }\n BundledProductOfferingDto bpod = (BundledProductOfferingDto) pdto;\n BundledProductOfferingJsonDto pjson = BundledProductOfferingJsonDto.fromDto(bpod, tmpset));\n set.add(pjson);\n }\n }\n return set;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T08:17:33.067", "Id": "53888", "Score": "0", "body": "I'm giving you an upvote. Even though we got the same answer (and mine slightly faster :P) I think your snippet reads better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T09:20:09.147", "Id": "53890", "Score": "0", "body": "@user1021726: hehe, funny, same idea :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T10:25:52.400", "Id": "53894", "Score": "1", "body": "You can eliminate the last if condition by putting `set.add(ProductOfferingJsonDto) pjson)` into the first condition, when the JSON instance is created. This would eliminate the need for json as well and so this method could be reduced to 15 lines." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T08:09:10.827", "Id": "33641", "ParentId": "33639", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T07:43:24.847", "Id": "33639", "Score": "2", "Tags": [ "java" ], "Title": "Converting between backend object and object suitable for JSON" }
33639
<p>Ever since reading Crockford's "Good Parts" and <a href="http://tddjs.com/" rel="nofollow">Johansen's TDD book</a>, I have wanted to use more of the <em>differential inheritance</em> pattern in my coding at work (as in avoiding <code>new</code> by using <code>Object.create()</code>), but I find that I am having a hard time argumenting for the clearness of the code when trying to make "types" that can be used for object creation. Most of my co-workers are "classically" inclined.</p> <p>I guess this question somehow boils down to these points</p> <ul> <li>downcasing/UpperCasing (i.e. "car" vs "Car")</li> <li>prefixing the base instances (i.e "prototypeCar"). This practice is for instance seen in the <a href="https://github.com/dilvie/fluentjs1/blob/master/fluent-javascript.js" rel="nofollow">code of the author of Fluent Javascript</a> </li> <li><p>init() methods VS factory methods. </p> <pre><code>// init style car.init = function(brand) { this.brand = brand; } myCar = Object.create(car).init("Nissan"); // versus // factory method function createCar(brand) { var o = Object.create(car); o.brand = brand; return o; } // alternative factory method function createCar(brand) { var o = Object.create(car, { brand : brand } ) return o; } myCar = createCar("nissan") </code></pre></li> </ul> <p>My problem with having lower cased <code>car</code> types is that for someone glancing over parts of the code, they might think that <code>car</code> is an instance of some kind of 'class' <code>Car</code>, and get confused when I suddenly start creating new instances from it. In my opinion, the notion of using a prefix, such as "prototype", seems to more clearly state my intentions with the instance. So do saying Car, but that implies that it should be used together with <code>new</code>, so one should perhaps refrain from that ... (?)</p>
[]
[ { "body": "<p>I see a conceptual issue with this approach: it is nice to inherit from objects, but these entities are not the \"real\" object. In other words, there is no much sense in using them outside of initialization code. If you need new <code>[Cc]ar</code> then it will not be wise to take any car that is nearby and just modify it and enjoy numerous side effects - you probably need some \"etalon\" of cars. The <code>Car</code>.</p>\n\n<p>To be honest, I frequently have an intention to use only factory methods in JavaScript and not use the operator <code>new</code> at all. But then I look on how many should I rewrite for that and give up because I do not see the real benefits from this approach - it is not a big task to rename the constructor <code>Something</code> to factory method <code>createSomething</code> and replace it within the code, but what is next?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T23:25:55.307", "Id": "53946", "Score": "0", "body": "Thanks for the reply. I see the point with regards to rewriting, but do you still follow through with it in new (pun intended) code? And which of the patterns do you end up using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T23:29:28.083", "Id": "53947", "Score": "0", "body": "In general I have yet to see much use of this way of structuring code for reuse. Usual mixins seem to be more prevalent as an alternative to the \"class\" style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T00:52:41.853", "Id": "53948", "Score": "0", "body": "Currently I'm trying to use the best tool for the task. I rely on the frameworks and common practices in the technology I use. For example, I like Angular directives and node.js modules. For internal logic I prefer functional style (I like pure functions very much in this area), for libraries I design OOP interfaces (I like DOM). Here is one of my recent code files: http://bit.ly/16U2K3b" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T00:53:06.573", "Id": "53949", "Score": "0", "body": "I actually afraid of mixins because this approach looks similar to multiple inheritance, which almost always is not a good idea. I cannot remember any situation when they will be an any use (maybe I just to not know them good enough to use them or never have to)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T19:35:15.930", "Id": "33672", "ParentId": "33646", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T12:47:05.417", "Id": "33646", "Score": "0", "Tags": [ "javascript", "inheritance", "prototypal-class-design" ], "Title": "Coding convention when using differential inheritance" }
33646
<p>Me and my colleagues do a small TDD-Kata practice everyday for 30 minutes. For reference this is the link for the excercise <a href="http://osherove.com/tdd-kata-1/" rel="nofollow">http://osherove.com/tdd-kata-1/</a> </p> <p>The objective is to write better code using TDD. This is my code which I've written</p> <pre><code> public class Calculator { public int Add( string numbers ) { const string commaSeparator = ","; int result = 0; if ( !String.IsNullOrEmpty( numbers ) ) result = numbers.Contains( commaSeparator ) ? AddMultipleNumbers( GetNumbers( commaSeparator, numbers ) ) : ConvertToNumber( numbers ); return result; } private int AddMultipleNumbers( IEnumerable getNumbers ) { return getNumbers.Sum(); } private IEnumerable GetNumbers( string separator, string numbers ) { var allNumbers = numbers .Replace( "\n", separator ) .Split( new string[] { separator }, StringSplitOptions.RemoveEmptyEntries ); return allNumbers.Select( ConvertToNumber ); } private int ConvertToNumber( string number ) { return Convert.ToInt32( number ); } } </code></pre> <p>and the tests for this class are</p> <pre><code> [TestFixture] public class CalculatorTests { private int ArrangeAct( string numbers ) { var calculator = new Calculator(); return calculator.Add( numbers ); } [Test] public void Add_WhenEmptyString_Returns0() { Assert.AreEqual( 0, ArrangeAct( String.Empty ) ); } [Test] [Sequential] public void Add_When1Number_ReturnNumber( [Values( "1", "56" )] string number, [Values( 1, 56 )] int expected ) { Assert.AreEqual( expected, ArrangeAct( number ) ); } [Test] public void Add_When2Numbers_AddThem() { Assert.AreEqual( 3, ArrangeAct( "1,2" ) ); } [Test] public void Add_WhenMoreThan2Numbers_AddThemAll() { Assert.AreEqual( 6, ArrangeAct( "1,2,3" ) ); } [Test] public void Add_SeparatorIsNewLine_AddThem() { Assert.AreEqual( 6, ArrangeAct( @"1 2,3" ) ); } } </code></pre> <p>Now I'll paste code which they have written </p> <pre><code> public class StringCalculator { private const char Separator = ','; public int Add( string numbers ) { const int defaultValue = 0; if ( ShouldReturnDefaultValue( numbers ) ) return defaultValue; return ConvertNumbers( numbers ); } private int ConvertNumbers( string numbers ) { var numberParts = GetNumberParts( numbers ); return numberParts.Select( ConvertSingleNumber ).Sum(); } private string[] GetNumberParts( string numbers ) { return numbers.Split( Separator ); } private int ConvertSingleNumber( string numbers ) { return Convert.ToInt32( numbers ); } private bool ShouldReturnDefaultValue( string numbers ) { return String.IsNullOrEmpty( numbers ); } } </code></pre> <p>and the tests</p> <pre><code> [TestFixture] public class StringCalculatorTests { [Test] public void Add_EmptyString_Returns0() { ArrangeActAndAssert( String.Empty, 0 ); } [Test] [TestCase( "1", 1 )] [TestCase( "2", 2 )] public void Add_WithOneNumber_ReturnsThatNumber( string numberText, int expected ) { ArrangeActAndAssert( numberText, expected ); } [Test] [TestCase( "1,2", 3 )] [TestCase( "3,4", 7 )] public void Add_WithTwoNumbers_ReturnsSum( string numbers, int expected ) { ArrangeActAndAssert( numbers, expected ); } [Test] public void Add_WithThreeNumbers_ReturnsSum() { ArrangeActAndAssert( "1,2,3", 6 ); } private void ArrangeActAndAssert( string numbers, int expected ) { var calculator = new StringCalculator(); var result = calculator.Add( numbers ); Assert.AreEqual( expected, result ); } } </code></pre> <p>Now the question is which one is better? </p> <p>My point here is that we do not need so many small methods initially because StringCalculator has no sub classes and secondly the code itself is so simple that we don't need to break it up too much that it gets confusing after having so many small methods.</p> <p>Their point is that code should read like english and also its better if they can break it up earlier than doing refactoring later and third when they will do refactoring it would be much easier to move these methods quite easily into separate classes. </p> <p>My point of view against is that we never made a decision that code is difficult to understand so why we are breaking it up so early. </p> <p>So the question is when is the good time to break up a code into smaller methods? </p> <ul> <li>Initially when you are writing the code</li> <li>Or when you look at the code and see it is difficult to read</li> </ul> <p>The reason I hesitate to choose option 1 because it will create so many methods initially which confuses me and I prefer to write it first, see if it is harder to read, then break it up. If it is a big block then I'll shift it into a separate class and break it up there.</p> <p>So I need a third person's opinion to understand which option is much better.</p>
[]
[ { "body": "<p>I think the code should be easily readable from the start. My goal is to avoid the need for comments. Your colleagues make great points about the advantages of such verbose code as well. Additionally, tools such as Resharper make it incredibly easily to restructure code so it's easily readable like this. </p>\n\n<p>The code that you wrote is definitely harder to read in my opinion. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T14:48:01.270", "Id": "53912", "Score": "0", "body": "I agree with you here that the ?: operator which I've used in Add method is making it a little harder to read. But this is my point here, after I've realized that this block is difficult to understand then I'll shift it to a separate method but not in the first place. The reason is, if we take their approach which is to create a separate method for almost everything then we get a lot of smaller methods which creates confusion. Wouldn't it better to extract that block to another class first and then refactor it there to create smaller methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T15:17:48.743", "Id": "53915", "Score": "1", "body": "Do you know that they created the separate method first, or if they performed an \"extract method\" refactoring (http://www.refactoring.com/catalog/extractMethod.html) after the fact? I tend to use both techniques depending on my knowledge of the code I'm writing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T15:21:48.803", "Id": "53916", "Score": "0", "body": "they performed \"extract method\" after writing the code. But still isn't it too early to extract a method just to make it read like english? because they do it for alomst each line because of Single Responsibility Principle. I am not saying they are doing wrong, I am asking isn't it too early? plus it will add so many small methods which will be difficult to handle. Why not after realizing that code is harder to read then shift the block into a class and then refactor it there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T15:38:36.160", "Id": "53918", "Score": "0", "body": "I don't think it's too early. The quicker you can make the code easier to read, the better. There's an extremely high likelihood that no one will have time to make it easier to read later. Plus, it's easier to perform an \"extract class\" refactoring if you've got a lot of methods to work with. Also, if necessary, you can always perform an \"inline method\" refactoring." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T16:13:40.627", "Id": "53920", "Score": "0", "body": "I Agree with @AlexDresko on this. It is better to write clean code early. I'd also like to add that it is much easier to refactor / clean up the code while the original meaning or idea is still fresh in your mind." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T14:28:11.297", "Id": "33652", "ParentId": "33649", "Score": "4" } } ]
{ "AcceptedAnswerId": "33652", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T13:20:36.537", "Id": "33649", "Score": "2", "Tags": [ "c#", "tdd" ], "Title": "How to write simple code using TDD" }
33649
<p>The problem is not very complicated (I mean it is easy to solve it), but the question is how to make it in the easiest way (Java)</p> <p>Input String: </p> <pre><code>String inputString = "[value=20][param=304.2][indicator=1500]"; </code></pre> <p>Expected output: array of <code>double</code>s : [20.0][304.2][1500.0]</p> <p>Sample solution:</p> <pre><code>String[] chunks = inputString.split("="); String valueStr = chunks[1].substring(0, chunks[1].indexOf(']')); String paramStr = chunks[2].substring(0, chunks[2].indexOf(']')); String indicatorStr = chunks[3].substring(0, chunks[3].indexOf(']')); // parsing by Double.parseDouble forming an array and returning it as a result. </code></pre> <p>What other (smarter) way would you propose using Java?</p>
[]
[ { "body": "<p>Don't know if using regex is overkill, but it does open up for a fairly concise and (in my opinion) readable solution.</p>\n\n<pre><code>public class ArgumentParser {\n public static final Pattern KEY_VALUE_PATTERN = Pattern.compile(\"\\\\[([a-zA-Z]+)=(-?\\\\d+\\\\.?\\\\d*)\\\\]\");\n\n public Map&lt;String, Double&gt; parse(String str) {\n Map&lt;String, Double&gt; values = new HashMap&lt;&gt;();\n\n Matcher matcher = KEY_VALUE_PATTERN.matcher(str);\n while (matcher.find()) {\n String key = matcher.group(1);\n Double value = Double.parseDouble(matcher.group(2));\n values.put(key, value);\n }\n\n return values;\n }\n}\n</code></pre>\n\n<p>Edit: The question did ask for an array of doubles to be returned, but that should be trivial to obtain once the parsing is done. Alternatively the parse-method could be modified to only extract the values.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T22:40:10.763", "Id": "61280", "Score": "0", "body": "The regular expression should probably allow an optional negative sign." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T13:15:33.987", "Id": "61380", "Score": "0", "body": "Good point. I've updated the answer to allow for this." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T14:29:20.893", "Id": "33653", "ParentId": "33650", "Score": "6" } }, { "body": "<p>Aside from the <em>easiest</em> code, you might want to consider <em>correct</em> and <em>robust</em> code.</p>\n\n<p>Assume following input: <code>[ param=40.2] [foobar =20] junk [=1500]</code>. Your code will actually parse this, even though that is likely to be wrong. You have to test if the input actually conforms to a certain format. During parsing, you throw away the information from the labels like <code>param</code>, and rather rely on the order. If you don't check for validity, and the format changes unexpectedly, you'll have hard to trace bugs.</p>\n\n<p>I would suggest you parse the data into a <code>Map&lt;String, Double&gt;</code>. The parsing can easily be done by regexes, e.g. the pattern <code>\\G \\s*\\[\\s* ([^=]+) \\s*=\\s* ([^\\]]*) \\s*\\]\\s*</code> (spaces are insignificant – use the <code>Pattern.COMMENTS</code> flag). This is laxer than your <code>substr</code> parsing, but is able to reject malformed input. This also asserts that the matches are adjacent, so no junk will be in between.</p>\n\n<p>Next, you iterate through all matches, updating the <code>Map</code> each time. The regex does not attempt to parse valid doubles – I'd let possible <code>NumberFormatException</code>s from <code>Double.parseDouble(...)</code> bubble up. Likewise, you should complain when the parsed data does not contain <code>value</code>, <code>param</code> and <code>indicator</code> fields. Note that this is a semantic constraint that should be tested <em>after</em> the parsing.</p>\n\n<p>I won't show a reimplementation taking these points into consideration because BjoernH's answer already implements the relevant points.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T14:45:30.290", "Id": "33654", "ParentId": "33650", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T13:49:10.710", "Id": "33650", "Score": "2", "Tags": [ "java", "strings", "parsing" ], "Title": "Retrieving doubles from string - simple problem" }
33650
<p>I have the following tables: </p> <pre><code> player | id | name | surname | |:-----------|------------:|:------------:| | 1001 | Mike | Tyson | | 2001 | John | Carlin | | 3001 | Dan | StanH | | 4001 | Alen | Derl | person | id | name | surname | |:-----------|------------:|:------------:| | 1001 | Mike | Tyson | | 2001 | Pirlon | Austin | | 6001 | Danly | StanH | | 4001 | Alen | Derl | </code></pre> <p>I want create an SQL query in order to get the same records of the above schemes and print first and last name.</p> <p>The query is </p> <pre><code>SELECT player.name, player.surname FROM player INNER JOIN person on player.id = person.id AND player.name = person.name AND player.surname = person.surname; </code></pre> <p>Is there any way to create a more efficient query?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T16:35:55.140", "Id": "53922", "Score": "1", "body": "I would consider, if possible, normalizing the database a touch so you don't have this repetition of data, and being forced to write queries like this. Having a table of 'Players' that instead just has a PlayerID and a foreign key PersonID would be a lot better and cause less issues." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T01:05:14.123", "Id": "56900", "Score": "0", "body": "It is as good as you can get in terms of SQL. Now the efficiency is a subject for many other factors: RDBMS you're actually using, if it is MySQL what engine is being used, actual table schemas, what indices you have, cardinality for both tables etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T10:00:54.603", "Id": "56921", "Score": "0", "body": "Actually, finding the same records between those two tables, was just a simple task I was asked. I just figured out the query. Considering that inner join is a kind of \"expensive\" operation, I was wondering if there is a more efficient way, in terms of sql query." } ]
[ { "body": "<p>SQL is made to function on Joins, I wouldn't say that they are &quot;kind of &quot;expensive&quot; operation&quot; RDMS databases are made to relate to other tables. if you had Primary and Foreign Keys set up and/or even indexes then it shouldn't be an &quot;expensive operation&quot;.</p>\n<p><strong>edit</strong></p>\n<p>here is the best query for what you are trying to accomplish.</p>\n<pre><code>SELECT player.name, player.surname \nFROM player INNER JOIN person ON player.id = person.id\nWHERE player.id = person.id\n AND player.name = person.name\n AND player.surname = person.surname\n</code></pre>\n<p>This is the write way to write the code, it's clean and straight forward to what is going on. your code essentially is doing the exact same thing, but is bad coding practice from my point of view.</p>\n<p><a href=\"http://www.sqlfiddle.com/#!6/3edd7/4/0\" rel=\"nofollow noreferrer\">SQL Fiddle Statistics and running code</a></p>\n<p><a href=\"http://www.sqlfiddle.com/#!6/3edd7/5\" rel=\"nofollow noreferrer\">SQL Fiddle Statistics for your code</a></p>\n<p>(it actually looks like the execution is the same.)</p>\n<p>I need to Note that both this query and the query that you are using join the two tables on their id columns. this is an issue because there is 1 id that holds different values in either table. so those id columns mean two totally separate things and shouldn't be joined on in all reality.</p>\n<p>example:</p>\n<blockquote>\n<p>player table</p>\n<p>| 2001 | John | Carlin |</p>\n</blockquote>\n<p>AND</p>\n<blockquote>\n<p>person table</p>\n<p>| 2001 | Pirlon | Austin |</p>\n</blockquote>\n<p>in this specific instance the where statement covers the id being different, in this one case. <strong>BUT YOU NEED TO BE AWARE THIS IS BAD DATA</strong> you should fix the database.</p>\n<p>Sorry to say but the <code>INTERSECT</code> query that has been suggested actually takes longer and has more operations attached to it then both your original code and the code I posted.</p>\n<p><a href=\"http://www.sqlfiddle.com/#!6/3edd7/6\" rel=\"nofollow noreferrer\">SQL Fiddle from jmoreno's answer</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T16:25:44.023", "Id": "57513", "Score": "0", "body": "This query returns ERROR: more than one row returned by a subquery used as an expression. Maybe you meant 'in' instead of '=' in your query. I like your query, but assuming that id is not the primary key, (so there is not primary key at all) does this query return a valid output?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T19:07:07.640", "Id": "57529", "Score": "0", "body": "Yes i meant `in`, my bad. It will provide valid informating if both tables hold exactly the same information in these columns for each ID. I will edit the question when i get to a laptop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T05:29:06.563", "Id": "57572", "Score": "0", "body": "I fixed that query in my post. and like I said it will return valid information. if the information is the same in the both tables. then it will also be correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T06:25:02.750", "Id": "57592", "Score": "1", "body": "Sample data clearly shows that ID is insufficient for a match. But I do agree with your comment on joins." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T06:30:51.757", "Id": "57593", "Score": "0", "body": "@jmoreno, I can't believe that I didn't look close enough at the sample input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T10:47:21.943", "Id": "57629", "Score": "0", "body": "Very analytical and straightforward answer. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T17:45:54.920", "Id": "57659", "Score": "0", "body": "@istovatis, you are welcome" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-15T19:07:24.527", "Id": "35447", "ParentId": "33657", "Score": "1" } }, { "body": "<p>The efficiency of a join is primarily based upon covering indexes, not number of columns used. Given your scenario, you basically have the right idea.</p>\n\n<p>You don't mention which RDBMS you are using, but you could possibly use the <a href=\"http://technet.microsoft.com/en-us/library/ms188055.aspx\" rel=\"nofollow\">INTERSECT</a> command.</p>\n\n<pre><code>Select id, name, surname\nFrom player\nIntersect\nSelect id, name, surname\nFrom person\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T06:40:27.607", "Id": "57604", "Score": "0", "body": "nice I was working on redoing my answer..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T06:45:20.650", "Id": "57606", "Score": "0", "body": "@Malachi: I mainly answered because there's a non-join approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T06:47:23.337", "Id": "57607", "Score": "0", "body": "I think I might have another. but that looks good too. but I think I might be able to come up with something else as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T07:13:13.077", "Id": "57616", "Score": "0", "body": "your code takes longer to run and has more associated with it than the original posters code... [SQLFiddle](http://www.sqlfiddle.com/#!6/3edd7/6) your code actually forces a left semi join, then a quicksort which draws attention and resources." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T07:24:26.657", "Id": "57618", "Score": "0", "body": "Adding an index should even that out a bit. http://www.sqlfiddle.com/#!6/d2b3d/1. But it conveys the intent better, which lacking a performance bottle neck, I would prefer over both size and speed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T07:31:08.350", "Id": "57619", "Score": "0", "body": "still slower, and on bigger tables, bigger databases this will compound. this is being measured on two tables with 3 columns and 4 rows each. and the difference is 2 ms . if these were real tables (which I hope they would have indexes and keys, and not have redundant data) then there would be much more information and that 2 ms will be a lot more, a lot. and it still uses a `JOIN`, not an `INNER JOIN`, but still a `JOIN` because that is how SQL works, on Joins" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T17:04:41.947", "Id": "57656", "Score": "0", "body": "performance is relevant, and Simplicity is relevant as well. the Simple Query shows exactly what is needed and runs fast and efficiently. there isn't any need for a `CTE` or `union` or `INTERSECT` and the Query that you provided in that fiddle returns duplicates, and uses more system resources, based on that execution plan. I could be wrong but the way I figure it the more stuff showing on the execution plan the more resources are being used. if you continue to use expensive queries like that when it isn't necessary it will not be good for the server." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T06:39:37.947", "Id": "35520", "ParentId": "33657", "Score": "1" } } ]
{ "AcceptedAnswerId": "35447", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T15:37:58.743", "Id": "33657", "Score": "1", "Tags": [ "optimization", "sql" ], "Title": "Same records between two tables" }
33657
<p>Wanted some opinions on something I have been working with, I've tried a few ways of structuring the way I retrieve and return data to my WebAPI, and I'm pretty happy with what I have so far, but I was looking for a comparison of the pro's and con's of using models vs entities for returning data on the WebAPI.</p> <p>In my opinion, from what I've seen, adding a model factory and returning models is good because you get control over what your object looks like, but it does mean you now have to map the entities to that model somewhere, increasing the code you have to write, particularly if you have a lot of entities.</p> <p>On the other hand, having partial classes of the generated objects allows me the same extensibility, and by adding a meta data class using <code>MetadataType(typeof(typename))</code>, I am able to decide what will be serialized and how they are built, giving me full control again over the structure, and being able to extend it when I want to, rather than having to for every entity.</p> <p>So, if I can get the same benefits with partials and metadata, without the additional code in mapping to models, what are other downsides, how come this approach is not as common? I mean, if I wanted I could do the mapping this way too, without the need for any factories to do the mapping, just by attributing the fields to be ignored and creating new ones with Get/Set to point to the original property.</p> <p>An example:</p> <p>Generated by T4 template:</p> <pre><code> public partial class FileHeader : BaseEntity { public FileHeader() { this.FileVersionSubs = new HashSet&lt;FileVersion&gt;(); } public int FileId { get; set; } public string Name { get; set; } public string Caption { get; set; } public virtual ICollection&lt;FileVersion&gt; FileVersionSubs { get; set; } } </code></pre> <p>The partial I make:</p> <pre><code>[MetadataType(typeof(FileHeaderMetaData))] public partial class FileHeader { // Additional fields go here } </code></pre> <p>Metadata file:</p> <pre><code>public class FileHeaderMetaData { // Any attributes for existing fields here, eg: [MyCustomAttribute] public int FileId { get; set; } } </code></pre> <p>If I were to approach this from a Model point of view, I would be repeating the same properties for every class I generate and wanted to return as well as mapping them, rather than the ones I explicitly want to change or hide.</p> <p>Thoughts, feelings and suggestions welcome!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T16:48:35.307", "Id": "54121", "Score": "0", "body": "What about a *generic solution*: If I am getting you right, your (view-)models would be stripped down versions of your (database-)entities, so why not writing a generic Mapper class, which maps per reflection the one to the other. done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T17:05:40.730", "Id": "54127", "Score": "0", "body": "I suppose if we boil it down to it's simplest: With the above structure for partials & meta-data, are view models even required?" } ]
[ { "body": "<p>No matter how simple I think my application is going to be, I always end up separating my viewmodels from my entities. Not only do I <strong>always</strong> encounter at least one case where the apparent convenience of any other approach makes it very unwieldly for me to finish a feature, but it's also good to practice loose coupling between your views and your domain.</p>\n\n<p>Say you're using entities with partial classes directly in your views, and the same entity is used in multiple views. Now you have a new feature that requires a change to your entities. How do you know it won't break your existing views? The compiler won't catch it, unless you have an automated suite of UI tests, you'll need to remember to manually test every screen again.</p>\n\n<p>Instead, if you create one viewmodel per view, you get the following advantages:</p>\n\n<ol>\n<li>Each viewmodel can be constructed to meet the needs of a single view. Don't need to some properties of an entity? Leave it out of the viewmodel! Want to include a few extra properties? Throw them in! Want to flatten out some entity hierarchy because it will be easier to display? Do it! </li>\n<li>Some (but not all) breaking changes you make to your entities will now be detected by your compiler. Even if you have unit tests (and you should), this is a nice reminder. </li>\n<li>Factories are much easier to test than views.</li>\n</ol>\n\n<p>In summary, the viewmodel should be the simplest representation of what the view needs, and no more. This decouples your entities from your views as well as decouples your views from each other. It also places mode code where it can be easily tested and maintained. It is a little more work initially but a lot less work in the long run.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T20:57:57.660", "Id": "54650", "Score": "0", "body": "This particular project, the views are built from metadata returned from the WebAPI and that data can differ depending on what is requesting it, this is done via attributes on the metadata class that controls what is serialized. Thank you for the response though, I think in most other projects I would agree" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T19:28:05.650", "Id": "33880", "ParentId": "33659", "Score": "4" } }, { "body": "<p>Honestly, because the entity gets serialized, and you can control the fields that get serialized, you're building a view model on the fly during serialization. In your solution there's no good reason not to use that approach.</p>\n\n<p>Now, if your entity model were in a different tier, and you needed to add some more data points from other sources, then you would end up building a view model in what we'd call the middle-tier. This is very common in large organizations; I know because I have to do it a lot.</p>\n\n<p>So, my advice for you, stick with the approach of attributing and extending the entity model because you have that luxury. It's very elegant, efficient, and reduces code; all very good things!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T20:58:31.303", "Id": "54651", "Score": "1", "body": "Thanks for the response, it does seem like a good solution for a webapi project, because of the complete seperation of concerns and dependancies" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T13:04:08.883", "Id": "33927", "ParentId": "33659", "Score": "3" } } ]
{ "AcceptedAnswerId": "33927", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T16:31:10.070", "Id": "33659", "Score": "6", "Tags": [ "c#", "asp.net", "api" ], "Title": "WebAPI - Return models vs entity and partial class with meta data" }
33659
<p>This is a query to return search results, but I feel it could be cleaned up a little. I just don't know how. </p> <pre><code>var queryResult = (from r in dc.Retailers where (string.IsNullOrEmpty(firstName) || SqlFunctions.PatIndex(firstName.Trim(), r.FirstName.Trim()) &gt; 0) &amp;&amp; (string.IsNullOrEmpty(lastName) || SqlFunctions.PatIndex(lastName.Trim(), r.LastName.Trim()) &gt; 0) &amp;&amp; (string.IsNullOrEmpty(companyName) || SqlFunctions.PatIndex(companyName.Trim(), r.CompanyName.Trim()) &gt; 0) &amp;&amp; (string.IsNullOrEmpty(phone) || SqlFunctions.PatIndex(phone.Trim(), r.Phone.Trim()) &gt; 0) &amp;&amp; (string.IsNullOrEmpty(email) || SqlFunctions.PatIndex(email.Trim(), r.Email.Trim()) &gt; 0) &amp;&amp; (string.IsNullOrEmpty(city) || SqlFunctions.PatIndex(city.Trim(), r.City.Trim()) &gt; 0) &amp;&amp; (string.IsNullOrEmpty(zip) || SqlFunctions.PatIndex(zip.Trim(), r.Zip.Trim()) &gt; 0) &amp;&amp; (string.IsNullOrEmpty(state) || SqlFunctions.PatIndex(state.Trim(), r.State.Trim()) &gt; 0) &amp;&amp; (string.IsNullOrEmpty(country) || SqlFunctions.PatIndex(country.Trim(), r.Country.Trim()) &gt; 0) select r ); </code></pre> <p>Update: For those confused by the query. Here is another version, which is probably better because it only builds the where parts when necessary. But I would still like to reduce the repetition. </p> <pre><code>var queryResult = (from r in dc.Retailers select r); if (!string.IsNullOrEmpty(firstName)) queryResult = queryResult.Where(ex =&gt; SqlFunctions.PatIndex(firstName.Trim(), ex.FirstName.Trim()) &gt; 0); if (!string.IsNullOrEmpty(lastName)) queryResult = queryResult.Where(ex =&gt; SqlFunctions.PatIndex(lastName.Trim(), ex.LastName.Trim()) &gt; 0); if (!string.IsNullOrEmpty(companyName)) queryResult = queryResult.Where(ex =&gt; SqlFunctions.PatIndex(companyName.Trim(), ex.CompanyName.Trim()) &gt; 0); if (!string.IsNullOrEmpty(phone)) queryResult = queryResult.Where(ex =&gt; SqlFunctions.PatIndex(phone.Trim(), ex.Phone.Trim()) &gt; 0); if (!string.IsNullOrEmpty(email)) queryResult = queryResult.Where(ex =&gt; SqlFunctions.PatIndex(email.Trim(), ex.Email.Trim()) &gt; 0); if (!string.IsNullOrEmpty(city)) queryResult = queryResult.Where(ex =&gt; SqlFunctions.PatIndex(city.Trim(), ex.City.Trim()) &gt; 0); if (!string.IsNullOrEmpty(zip)) queryResult = queryResult.Where(ex =&gt; SqlFunctions.PatIndex(zip.Trim(), ex.Zip.Trim()) &gt; 0); if (!string.IsNullOrEmpty(country)) queryResult = queryResult.Where(ex =&gt; SqlFunctions.PatIndex(country.Trim(), ex.Country.Trim()) &gt; 0); if (!string.IsNullOrEmpty(state)) queryResult = queryResult.Where(ex =&gt; SqlFunctions.PatIndex(state.Trim(), ex.State.Trim()) &gt; 0); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T16:44:22.307", "Id": "53923", "Score": "1", "body": "What is the point of the query? It looks like, for each field, you're searching for Retailers where the field is null or empty OR is not null or empty... which doesn't make sense." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T16:58:01.470", "Id": "53924", "Score": "1", "body": "It only filters by a search criteria if a value exists. For example. If you type in a state, it will only filter by state. If you type in a state and a zip, it will filter by both." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T18:02:04.430", "Id": "53932", "Score": "0", "body": "I think I'd exploit the fact that `IQueryable<T>` can be \"built\" from multiple chained calls, ie make a function that takes and returns an `IQueryable` for each search criteria." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T18:11:14.830", "Id": "53933", "Score": "0", "body": "You want to be careful while trying to refactor this code. You may end up writing code which does filtering on the client side instead of doing it in the database. Because you have all these local variables, it will be hard to make it more generic. Look in to PredicateBuilder -http://www.albahari.com/nutshell/predicatebuilder.aspx class to help you build this more dynamically if you were to get rid of the local variables." } ]
[ { "body": "<p>Apply the common refactoring used for repeated code: extracting a method. In your case, creating the method won't be trivial, because you want to create a different <code>Expression</code> each time. That is, unless you use <a href=\"http://www.albahari.com/nutshell/linqkit.aspx\" rel=\"nofollow\">LINQKit</a>:</p>\n\n<pre><code>public static IQueryable&lt;T&gt; WhereEqualsByPatIndex&lt;T&gt;(\n this IQueryable&lt;T&gt; query, string value, Expression&lt;Func&lt;T, string&gt;&gt; propertyExpression)\n{\n if (string.IsNullOrEmpty(value))\n return query;\n\n return query.Where(\n ex =&gt; SqlFunctions.PatIndex(\n value.Trim(), propertyExpression.Invoke(ex, propertyExpression).Trim()) &gt; 0);\n}\n</code></pre>\n\n<p>Usage would be like this (that call to <code>AsExpandable()</code> is important):</p>\n\n<pre><code>dc.Retailers\n .AsExpandable()\n .WhereEqualsByPatIndex(firstName, ex =&gt; ex.FirstName)\n .WhereEqualsByPatIndex(lastName, ex =&gt; ex.LastName)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T19:53:22.133", "Id": "54163", "Score": "0", "body": "Great answer. I did not know about AsExpandable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T20:16:54.993", "Id": "54165", "Score": "1", "body": "@SolutionYogi Regarding [your suggested edit](http://codereview.stackexchange.com/review/suggested-edits/13870): without the call to `AsExpandable()`, the code would throw an exception, saying that EF doesn't understand the expression. There are some cases where doing things incorrectly results in performing the filtering on the client, but this is not one of them." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T19:34:00.877", "Id": "33753", "ParentId": "33661", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T16:35:59.187", "Id": "33661", "Score": "1", "Tags": [ "c#", "linq" ], "Title": "Is there a way to eliminate the repetition in this linq query?" }
33661
<p>I want to return a list of the values from the binary tree. Is there a shorter and more efficient way to write the method for numbers?</p> <pre><code>class BTNode(object): """A node in a binary tree.""" def __init__(self, item, left=None, right=None): """(BTNode, object, BTNode, BTNode) -&gt; NoneType Initialize this node to store item and have children left and right, as well as depth 0. """ self.item = item self.left = left self.right = right self.depth = 0 # the depth of this node in a tree def number(self: 'BTNode') -&gt; list: lst = [] if self.right is None and self.left is None: lst.append(self.item) else: lst.append(self.item) if self.left: left = self.left.number() lst.extend(left) if self.right: right = self.right.number() lst.extend(right) return lst </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-28T18:56:02.867", "Id": "63651", "Score": "0", "body": "I think `number` would be better named `enumerate`." } ]
[ { "body": "<ol>\n<li><p>There is no docstring for the <code>number</code> method.</p></li>\n<li><p>There are no test cases. This kind of code would be an ideal opportunity to write some <a href=\"http://docs.python.org/3/library/doctest.html\" rel=\"nofollow\">doctests</a>.</p></li>\n<li><p>The <code>depth</code> property is always 0. This seems useless.</p></li>\n<li><p>The method name <code>number</code> is misleading. (It does not return a number.) I would call it something like <code>flattened_pre_order</code> because it <em>flattens</em> the tree into a list using <a href=\"https://en.wikipedia.org/wiki/Tree_traversal#Pre-order\" rel=\"nofollow\"><em>pre-order traversal</em></a>.</p></li>\n<li><p>The variable name <code>lst</code> is misspelt. Better to call it something like <code>result</code>.</p></li>\n<li><p>This code:</p>\n\n<pre><code>if self.right is None and self.left is None:\n lst.append(self.item)\nelse:\n lst.append(self.item)\n</code></pre>\n\n<p>can be replaced with:</p>\n\n<pre><code>lst.append(self.item)\n</code></pre>\n\n<p>since it doesn't matter whether the condition is true or false.</p></li>\n<li><p>There's quite a lot of copying going on in the traversal of the tree: each time you call <code>a.extend(b)</code>, Python has to copy out the list <code>b</code>. This copying causes the traversal of a tree with <em>n</em> nodes to take O(<em>n</em><sup>2</sup>) time instead of O(<em>n</em>). See below for a way to avoid this copying.</p></li>\n<li><p>You use recursion to visit the child nodes, which means that traversing a very deep tree will exceed Python's maximum recursion depth:</p>\n\n<pre><code>&gt;&gt;&gt; n = None\n&gt;&gt;&gt; for i in range(1000): n = BTNode(i, n)\n... \n&gt;&gt;&gt; n.number()\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"cr33662.py\", line 22, in number\n left = self.left.number()\n [... many lines omitted ...]\nRuntimeError: maximum recursion depth exceeded\n</code></pre>\n\n<p>The way to avoid this is to maintain your own stack, like this:</p>\n\n<pre><code>def flattened_pre_order(self: 'BTNode') -&gt; list:\n \"\"\"Return a list of items in the tree rooted at this node, using\n pre-order traversal.\n\n &gt;&gt;&gt; tree = BTNode(1, BTNode(2, None, BTNode(3)), BTNode(4))\n &gt;&gt;&gt; tree.flattened_pre_order()\n [1, 2, 3, 4]\n &gt;&gt;&gt; node = BTNode(9999)\n &gt;&gt;&gt; for i in range(9998, -1, -1): node = BTNode(i, node)\n &gt;&gt;&gt; node.flattened_pre_order() == list(range(10000))\n True\n\n \"\"\"\n result = []\n stack = [self]\n node = None\n while stack:\n if node is None:\n node = stack.pop()\n if node is not None:\n result.append(node.item)\n stack.append(node.right)\n node = node.left\n return result\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T10:35:32.690", "Id": "33701", "ParentId": "33662", "Score": "4" } }, { "body": "<p>Rather than building up a list and returning it, consider implementing a <a href=\"http://docs.python.org/2/library/stdtypes.html#generator-types\" rel=\"nofollow\">generator</a> instead. Then you could \"yield\" each <code>self.item</code>. If the result is going to be processed one at a time and the result is a very long list you save the expense of building up that long list.</p>\n\n<pre><code>def __iter__(self):\n ''' Pre-order iterator '''\n yield self.item\n if self.left:\n for item in self.left:\n yield item\n if self.right:\n for item in self.right:\n yield item\n</code></pre>\n\n<p>Furthermore, you can easily reimplement the original function by taking advantage of the generator:</p>\n\n<pre><code>def number(self: 'BTNode') -&gt; list:\n ''' Pre-order traversal '''\n return list(self)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-28T15:49:55.583", "Id": "38225", "ParentId": "33662", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T18:09:45.487", "Id": "33662", "Score": "6", "Tags": [ "python", "tree", "python-3.x", "depth-first-search" ], "Title": "Returning a list of the values from the binary tree" }
33662
Portable Document Format (PDF) is an open standard for electronic document exchange maintained by the International Organization for Standardization (ISO). Questions can be about creating, reading, editing PDFs using different languages.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T18:32:23.530", "Id": "33664", "Score": "0", "Tags": null, "Title": null }
33664
Least Recently Used (LRU) is a family of caching algorithms. Please use the "cache" tag instead.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T19:23:21.703", "Id": "33667", "Score": "0", "Tags": null, "Title": null }
33667
In mathematics, a matrix (plural matrices) is a rectangular array of numbers, symbols, or expressions, arranged in rows and columns. The individual items in a matrix are called its elements or entries.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T19:32:13.043", "Id": "33669", "Score": "0", "Tags": null, "Title": null }
33669
A programming idiom is a way to overcome a programming language limitation and/or to write commonly-used code with a purpose that is separated from a literal meaning of the code. Also, an idiom is a preferred way to write code, when there is more than one obvious way to do it.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T19:35:15.277", "Id": "33671", "Score": "0", "Tags": null, "Title": null }
33671
<h3>Description</h3> <p>A finite-state machine (FSM), or simply a state machine, is a mathematical model of computation. It is an abstract machine that can be in exactly one of a finite number of states at any given time. The FSM can change from one state to another in response to some external inputs; the change from one state to another is called a transition. An FSM is defined by a list of its states, its initial state, and the conditions for each transition.</p> <h3>Flow</h3> <p>A state machine runs typically as run-to-completion. Such scheduling is a scheduling model in which each task runs until it either finishes, or explicitly yields control back to the scheduler. Run to completion systems typically have an event queue which is serviced either in strict order of admission by an event loop, or by an admission scheduler which is capable of scheduling events out of order, based on other constraints such as deadlines.</p> <h3>Usage</h3> <p>In addition to their use in modeling reactive systems presented here, finite state machines are significant in many different areas, including electrical engineering, linguistics, computer science, philosophy, biology, mathematics, and logic. Finite state machines are a class of automata studied in automata theory and the theory of computation. In computer science, finite state machines are widely used in modeling of application behavior, design of hardware digital systems, software engineering, compilers, network protocols, and the study of computation and languages.</p> <h3>Representations</h3> <p>Common representations and frameworks for building state machines include state/event tables, UML machines, SDL machines, Mealy machines and Moore machines.</p> <h3>Links</h3> <ul> <li><a href="https://en.wikipedia.org/wiki/Finite-state_machine" rel="nofollow noreferrer">Finite State Machine</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-11-01T19:38:11.120", "Id": "33673", "Score": "0", "Tags": null, "Title": null }
33673
A state machine is a model for designing systems which change based upon their current state and what input they receive.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T19:38:11.120", "Id": "33674", "Score": "0", "Tags": null, "Title": null }
33674
<p>I've looked at <code>boost::exception</code> and realized it is too advanced for my project, as my colleagues mostly have legacy C background. I do not need arbitrarily complex information in exception, just some error messages and trace info that can be written to process log.</p> <p>Someone on Stack Overflow <a href="https://stackoverflow.com/questions/8481147/if-you-catch-an-exception-by-reference-can-you-modify-it-and-rethrow">wrote such code</a> as an example, but his solution can <code>throw</code> while trying to insert additional exception info (looks dangerous to me, correct me if I am wrong).</p> <p>I tried to avoid using anything that can <code>throw</code> (vector of strings) inside the exception object. See: <a href="http://ideone.com/a6Ope7" rel="nofollow noreferrer">usage example</a>.</p> <p>Your feedback in term of correctness, ease of use, and required additional functionality is welcome.</p> <pre><code>const unsigned int long_enough = 512; class my_exception : public exception { std::array&lt;char, long_enough&gt; err; std::array&lt;char, long_enough&gt;::iterator insertion_point; public: template &lt;typename Iter&gt; void append(Iter first, Iter last) noexcept { //Remember null terminator! auto space_left = std::distance(insertion_point, err.end()); if (std::distance(first, last)&gt;=space_left){ last = first + (space_left - 1); } insertion_point = copy(first, last, insertion_point); } void append(const char msg[]) noexcept { append(msg, msg+strlen(msg)); } my_exception(const char msg[]) noexcept { insertion_point = err.begin(); append(msg, msg+strlen(msg)); } virtual const char* what() const noexcept override{ return err.data(); } }; </code></pre>
[]
[ { "body": "<p>A note on the <a href=\"https://stackoverflow.com/questions/8481147/if-you-catch-an-exception-by-reference-can-you-modify-it-and-rethrow\">the link</a> you posted; the OP was asking a hypothetical question in regards to what happens ('under the hood') to the call stack/exception/etc. if the exception that is caught is of a reference type (i.e. <code>catch (std::exception&amp; e)</code> vs <code>catch (const std::exception&amp; e)</code>). As was answered there, yes it is not a good idea to modify the exception within a catch (though completely legal code, still not advised). </p>\n\n<p>Per your code, there are a couple of things worth noting:\nchanging your <code>err</code> type from a <code>std::array&lt;char, long_enough&gt;</code> to a <code>std::string</code> would simplify all of your code, also, while you can pass a <code>const char[]</code> into functions, it decays into a pointer (pointing to the first element in the array), so it's similar to just <code>const char*</code>, if you're intent WAS to pass in a reference to a <code>char[]</code>, it's recommended you pass a const size, as in <code>template&lt;int N&gt; someFn(const char (&amp;x)[N])</code>, otherwise stack issues can occur. As well, if you're working with C++, unless you have a specific need to use a <code>char[]</code> (which is possible) it's advised to use a <code>std::string</code> over a <code>char[]</code>.</p>\n\n<p>Lastly, while having an <code>append</code> function to add aditional information into your exception object could be useful, it's usually better to derive a specific exception from your base exception with specific information in it (or otherwise just put the needed information in your <code>throw exception...</code>). Here's you're exception class with the <code>err</code> variable being a <code>std::string</code></p>\n\n<pre><code>class my_exception : virtual public std::exception {\nprivate:\n std::string err;\npublic:\n void append(std::string::iterator first, std::string::iterator last) {\n err.append(first, last);\n }\n void append(const char* msg) {\n err.append(msg);\n }\n my_exception(const char* msg) noexcept : err(msg) {}\n virtual const char* what() const throw() {\n return err.c_str();\n }\n};\n</code></pre>\n\n<p>Use it like such:</p>\n\n<pre><code>try {\n throw my_exception(\"here's a simple message\");\n} catch (std::exception e) {\n e.append(\"...added some text\");\n std::cout &lt;&lt; \"error: \" &lt;&lt; e.what() &lt;&lt; std::endl;\n // or printf(\"error: %s\\n\", e.what()) for your C friends\n}\n</code></pre>\n\n<p>As a side note (and for reference), here is the exception code from part of an open source framework I'm working on (just in a single header file exception.hpp):</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;exception&gt;\n#include &lt;string&gt;\n\nnamespace your_namespace {\n class exception : virtual public std::exception {\n public:\n exception() throw() : m_what(\"general exception\") {}\n exception(const char *reason) throw() : m_what(reason) {}\n exception(const std::string&amp; reason) throw() : m_what(reason) {}\n virtual ~exception() throw() {}\n virtual const char* what() const throw() { return m_what.c_str(); }\n virtual void seterr(const char *err) { this-&gt;m_what = std::string(err); }\n virtual void seterr(const std::string &amp;err) { this-&gt;m_what = err; }\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; s, const omni::exception&amp; e)\n { s &lt;&lt; e.m_what; return s; }\n friend std::basic_ostream&lt;wchar_t&gt;&amp; operator&lt;&lt;(std::basic_ostream&lt;wchar_t&gt;&amp; s, const omni::exception&amp; e) {\n s &lt;&lt; e.m_what.c_str();\n return s;\n }\n protected:\n std::string m_what;\n };\n\n class some_other_exception : public your_namespace::exception {\n public:\n some_other_exception() : exception(\"some other exception happened\") {}\n\n };\n}\n</code></pre>\n\n<p>To use:</p>\n\n<pre><code>try {\n throw your_namespace::exception();\n} catch (std::exception e) { // or const std::exception&amp;\n std::cout &lt;&lt; \"error: \" &lt;&lt; e &lt;&lt; std::endl;\n // or printf(\"error: %s\\n\", e.what()) for your C friends\n}\n\ntry {\n throw your_namespace::exception(\"Here's an exception for you\");\n} catch (std::exception e) {\n std::cout &lt;&lt; \"error: \" &lt;&lt; e &lt;&lt; std::endl;\n}\n\ntry {\n throw your_namespace::some_other_exception();\n} catch (std::exception e) {\n std::cout &lt;&lt; \"error: \" &lt;&lt; e &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>I hope that can help</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-20T20:16:21.643", "Id": "198750", "Score": "0", "body": "@Deduplicator, I've edited my post to be a little more clear, I was more trying to point out that if they wanted to pass the reference itself instead of the decayed pointer (that is `char c[5]; someFn(&c)` vs `someFn(&c[0])`) then their syntax would need changing. I've witnessed some C++ devs who use `char[]` as a function parameter to intend something like the following: `someFn(char[]&)` without understanding that a `char[]` type gets decayed to a pointer type in a function call. So `someFn(char[])` and `someFn(char*)` are completely different types to these devs :/ Sorry for the confusion!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-18T09:27:43.457", "Id": "37660", "ParentId": "33675", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T19:40:24.710", "Id": "33675", "Score": "1", "Tags": [ "c++", "c++11", "exception-handling" ], "Title": "Exception based on std::exception but easy to modify and rethrow" }
33675
<p>I'm working on a simple decorator that creates and manages a database cursor. The goal is to 'inject' the cursor as the first argument of the function, but not expose it to the caller.</p> <p><strong>Usage:</strong></p> <pre><code>import psycopg2 @needsNewCursor def findItem(cursor, item_id): cursor.execute('SELECT name FROM items WHERE id = %s', [item_id]) item_result = cursor.fetchone() # ... return item # caller only needs to know about the ID findItem(1234) </code></pre> <p><strong>Decorator:</strong></p> <pre><code>def needsNewCursor(func): def decorator(*args, **kargs): print 'Creating new cursor' # This is slightly different in the final code, but I'm only # concerned about how I'm dealing with decorators, at the moment cursor = createDefaultCursor() if cursor: with cursor: # Pass the cursor in as the 1st param return func(cursor, *args, **kargs) # Give the function a chance to deal with fails return func(None, *args, **kargs) # QUESTION: Is this enough? decorator.__name__ = func.__name__ return decorator </code></pre> <p>Is this a good approach?</p>
[]
[ { "body": "<p>No, I don't think this is a good approach. Anyone who sees the declaration <code>def findItem(cursor, item_id):</code> will call the function with two arguments and scratch one's head to no end when it does not work.</p>\n\n<p>You could just as well have <code>cursor = createDefaultCursor()</code> as the first line of each function that uses a cursor. The number of lines does not increase as you can omit the <code>@needsNewCursor</code> line.</p>\n\n<p>Even better might be to create a context manager to deal with opening and closing a cursor and start each function with a statement like <code>with new_cursor() as cursor:</code>. A context manager also has an opportunity to deal with exceptions raised in the <code>with</code> block.</p>\n\n<p>Anyway, when writing decorators, instead of assigning yourself <code>decorator.__name__ = func.__name__</code> you can apply the <a href=\"http://docs.python.org/2/library/functools.html#functools.wraps\"><code>functools.wraps</code></a> decorator that also copies the docstring.</p>\n\n<p>One more thing: in your example <code>needsNewCursor</code> is a decorator. You should choose a different name for the inner function. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T21:37:58.947", "Id": "53942", "Score": "0", "body": "Thanks a lot, really like your ideas! :) I will switch to your approach.\nReally like the context manager idea! thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T21:13:49.320", "Id": "33679", "ParentId": "33678", "Score": "5" } } ]
{ "AcceptedAnswerId": "33679", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T20:13:42.577", "Id": "33678", "Score": "3", "Tags": [ "python", "beginner", "cursor" ], "Title": "Simple decorator for creating and managing a database cursor" }
33678
<p>I've been working on this word search algorithm and had some issues about its speed. It kinda looks like it takes a little too much time.</p> <p>If anyone could offer suggestions on making this better and improving my skills, that would be great.</p> <pre><code> #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;fstream&gt; using namespace std; bool Check(string Letter, string Matrix) { return (Letter == Matrix) ? true : false; } int main() { int Height = 0, Widht = 0, Numb = 0, Longer = 0, Look = 0, Look1 = 0, Look2 = 0, Look3 = 0, Poz = 0, Poz1 = 0; int Loop = 0, Loop1 = 0, Loop2 = 0, Loop3 = 0, Loop4 = 0, Loop5 = 0, Loop6 = 0; bool Found, Found1, Found2, Found3; ifstream Data("Files/Info.txt"); Data &gt;&gt; Widht &gt;&gt; Height; string Matrix[Height][Widht]; while(Loop &lt; Height) { Loop1 = 0; while(Loop1 &lt; Widht) { Data &gt;&gt; Matrix[Loop][Loop1]; Loop1++; } Loop++; } Data &gt;&gt; Numb; string Words[Numb]; while(Loop2 &lt; Numb) { Data &gt;&gt; Words[Loop2]; Loop2++; } Data.close(); while(Loop3 &lt; Numb) { Longer = Words[Loop3].size(); Loop4 = 0; Loop6 = 0; cout &lt;&lt; Words[Loop3] &lt;&lt; endl; while(Loop4 &lt; Height) // Looks horizantaly { Loop5 = 0; Look = 0; Look1 = 0; while(Loop5 &lt; Widht - Longer + 1) { Found = Check(Words[Loop3].substr(Look, 1), Matrix[Loop4][Loop5]); if(Found) { Loop6 = 1; Look = Loop5; Poz = Loop4; Poz1 = Loop5; while(Loop6 &lt; Longer) { Look++; Found1 = Check(Words[Loop3].substr(Loop6, 1), Matrix[Loop4][Look]); if(Found1) { Loop6++; } else { Loop5 += Loop6; Loop6 = Longer + 1; } } } if(Loop6 == Longer) { cout &lt;&lt; "Word " &lt;&lt; Words[Loop3] &lt;&lt; " was found at: " &lt;&lt; Poz &lt;&lt; " collumn " &lt;&lt; Poz1 + 1 &lt;&lt; " symbol. Horizontaly from right to left" &lt;&lt; endl; Loop5 = Widht; Loop4 = Height; Loop3++; } Loop5++; } Loop4++; } Loop3++; } return 0; } </code></pre> <p>The infos file looks like this:</p> <pre><code>10 10 a s d f g h j k l o e t a k t r e e a d t e d a w e f g d a r e s a g a f a q w d c s q a z x v n b q w e t a s f w p s w a r y i w t o o a s b b d s s w q o k w e r a d g d a p a q w r c b a x l s k 3 tree poop test </code></pre> <p>Of course, I will later add other directions in which words might be written.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-27T21:14:20.370", "Id": "63570", "Score": "0", "body": "took me like 5 seconds to find all the words...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-01T14:56:05.943", "Id": "63952", "Score": "0", "body": "Yeah this is old code, now i have improved one which can work up with matrix of 40000 * 40000 or 1,6 billion letters" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-06T10:27:42.707", "Id": "202583", "Score": "0", "body": "Why don't you use for loops? they much more easy to write and read.\nI was just lost in your loops for input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-06T12:24:33.433", "Id": "202602", "Score": "0", "body": "What you are trying to do, is very similar to [this](https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=951). there is a nice implementation [here](https://saicheems.wordpress.com/2014/01/05/uva-10010-wheres-waldorf/) I think it is not the same, but you can use it very much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-06T12:26:21.627", "Id": "202603", "Score": "0", "body": "I think one thing to fuel your performance would be change the string matrix[][] to char matrix[][]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-06T12:47:54.687", "Id": "202605", "Score": "0", "body": "as the last comment, the best algorithm for comparing two strings as far as I know is [KMP algorithm](https://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm) . It is a little bit tricky to implement, if you want to get what it is doing tracing it several times on paper would give you good intuition." } ]
[ { "body": "<ul>\n<li><p><code>widht</code> is misspelled; it should be <code>width</code>. :-)</p></li>\n<li><p>Some generalities regarding naming convention:</p>\n\n<p>Variables and functions should start with a lowercase letter:</p>\n\n<pre><code>// \"camel case\"\nint camelCaseVariable;\nvoid camelCaseFunction() {}\n</code></pre>\n\n<p></p>\n\n<pre><code>// \"snake case\"\nint snake_case_variable;\nvoid snake_case_function() {}\n</code></pre>\n\n<p>Custom types should start with a capital letter:</p>\n\n<pre><code>class Class;\n</code></pre>\n\n<p>Macros should be uppercase:</p>\n\n<pre><code>#define MACRO 0\n</code></pre></li>\n<li><p><code>Check()</code>'s body can be simplified as such:</p>\n\n<pre><code>return Letter == Matrix; // already returns true or false\n</code></pre>\n\n<p>Its parameters should also be passed by constant reference since they're not being modified:</p>\n\n<pre><code>bool Check(string const&amp; Letter, string const&amp; Matrix) {}\n</code></pre></li>\n<li><p>You should make sure the input file is open before proceeding. If not, terminate from <code>main()</code> by returning <code>1</code> or <a href=\"http://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"nofollow\"><code>EXIT_FAILURE</code></a>.</p></li>\n<li><p><em>You could vastly improve readability by using more functions</em>. Putting everything in <code>main()</code> is not always a good idea, especially with a lot of nesting. Define the functions to perform one important task, and call them in <code>main()</code> or wherever else as needed. Function call overhead shouldn't hurt you here, making the readability aspect more important.</p>\n\n<p>In its current state, more comments may help others follow the code. That, in turn, could help flesh out any optimization issues. However, this <em>isn't</em> a substitute for writing readable code.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T22:23:24.603", "Id": "33683", "ParentId": "33681", "Score": "4" } }, { "body": "<p><strong>Code style</strong></p>\n\n<ol>\n<li><p>As you are writing C++ there is no need to declare all local variables at the beginning of a block. Declare them where they are needed.</p></li>\n<li><p>Give your loop counters sensible names. Single letter loop counters are accepted practice but sometimes it makes it easier to read to provide some more descriptive name.</p></li>\n<li><p>There is no value in using <code>while</code> loops everywhere. In some places <code>for</code> loops would be much cleaner to read, especially since they allow you to declare the loop counter in place. I found it very hard to discern all the loop variables to see if they are being used later on for some reason. So your first <code>while</code> loop in <code>main</code> could be rewritten as:</p>\n\n<pre><code>for (int y = 0; y &lt; Height; y++)\n{\n for (int x = 0; x &lt; Width; x++)\n {\n Data &gt;&gt; Matrix[y][x];\n }\n}\n</code></pre>\n\n<p>This clearly limits the scope of the loop counter to the loop so anyone reading the code doesn't have to check if the variables might be used further down. It also states the invariants of the loop all in one place. I choose <code>x</code> and <code>y</code> because using <code>x</code> and <code>y</code> to denote coordinates in a 2d structure is fairly common in the programming world. For other loops different names will make more sense.</p>\n\n<p>Same goes for the outer <code>while</code> loop which loops over all words. The inner <code>while</code> loops are ok since you are skipping some parts but still the loop counters should be renamed to something more suitable.</p></li>\n<li><p>Also your other variables could use more descriptive names. For example</p>\n\n<ul>\n<li><code>Numb</code> should be <code>wordCount</code></li>\n<li><code>Longer</code> should be <code>wordLength</code></li>\n</ul></li>\n<li><p>As Jamal said: standard naming convention for local variables and methods is <code>camelCase</code>, classes are <code>PascalCase</code>.</p></li>\n<li><p>Do not use an array to hold a bunch of loop counters. See above for recommendations for loops.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T08:44:28.383", "Id": "54092", "Score": "0", "body": "+1 good stuff. Honestly, I couldn't follow the code well enough to determine that an array is a bad idea here. When I see so many like-variables like that, an array first comes to mind. Normally I wouldn't recommend such a thing. :-) I really wish I knew how this code could be refactored." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T18:07:54.430", "Id": "54140", "Score": "0", "body": "Thanks it's useful, but I still think that while loops are more comfortable to use." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T08:37:04.693", "Id": "33783", "ParentId": "33681", "Score": "3" } }, { "body": "<p>For arrays whose size can be determined at compile time, such as Loop and Possible, prefer the use of <code>std::array</code> which will be safer for bounds checking and will not degenerate into a pointer when passed to another function. (<code>std::array</code> is only available with C++11)</p>\n\n<p>For arrays whose size cannot be determined at compile time, such as Matrix and the members of Matrix, prefer to use <code>std::vector</code> which will take care of the memory allocations for you, and allow you more flexibility in your code.</p>\n\n<p>You can still use the bracket <code>[]</code> syntax with <code>std::array</code> and <code>std::vector</code> so only minimal changes to the above code should be required for implementation, but it is safer to use <code>std::vector::at</code> so that vector can perform bounds checking for you (it will throw an exception if you attempt to access an element outside of the bounds of the vector instead of simply giving you access to raw memory.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-13T15:34:57.510", "Id": "37313", "ParentId": "33681", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T21:23:00.343", "Id": "33681", "Score": "6", "Tags": [ "c++", "algorithm", "performance", "search" ], "Title": "Improving speed of word search algorithm" }
33681
<p>I have a working solution for the given problem of A/B Optimization, but you as an experienced Python (3) developer will agree with me, that this solution is not very pythonic at all.</p> <p>My Question here is: <em>How do I make this code more pythonic?</em></p> <p>It's a very procedural process that one would expect from a Basic program, but not from a Python program. Please help me to become a better coder and make pythonic code by working through this example with me.</p> <p>Here's the problem and my solution.</p> <h2>Problem</h2> <blockquote> <p>In this test you will be given a CSV containing the results of a website's A/B homepage test. The site is simultaneously testing 5 design variables (A, B, C, D, and E) and tracking if users clicked on the signup button (Z). Each line of the CSV represents a visitor to the homepage, what they saw, and if they clicked or not. The A-E variables will have values of 1-5, representing which version of that design element was shown to the user. The Z variable will contain either a 1 to represent that the user clicked signup, or a 0 to represent that the user did not.</p> <pre><code>A B C D E Z 1 3 1 2 4 1 3 2 1 5 5 0 4 3 2 2 5 1 5 5 2 3 4 0 2 4 1 3 4 0 ... </code></pre> <p>Your task will be to determine the single combination of A-E values that will make users most likely to click the signup button. Assume the effects of each A-E value are mutually exclusive. If two values of a variable are equally optimal, choose the lesser value. You will enter the answer in the form of a 5-digit number, the first digit being the optimal A value, the second being the optimal B value, the third being the optimal C value, etc.</p> </blockquote> <h2>Solution</h2> <pre><code>from urllib.request import urlopen def getBestDesign(url): data = urlopen(url).readlines() A = {}; B = {}; C = {}; D = {}; E = {}; A['1'] = 0 A['2'] = 0 A['3'] = 0 A['4'] = 0 A['5'] = 0 B['1'] = 0 B['2'] = 0 B['3'] = 0 B['4'] = 0 B['5'] = 0 C['1'] = 0 C['2'] = 0 C['3'] = 0 C['4'] = 0 C['5'] = 0 D['1'] = 0 D['2'] = 0 D['3'] = 0 D['4'] = 0 D['5'] = 0 E['1'] = 0 E['2'] = 0 E['3'] = 0 E['4'] = 0 E['5'] = 0 for row in data: row = row.decode(encoding='UTF-8').split('\t') if row[5].startswith('1'): A[str(row[0])] += 1 B[str(row[1])] += 1 C[str(row[2])] += 1 D[str(row[3])] += 1 E[str(row[4])] += 1 maxclicks_A = max(A.values()) maxclicks_B = max(B.values()) maxclicks_C = max(C.values()) maxclicks_D = max(D.values()) maxclicks_E = max(E.values()) for k, v in A.items(): if v == maxclicks_A: print('A: ', k) for k, v in B.items(): if v == maxclicks_B: print('B: ', k) for k, v in C.items(): if v == maxclicks_C: print('C: ', k) for k, v in D.items(): if v == maxclicks_D: print('D: ', k) for k, v in E.items(): if v == maxclicks_E: print('E: ', k) if __name__ == &quot;__main__&quot;: url = input('Url: ') getBestDesign(url) </code></pre>
[]
[ { "body": "<p>There is <em>massive</em> code duplication in your script. Basically you are doing the same things for <code>A</code> through <code>E</code>, so you could just put them in a list of dictionaries and use loops. Also, by using <code>defaultdict</code> you do not have to initialize them per hand (and even if not you could use a loop for this, too). Also, I'd recommend removing the code for transforming the URL to a 2D array from the function, and using just <code>split()</code> without <code>'\\t'</code> the code works as well, and is somewhat more robust to other input formats.</p>\n\n<pre><code>from urllib.request import urlopen\nfrom collections import defaultdict\n\ndef getBestDesign(data):\n # this list holds all your A, B, C, ... dicts, with defaultvalues\n ABCDE = [defaultdict(int) for i in range(5)]\n for row in data:\n if row[5] == '1':\n for i in range(5):\n ABCDE[i][row[i]] += 1\n for i in range(5):\n maxclicks = max(ABCDE[i].values())\n for k, v in ABCDE[i].items():\n if v == maxclicks:\n print('ABCDE'[i], \": \", k) # note the ''!\n # break # optional, stop after first \"max\" value\n\nif __name__ == \"__main__\":\n url = input('Url: ')\n lines = urlopen(url).readlines()\n data = [line.decode(encoding='UTF-8').split() for line in lines]\n getBestDesign(data)\n</code></pre>\n\n<p>The algorithms is still basically the same as yours, and I think that it can still be improved. Probably you could use <code>numpy</code> to treat the input data as a matrix and do all sorts of useful matrix operations on the data. Further, you could probably use <code>collections.Counter</code> or <code>itertools.groupby</code> for counting the good combinations, reducing the whole thing to two or three lines.</p>\n\n<hr>\n\n<p>Here's another version, even shorter, doing some preprocessing and using <code>collections.Counter</code>:</p>\n\n<pre><code>def getBestDesign(data):\n filtered = [d[:-1] for d in data if d[5] == '1']\n for i, d in enumerate(zip(*filtered)):\n key, maxclicks = Counter(d).most_common(1)[0]\n print(\"{0}: {1} ({2})\".format(\"ABCDE\"[i], key, maxclicks))\n</code></pre>\n\n<p>Let's explain this line by line:</p>\n\n<ul>\n<li>the <code>filtered</code> <a href=\"http://docs.python.org/3.3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow noreferrer\">list comprehension</a> holds just the lines from <code>data</code> where the user has clicked; as this is already filtered, we can drop the last column with <code>[:-1]</code></li>\n<li>in the loop, we iterate the data columns -- <a href=\"http://docs.python.org/3.3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip(*...)</code></a> basically <a href=\"https://stackoverflow.com/a/4937526/1639625\">transposes</a> the matrix -- using <code>enumerate</code>, which yields the index <code>i</code> and the actual data <code>d</code> at that index</li>\n<li>the <a href=\"http://docs.python.org/dev/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>Counter</code></a> class is used to count each variant and to return the <code>most_common</code> one</li>\n<li>finally, we <code>print</code> the result using <a href=\"http://docs.python.org/3.3/library/stdtypes.html#str.format\" rel=\"nofollow noreferrer\"><code>string.format</code></a>, using the index <code>i</code> to get the respective letter from the string <code>\"ABCDE\"</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T10:16:16.547", "Id": "54099", "Score": "0", "body": "+1, but it seems wrong to me that you have one loop over `ABCDE[i].values()` to find `maxclicks` and then a second loop over `ABCDE[i].items()` to find the key. Better to do this in a single loop: `k, maxclicks = max(ABCDE[i].items(), key=operator.itemgetter(1))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T10:49:20.873", "Id": "54100", "Score": "0", "body": "@GarethRees You are right! When I wrote this, I thought \"this seems wrong, there has to be a better way\" all the time, but did not catch it. Thanks! (Then again, this way there will always be only _one_ max value, whereas there may be multiple.)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T13:04:19.990", "Id": "33703", "ParentId": "33684", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T00:31:19.560", "Id": "33684", "Score": "2", "Tags": [ "python", "optimization", "python-3.x" ], "Title": "How to turn this working A/B optimization program into more pythonic code?" }
33684
<p>I'd like to simplify this Scala code:</p> <pre><code>private def getToken() = { val token = getTokenFromDb() token match { case Some(x) =&gt; token case None =&gt; { val remoteToken = getTokenRemote() remoteToken match { case Some(x) =&gt; { writeTokenToDb(x) remoteToken } case None =&gt; None } } } } </code></pre>
[]
[ { "body": "<pre><code>private def getToken(): Option[Token] = {\n def remoteToken =\n getTokenRemote() map { r =&gt; writeTokenToDb(r); r }\n getTokenFromDb orElse remoteToken\n}\n</code></pre>\n\n<p>Please write always the type of a function for outer functions - it makes it far more readable to understand the source code (often it is useful to add the types to inner functions/declarations as well).</p>\n\n<p>Beside from that you can also write <code>case t: Some =&gt; t</code> or <code>case t @ Some(_) =&gt; t</code> to express that you return the matched type. Your way of <code>case Some(x) =&gt; token</code> is hard to understand, because one needs to know what's <code>token</code>.</p>\n\n<p>Furthermore, you don't need braces around a match block, you can simply write</p>\n\n<pre><code>case x =&gt;\n a\n b\n</code></pre>\n\n<p>And naming a variable in a similar way as a function, like in <code>val token = getToken()</code> is completely unnecessary, when it is only used once, it also doesn't increase readability. In such cases just inline the function call: <code>getToken match { ... }</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T05:48:20.430", "Id": "54009", "Score": "0", "body": "it seems like you make an unnecessary recursive call in `def getToken()`. How can it return `Some(x)` in ` `getToken orElse remoteToken` ? It will call itself recursively." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T05:52:21.573", "Id": "54010", "Score": "0", "body": "it's my miss, it should be `getTokenFromDb`, shouldn't it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T10:36:55.653", "Id": "54016", "Score": "0", "body": "@Alex: You are right, that was a mistake." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T09:49:40.413", "Id": "33696", "ParentId": "33685", "Score": "4" } } ]
{ "AcceptedAnswerId": "33696", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T03:21:52.787", "Id": "33685", "Score": "2", "Tags": [ "scala" ], "Title": "Is there any way to simplify this code" }
33685
<p>I have written this code which finds duplicate numbers and the occurrence of a particular number in an array. I have used a <code>HashMap</code>, but I want to know if there is a more efficient way to do the same, or whether I should be using another method.</p> <pre><code>import java.util.*; class test7 { public static void main(String ...a) { int []arr={10,20,10,2,11,10,32,15,15,10,10}; HashMap&lt;Integer,Integer&gt; num=new HashMap&lt;Integer,Integer&gt;(); for(int t: arr) { Integer tmp_int=new Integer(t); if(num.containsKey(tmp_int)) { Integer i_ob=num.get(tmp_int); num.put(tmp_int,new Integer(i_ob.intValue()+1)); } else { num.put(tmp_int,new Integer(1)); } } System.out.println(num); } } </code></pre> <p>Output:</p> <pre><code>{32=1, 2=1, 20=1, 10=5, 11=1, 15=2} </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-13T23:50:57.210", "Id": "327844", "Score": "0", "body": "Regardless of the fact that explicit boxing is unnecessary here, it's better to use [`Integer.valueOf(int)`](http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#valueOf-int-) than the constructor `Integer(int)` (see the documentation of that method, to which I linked the method name, for an explanation why)." } ]
[ { "body": "<p>I have modified your code. The logic is same as you have done. You do not need to create those <code>Integer</code>. Read about <a href=\"http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html\" rel=\"nofollow\">Autoboxing</a>. If the input array is large, you will see performance hit for creating Integer. Note that Integer is a class, and not a primitive type in java.</p>\n\n<pre><code>public static void main(String[] args) { \n int[] arr={10,20,10,2,11,10,32,15,15,10,10}; \n HashMap&lt;Integer,Integer&gt; result = new HashMap&lt;Integer,Integer&gt;(); \n\n for(int element : arr) \n { \n if(result.containsKey(element)) \n { \n result.put(element, result.get(element) + 1); \n } \n else \n { \n result.put(element, 1); \n } \n } \n System.out.println(result); \n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T05:15:47.807", "Id": "33688", "ParentId": "33686", "Score": "4" } }, { "body": "<p>As described <a href=\"https://stackoverflow.com/a/32516817/5934924\">here</a> you could use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#frequency-java.util.Collection-java.lang.Object-\" rel=\"nofollow noreferrer\">Collections.frequency</a> to find duplicate numbers in java 8:</p>\n\n<pre><code>numbers.stream()\n .filter(i -&gt; Collections.frequency(numbers, i) &gt;1)\n .collect(Collectors.toSet())\n .forEach(System.out::println);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-13T20:33:37.957", "Id": "172905", "ParentId": "33686", "Score": "2" } } ]
{ "AcceptedAnswerId": "33688", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T03:54:51.693", "Id": "33686", "Score": "3", "Tags": [ "java" ], "Title": "Finding duplicate numbers" }
33686
<p>I posted a couple of weeks ago with a <a href="https://codereview.stackexchange.com/questions/32854/critique-a-beginners-linked-list-implementation">double linked list</a>. It was recommended that I rewrite the code as a singlely linked list and replace the recursive parts with loops.</p> <p>I've gone ahead and made several edits and was hoping to get another critique of the code.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; struct file { int fd; struct file *next; }; struct file *create_head(void) { struct file *first_link = malloc ( sizeof *first_link ); return first_link; } void insert(struct file *node, int val) { while (node-&gt;next != NULL) { node = node-&gt;next; } struct file *tail = malloc ( sizeof *tail ); node-&gt;next = tail; tail-&gt;fd = val; tail-&gt;next = NULL; } int delete(struct file *node, int val) { struct file *prev; while (node-&gt;fd != val) { if(!(node-&gt;next)) { return 1; } else { prev = node; node = node-&gt;next; } } prev-&gt;next = node-&gt;next; free(node); return 0; } int locate(struct file *node, int val) { while (node-&gt;fd != val) { if (!(node-&gt;next)) { return 1; } else { node = node-&gt;next; } } printf ("Value %d in list\n", val); return 0; } void dump(struct file *node) { while (node-&gt;next) { printf ("Node: %d\n", node-&gt;fd); node = node-&gt;next; } printf ("Node: %d\n", node-&gt;fd); } int get_choice(void) { int choice; int val; struct file *head = NULL; while ( true ) { printf ("\n[Choices - Insert=1, Delete=2, Locate=3, Dump=4, Exit=5]\n"); printf ("\nEnter selection: "); scanf("%d", &amp;choice); switch (choice) { case (1): printf ("Enter value: "); scanf ("%d", &amp;val); if (!(head)) { head = create_head(); head-&gt;fd = val; head-&gt;next = NULL; } else { insert(head, val); } break; case (2): if (head) { printf ("Enter value: "); scanf ("%d", &amp;val); if (head-&gt;fd == val &amp;&amp; head-&gt;next == NULL) { head = NULL; } else if (head-&gt;fd == val &amp;&amp; head-&gt;next != NULL) { free (head); head = head-&gt;next; } else if (delete(head, val) == 1) { printf ("Value %d not in list\n", val); } } else { printf ("List is empty!\n"); } break; case (3): if (head) { printf ("Enter value: "); scanf ("%d", &amp;val); if (locate(head, val) == 1) { printf ("Value %d not in list\n", val); } } else { printf ("List is empty!\n"); } break; case (4): if (head) { dump(head); } else { printf ("Nothing to dump!\n"); } break; case (5): return 0; } } } int main(void) { printf ("\nSingle Linked List: \n"); get_choice(); return 0; } </code></pre>
[]
[ { "body": "<p><strong>Stylistic/Function</strong></p>\n\n<ol>\n<li>Your list holds values of type <code>int</code> yet you named the node type very specific in relation to file descriptors which will be a bit weird if you make a list of lets say prime numbers you want to operate on. Consider renaming your node type to something more generic rather than <code>file</code> (especially sincere there is a <code>FILE</code> type in <code>&lt;stdio.h&gt;</code>)</li>\n<li>Your <code>insert</code> method actually doesn't insert an element, it appends it to the end so it should be named <code>append</code>.</li>\n<li><code>delete</code> doesn't work when the node you want to delete is <code>head</code>. I know you handle that case separately in <code>get_choice</code> but it's still bad that the caller has to know that fact. It also clutters the code with lots of special handling.</li>\n<li><code>dump</code> is a bit weird: It skips the first one, then prints all following nodes in order and then prints the first one. So while it prints out all nodes I'd say it's still unexpected from a usage point of view.</li>\n<li>None of your methods can deal with the fact if <code>NULL</code> is being passed in. </li>\n<li>If you <code>typedef</code> your structs then you can save some typing work.</li>\n</ol>\n\n<p><strong>Structural/Design</strong></p>\n\n<ol>\n<li>Your list does not have a nice API to use. You can see that in <code>get_choice</code> which is cluttered with handling of many special cases.</li>\n<li>Some methods like <code>insert</code> (<code>size/length</code> would be a different candidate) are inefficient as you have to iterate the entire list first. You could avoid that by keeping a separate <code>tail</code> pointer.</li>\n</ol>\n\n<p>I suggest you create a list object which holds <code>head</code>, <code>tail</code> and possibly <code>length</code> of the list and all your methods should operate on an object of that list type rather than nodes. Something along these lines:</p>\n\n<pre><code>typedef struct node_\n{\n int value;\n struct node *next;\n} node;\n\ntypedef struct list_\n{\n struct node *head;\n struct node *tail;\n int length;\n} list;\n</code></pre>\n\n<p>And then define some methods to operate on:</p>\n\n<pre><code>// creates a new empty list\nlist *new_list()\n{\n}\n\n// deletes the list and all the nodes\nvoid delete_list(list *l)\n{\n}\n\n// appends new value to the list\nvoid append(list *l, int value)\n{\n}\n\n// insert a value at a given position\nvoid insert(list *l, int value, int position)\n{\n}\n\n// deletes the first node with the given value from the list\n// return 1 if node found and deleted, 0 otherwise\nint delete_item(list *l, int value)\n{\n}\n\n// returns the first node with the given value or NULL if not found\nnode *find(list *l, int value)\n{\n}\n\n// prints the content of the list\nvoid print_list(list *l)\n{\n}\n</code></pre>\n\n<p>Your <code>get_choice</code> method would then look like this:</p>\n\n<pre><code>int get_choice(void) {\n int choice;\n int val;\n list *myList = new_list();\n while ( true ) {\n printf (\"\\n[Choices - Insert=1, Delete=2, Locate=3, Dump=4, Exit=5]\\n\");\n printf (\"\\nEnter selection: \");\n scanf(\"%d\", &amp;choice);\n switch (choice) {\n case (1): \n printf (\"Enter value: \");\n scanf (\"%d\", &amp;val);\n append(myList, val);\n break;\n case (2):\n if (myList-&gt;length &gt; 0) { \n printf (\"Enter value: \");\n scanf (\"%d\", &amp;val); \n if (!delete_item(myList, val))\n { \n printf (\"Value %d not in list\\n\", val);\n }\n }\n else {\n printf (\"List is empty!\\n\");\n }\n break;\n case (3): \n if (myList-&gt;length &gt; 0) {\n printf (\"Enter value: \");\n scanf (\"%d\", &amp;val); \n if (find(myList, val) == NULL) {\n printf (\"Value %d not in list\\n\", val);\n }\n }\n else {\n printf (\"List is empty!\\n\");\n }\n break;\n case (4): \n if (myList-&gt;length &gt; 0) { \n print_list(myList);\n }\n else {\n printf (\"Nothing to dump!\\n\");\n }\n break;\n case (5): \n return 0;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T04:47:18.520", "Id": "54006", "Score": "0", "body": "these points are all very enlightening. Especially testing for NULL and having the separate list to track." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T02:26:58.000", "Id": "33723", "ParentId": "33687", "Score": "3" } } ]
{ "AcceptedAnswerId": "33723", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T04:52:44.387", "Id": "33687", "Score": "3", "Tags": [ "c", "linked-list" ], "Title": "Review of singlely linked list C" }
33687
<p>I write quite a bit of code in C, but haven't done much C++ since my college CS classes. I have been revisiting C++ recently, and thought I would re-implement a program I had previously written in C, but this time in C++. I particularly took advantage of containers and other features standardized recently by the C++11 standard.</p> <p>I really enjoyed writing the code, and have verified that the C++ version of my program generates the same output as the original C version. However, there is a <em>substantial</em> performance margin--I'm talking like an order of magnitude and then some for the test I ran.</p> <p>Many programmers claim that C++ performance should be close to C. Of course there's a bit more overhead, but from 48 seconds to 18 minutes--that's just unreasonable.</p> <p>I'm wondering whether I've done something completely wrong or inefficient, which is causing the performance discrepancy. Any feedback would be welcome.</p> <p>Here is the C code:</p> <pre><code>/* Copyright (c) 2013, Daniel S. Standage &lt;daniel.standage@gmail.com&gt; Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include &lt;getopt.h&gt; #include &lt;stdio.h&gt; #include "khash.h" //------------------------------------------------------------------------------ // Definitions/prototypes/initializations for data structures, functions, etc. //------------------------------------------------------------------------------ #define MAX_LINE_LENGTH 8192 #define MAX_ID_LENGTH 1024 KHASH_MAP_INIT_STR(m32, unsigned) typedef struct { char delim; const char *outfile; FILE *outstream; unsigned numfiles; } SmrOptions; void smr_init_options(SmrOptions *options); khash_t(m32) *smr_collect_molids(SmrOptions *options, khash_t(m32) **maps); khash_t(m32) *smr_load_file(const char *filename); void smr_parse_options(SmrOptions *options, int argc, char **argv); void smr_print_matrix(SmrOptions *options, khash_t(m32) **maps); void smr_print_usage(FILE *outstream); void smr_terminate(SmrOptions *options, khash_t(m32) **maps); //------------------------------------------------------------------------------ // Main method //------------------------------------------------------------------------------ int main(int argc, char **argv) { SmrOptions options; smr_init_options(&amp;options); smr_parse_options(&amp;options, argc, argv); unsigned i; khash_t(m32) **maps = malloc( sizeof(void *) * options.numfiles ); for(i = 0; i &lt; options.numfiles; i++) maps[i] = smr_load_file(argv[optind+i]); smr_print_matrix(&amp;options, maps); smr_terminate(&amp;options, maps); return 0; } //------------------------------------------------------------------------------ // Function implementations //------------------------------------------------------------------------------ khash_t(m32) *smr_collect_molids(SmrOptions *options, khash_t(m32) **maps) { unsigned i; khiter_t iter; khash_t(m32) *ids = kh_init(m32); for(i = 0; i &lt; options-&gt;numfiles; i++) { for(iter = kh_begin(maps[i]); iter != kh_end(maps[i]); iter++) { if(!kh_exist(maps[i], iter)) continue; const char *molid = kh_key(maps[i], iter); khint_t key = kh_get(m32, ids, molid); if(key == kh_end(ids)) { int code; key = kh_put(m32, ids, molid, &amp;code); if(!code) { fprintf(stderr, "error: failure storing key '%s'\n", molid); kh_del(m32, ids, key); } else kh_value(ids, key) = 1; } } } return ids; } void smr_init_options(SmrOptions *options) { options-&gt;delim = ','; options-&gt;outfile = "stdout"; options-&gt;outstream = stdout; options-&gt;numfiles = 0; } khash_t(m32) *smr_load_file(const char *filename) { FILE *instream = fopen(filename, "r"); if(instream == NULL) { fprintf(stderr, "error opening file '%s'\n", filename); exit(1); } khash_t(m32) *map = kh_init(m32); char buffer[MAX_LINE_LENGTH]; while(fgets(buffer, MAX_LINE_LENGTH, instream) != NULL) { const char *tok = strtok(buffer, "\t\n"); tok = strtok(NULL, "\t\n"); int bflag = atoi(tok); if(bflag &amp; 0x4) continue; tok = strtok(NULL, "\t\n"); khint_t key = kh_get(m32, map, tok); if(key == kh_end(map)) { int code; const char *molid = strdup(tok); key = kh_put(m32, map, molid, &amp;code); if(!code) { fprintf(stderr, "error: failure storing key '%s'\n", molid); kh_del(m32, map, key); } else kh_value(map, key) = 0; } unsigned tsareadcount = kh_value(map, key); kh_value(map, key) = tsareadcount + 1; } fclose(instream); return map; } void smr_parse_options(SmrOptions *options, int argc, char **argv) { int opt = 0; int optindex = 0; const char *optstr = "d:ho:"; const struct option smr_options[] = { { "delim", required_argument, NULL, 'd' }, { "help", no_argument, NULL, 'h' }, { "outfile", required_argument, NULL, 'o' }, { NULL, no_argument, NULL, 0 }, }; for(opt = getopt_long(argc, argv, optstr, smr_options, &amp;optindex); opt != -1; opt = getopt_long(argc, argv, optstr, smr_options, &amp;optindex)) { switch(opt) { case 'd': if(strcmp(optarg, "\\t") == 0) optarg = "\t"; else if(strlen(optarg) &gt; 1) { fprintf(stderr, "warning: string '%s' provided for delimiter, using " "only '%c'\n", optarg, optarg[0]); } options-&gt;delim = optarg[0]; break; case 'h': smr_print_usage(stdout); exit(0); break; case 'o': options-&gt;outfile = optarg; break; default: fprintf(stderr, "error: unknown option '%c'\n", opt); smr_print_usage(stderr); break; } } if(strcmp(options-&gt;outfile, "stdout") != 0) { options-&gt;outstream = fopen(options-&gt;outfile, "w"); if(options-&gt;outstream == NULL) { fprintf(stderr, "error: unable to open output file '%s'\n", options-&gt;outfile); exit(1); } } options-&gt;numfiles = argc - optind; if(options-&gt;numfiles &lt; 1) { fputs("expected 1 or more input files\n", stderr); smr_print_usage(stderr); exit(1); } } void smr_print_matrix(SmrOptions *options, khash_t(m32) **maps) { khiter_t iter; unsigned i; khash_t(m32) *molids = smr_collect_molids(options, maps); for(iter = kh_begin(molids); iter != kh_end(molids); iter++) { if(!kh_exist(molids, iter)) continue; const char *molid = kh_key(molids, iter); fprintf(options-&gt;outstream, "%s%c", molid, options-&gt;delim); for(i = 0; i &lt; options-&gt;numfiles; i++) { if(i &gt; 0) fputc(options-&gt;delim, options-&gt;outstream); khint_t key = kh_get(m32, maps[i], molid); if(key == kh_end(maps[i])) fputc('0', options-&gt;outstream); else { unsigned readcount = kh_value(maps[i], key); fprintf(options-&gt;outstream, "%u", readcount); } } fputc('\n', options-&gt;outstream); } kh_destroy(m32, molids); } void smr_print_usage(FILE *outstream) { fputs("\nSMR: SAM mapped reads\n\n" "The input to SMR is 1 or more SAM files. The output is a table (1 column for\n" "each input file) showing the number of reads that map to each sequence.\n\n" "Usage: smr [options] sample-1.sam sample-2.sam ... sample-n.sam\n" " Options:\n" " -d|--delim: CHAR delimiter for output data; default is comma\n" " -h|--help print this help message and exit\n" " -o|--outfile: FILE name of file to which read counts will be\n" " written; default is terminal (stdout)\n", outstream); } void smr_terminate(SmrOptions *options, khash_t(m32) **maps) { unsigned i; khint_t iter; for(i = 0; i &lt; options-&gt;numfiles; i++) { for(iter = kh_begin(maps[i]); iter != kh_end(maps[i]); iter++) { if(!kh_exist(maps[i], iter)) continue; char *molid = (char *)kh_key(maps[i], iter); free(molid); } kh_destroy(m32, maps[i]); } free(maps); fclose(options-&gt;outstream); } </code></pre> <p>And here is the C++ code:</p> <pre><code>/* Copyright (c) 2013, Daniel S. Standage &lt;daniel.standage@gmail.com&gt; Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include &lt;unistd.h&gt; #include &lt;cstring&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;unordered_map&gt; #include &lt;unordered_set&gt; #include &lt;vector&gt; typedef std::unordered_set&lt;std::string&gt; uset; typedef std::unordered_map&lt;std::string, unsigned&gt; umap; struct SmrOptions { char delim; std::string outfile; std::ostream&amp; outstream; unsigned numfiles; std::vector&lt;std::string&gt; infiles; SmrOptions(char d, std::string of, std::ostream&amp; os, unsigned nf, std::vector&lt;std::string&gt; infls) : delim(d), outfile(of), outstream(os), numfiles(nf), infiles(infls) {} }; typedef struct SmrOptions SmrOptions; uset smr_collect_molids(SmrOptions&amp; options, std::vector&lt;umap&gt;&amp; rm2seqPerSample); umap smr_load_file(std::istream&amp; instream, char delim); SmrOptions smr_parse_options(int argc, char **argv); void smr_print_matrix(SmrOptions&amp; options, std::vector&lt;umap&gt;&amp; rm2seqPerSample); void smr_print_usage(std::ostream&amp; outstream); std::vector&lt;std::string&gt;&amp; smr_string_split(const std::string &amp;s, char delim, std::vector&lt;std::string&gt; &amp;elems); //------------------------------------------------------------------------------ // Main method //------------------------------------------------------------------------------ int main(int argc, char **argv) { SmrOptions options = smr_parse_options(argc, argv); std::vector&lt;umap&gt; rm2seqPerSample; for(unsigned i = 0; i &lt; options.numfiles; i++) { std::ifstream ifs (std::string(options.infiles[i])); if(!ifs.is_open()) { std::cerr &lt;&lt; "error opening input file " &lt;&lt; options.infiles[i] &lt;&lt; std::endl; exit(1); } rm2seqPerSample.push_back(smr_load_file(ifs, options.delim)); ifs.close(); } smr_print_matrix(options, rm2seqPerSample); //options.outstream.close(); return 0; } //------------------------------------------------------------------------------ // Function implementations //------------------------------------------------------------------------------ uset smr_collect_molids(SmrOptions&amp; options, std::vector&lt;umap&gt;&amp; rm2seqPerSample) { uset molids; for(std::vector&lt;umap&gt;::iterator ssiter = rm2seqPerSample.begin(); ssiter != rm2seqPerSample.end(); ssiter++) { umap&amp; rm2seq = *ssiter; for(umap::iterator iter = rm2seq.begin(); iter != rm2seq.end(); iter++) { molids.emplace(iter-&gt;first); } } return molids; } umap smr_load_file(std::istream&amp; instream, char delim) { umap rm2seq; std::string buffer; while(std::getline(instream, buffer)) { if(buffer[0] == '@') continue; std::vector&lt;std::string&gt; tokens; smr_string_split(buffer, '\t', tokens); std::string molid = tokens[2]; std::string bflag_str = tokens[1]; int bflag = std::stoi(bflag_str); if(bflag &amp; 0x4) continue; umap::iterator keyvaluepair = rm2seq.find(molid); if(keyvaluepair == rm2seq.end()) rm2seq.emplace(molid, 1); else rm2seq[molid] += 1; } return rm2seq; } SmrOptions smr_parse_options(int argc, char **argv) { char delim = ','; std::string outfile = "stdout"; char opt; const char *arg; while((opt = getopt(argc, argv, "d:ho:")) != -1) { switch(opt) { case 'd': arg = optarg; if(strcmp(optarg, "\\t") == 0) arg = "\t"; else if(strlen(optarg) &gt; 1) { std::cerr &lt;&lt; "warning: string '" &lt;&lt; arg &lt;&lt; "' provided for delimiter, using only '" &lt;&lt; arg[0] &lt;&lt; "'" &lt;&lt; std::endl; } delim = arg[0]; break; case 'h': smr_print_usage(std::cout); exit(0); break; case 'o': outfile = optarg; break; default: fprintf(stderr, "error: unknown option '%c'\n", opt); smr_print_usage(std::cerr); break; } } std::ofstream outfilestream; bool usestdout = (outfile.compare(std::string("stdout")) == 0); if(!usestdout) outfilestream.open(outfile, std::ios::out); std::ostream&amp; outstream = (usestdout ? std::cout : outfilestream); unsigned numfiles = argc - optind; if(numfiles &lt; 1) { std::cerr &lt;&lt; "expected 1 or more input files" &lt;&lt; std::endl; smr_print_usage(std::cerr); exit(1); } std::vector&lt;std::string&gt; infiles; for(unsigned i = 0; i &lt; numfiles; i++) { int ind = optind + i; std::string filename (argv[ind]); infiles.push_back(filename); } return SmrOptions (delim, outfile, outstream, numfiles, infiles); } void smr_print_matrix(SmrOptions&amp; options, std::vector&lt;umap&gt;&amp; rm2seqPerSample) { uset molids = smr_collect_molids(options, rm2seqPerSample); for(uset::iterator iter = molids.begin(); iter != molids.end(); iter++) { std::string molid = *iter; options.outstream &lt;&lt; molid &lt;&lt; options.delim; for(std::vector&lt;umap&gt;::iterator sampleiter = rm2seqPerSample.begin(); sampleiter != rm2seqPerSample.end(); sampleiter++) { if(sampleiter != rm2seqPerSample.begin()) options.outstream &lt;&lt; options.delim; umap rm2seq = *sampleiter; umap::const_iterator keyvaluepair = rm2seq.find(molid); if(keyvaluepair == rm2seq.end()) options.outstream &lt;&lt; '0'; else options.outstream &lt;&lt; keyvaluepair-&gt;second; } options.outstream &lt;&lt; std::endl; } } void smr_print_usage(std::ostream&amp; outstream) { outstream &lt;&lt; std::endl &lt;&lt; "SMR: SAM mapped reads" &lt;&lt; std::endl &lt;&lt; std::endl &lt;&lt; "The input to SMR is 1 or more SAM files. The output is a table (1 column for" &lt;&lt; std::endl &lt;&lt; "each input file) showing the number of reads that map to each sequence." &lt;&lt; std::endl &lt;&lt; std::endl &lt;&lt; "Usage: smr [options] sample-1.sam sample-2.sam ... sample-n.sam" &lt;&lt; std::endl &lt;&lt; " Options:" &lt;&lt; std::endl &lt;&lt; " -d|--delim: CHAR delimiter for output data; default is comma" &lt;&lt; std::endl &lt;&lt; " -h|--help print this help message and exit" &lt;&lt; std::endl &lt;&lt; " -o|--outfile: FILE name of file to which read counts will be" &lt;&lt; std::endl &lt;&lt; " written; default is terminal (stdout)" &lt;&lt; std::endl &lt;&lt; std::endl; } std::vector&lt;std::string&gt;&amp; smr_string_split(const std::string &amp;s, char delim, std::vector&lt;std::string&gt; &amp;elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } </code></pre> <p>These are accessible from <a href="https://github.com/standage/smr/tree/c941a4aee4009f16039960c797827175a2289797" rel="nofollow">commit c941a4aee4 of my GitHub repo</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T07:16:06.313", "Id": "53958", "Score": "2", "body": "Lot of extra copying. But it's hard to measure actual throughput with a set of input data. Also to help other people in the future we ask you post the code for review on the site. This has two effects: 1) It makes sure the code that we spend time reviewing is available for others to compare review notes against 2) The code is in the public domain (see last line on page)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T11:33:08.530", "Id": "53965", "Score": "0", "body": "@LokiAstari Did you mean hard to measure *without* input data? A sample input file is available at http://de.iplantcollaborative.org/dl/bacae906-6c89-42a7-adbd-d2375f7039ca, but be warned its 26GB. I'm working on uploading a compressed file, will update once I have." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T12:36:43.657", "Id": "53966", "Score": "0", "body": "Ok, here is the link to the same file gzip-compressed: http://de.iplantcollaborative.org/dl/22c07038-7ccd-4c9d-9f83-342340546c6e. Any subset of this file will work fine for testing each line is an independent data entry." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T23:47:23.250", "Id": "53995", "Score": "2", "body": "@LokiAstari maybe nitpicking, but **creative commons != public domain**. We have [some restrictions](http://creativecommons.org/licenses/by-sa/3.0/) such as *attribution required* and *share alike*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T02:26:11.390", "Id": "53997", "Score": "0", "body": "Who said C is faster than C++ at all? http://stackoverflow.com/questions/6955114/is-c-notably-faster-than-c" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T02:48:12.537", "Id": "53999", "Score": "0", "body": "@Celeritas: But good C++ should not be significantly slower than well written C. But it should be significantly smaller (in source code). Basically the argument I would use is that code written in C and C++ should generate code of approx the same speed. But because it has a lot of compiler generated features. The source should be smaller. Let the test begin." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T02:48:56.053", "Id": "54000", "Score": "0", "body": "@codesparkle: Point well taken." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:02:17.243", "Id": "54762", "Score": "0", "body": "Description of the [SAM file format](http://samtools.sourceforge.net)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T22:24:18.897", "Id": "54765", "Score": "0", "body": "[Excerpt](https://github.com/dpoon/smr/blob/31d6aa0e4aa480d687d39d79c66f0630f13f5ed4/sample.sam) from the [sample data](http://de.iplantcollaborative.org/dl/bacae906-6c89-42a7-adbd-d2375f7039ca)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T11:07:11.660", "Id": "56848", "Score": "0", "body": "Have you profiled your program to see where the bottlenecks are? Did you check the memory usage of your program? With all the copying, it's likely that the C++ program needs much more memory! and might simply be thrashing." } ]
[ { "body": "<p>As the comments alluded to, there's a lot of copying going on. Since I don't have profile data (wrong way to go after performance), I'll go over differences in the approach.</p>\n\n<h2>main()</h2>\n\n<p>In <code>main()</code>, the C version pre-allocates an array of <code>options.numfiles</code> pointers, but the C++ version merely uses <code>push_back()</code> to build a vector. Since you know the size, you could make the C++ version pre-allocate similarly by calling <code>rm2seqPerSample.reserve(options.numfiles)</code>.</p>\n\n<p><code>smr_load_file</code> returns a pointer in the C version, and a <code>std::unordered_map&lt;string, unsigned&gt;</code> in the C++ version. While this probably uses <code>RVO</code> to avoid an initial copy or move, this is then pushed into the above vector, which must move or copy the map. It would be more idiomatic in C++ to wrap this into a class, and perhaps call <code>emplace_back</code> instead:</p>\n\n<pre><code>struct smr_file : private std::unordered_map&lt;std::string, unsigned&gt;\n{\n smr_file(std::istream&amp; instream, char delim)\n {\n // code from smr_load_file operating on *this here\n }\n};\n: : :\nint main(...)\n{\n std::vector&lt;smr_file&gt; rm2secPerSample;\n : : :\n rm2seqPerSample.emplace_back(ifs, options.delim);\n : : :\n}\n</code></pre>\n\n<h2>smr_load_file()</h2>\n\n<p>Diving into the <code>smr_load_file</code>, there are small things and larger things. Starting small, you can replace <code>rm2seq[molid] += 1</code> with <code>keyvaluepair-&gt;second += 1</code> to avoid a second lookup. Or maybe you can replace the entire find/emplace/increment stanza with just <code>rm2seq[molid] += 1</code>, if you can ensure the key-value-pair instantiates with value 0. (The former could help with efficiencies; the latter could help with local code complexity, which is usually more important.) Going a bit larger, the call to <code>smr_string_split</code> worried me, as string splits are easy to get wrong, and it sounds like this could well be one of your bottlenecks.</p>\n\n<h2>smr_string_split()</h2>\n\n<p>Looking at <code>smr_string_split</code>, there are a few things I would likely change. First off, a badly formatted line could result in a crash in the calling code (if there's fewer than two delimiters found, only one or two elements will be in the vector, so the following <code>tokens[2]</code> will misbehave). Second, there are a lot of data copies in these few lines of code, such as into the <code>stringstream</code>, out into the <code>string</code>, and onward into the <code>vector&lt;string&gt;</code> <code>elems</code>. I would be tempted to replace this with a more straightforward method that specifically parses out these items, either returning through \"out\" parameters (<code>bool smr_parse_line(const std::string&amp; line, char delim, int &amp;bflag, std::string&amp; molid)</code>), with a tuple (<code>std::tuple&lt;int, std::string&gt; smr_parse_line(const std::string&amp; line, char delim)</code>), or even just implement it inline. As for implementing this method, I would tend towards <code>std::string::find</code> and <code>substr</code> calls, as it seems you only support a predefined number of tokens.</p>\n\n<h2>smr_print_matrix()</h2>\n\n<p><code>smr_print_matrix</code> starts with a copy or move, though probably elided due to <code>RVO</code>, but then loops suboptimally. The manual iterator bounds checking in the iterator faces a potential performance penalty due to its repeated calculation of <code>end()</code>. I would suggest replacing the for loops with a range for: <code>for (auto&amp; molid : molids)</code>, similarly <code>for (auto&amp; rm2seq : rm2seqPerSample)</code>. The only trick is handling your conditional output of <code>options.delim</code>. Here your use of <code>rm2seq.find</code> is correct, although I can't guess whether conditionally outputting a <code>char</code> instead of an <code>int</code> would have any effect. If it doesn't, something like <code>options.outstream &lt;&lt; (keyvaluepair != rm2seq.end()) ? keyvaluepair-&gt;second : 0;</code> might be a maintenance win (or loss if you hate <code>?:</code>).</p>\n\n<h2>smr_collect_molids()</h2>\n\n<p>The for loops should be changed similarly, but at least here you use references to capture your iterator's referenced value. The translation between C and C++ here seems a little iffy, as I don't see what captures the <code>else kh_value(ids, key) = 1</code>.</p>\n\n<h2>overview</h2>\n\n<p>Your code has taken a first stab at becoming idiomatic C++ code, but it has more steps to go. You've replaced the khash data structure with data structures from C++, but are still using them in a largely C fashion. There's nothing inherently wrong with this, although it may surprise many C++ developers, and may be unable to leverage many of the improvements in C++.</p>\n\n<p>The biggest general thing to watch out for are invisible copies of large amounts of data. Some of this can be dodged by making certain to call methods that support <code>move</code>. Other parts can be removed by changing the ownership of objects to only create them in their final place (such as my smr_file example). Still other parts can be removed by not changing between different representations of the same data (string to stringstream, and so forth). Finally, just because it is C++, don't feel you have to give up C tools that happen to be faster at certain tasks. Instead try to understand why they are faster, and see if there are alternatives in C++ that you didn't already consider.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T03:22:16.513", "Id": "57213", "Score": "0", "body": "Thanks for your feedback. The pointers regarding idiomatic C++ were particularly helpful. Most of this has not made any difference in performance, unfortunately. It wasn't until I addressed the `smr_string_split` function (gave up on `stringstream` and reverted to `strtok`) that I was able to achieve C-like performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T03:32:21.060", "Id": "57214", "Score": "0", "body": "I'm not surprised that `smr_string_split` was the bottleneck. I don't want to fan the iostream flames, but all the copies there just couldn't help. By the way, in theory `string::find` and `string::substr` should be faster than `strtok`, as they throw away and recalculate less information (length of substring), but it's hard to guess if the difference would be measurable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T15:47:17.680", "Id": "57300", "Score": "0", "body": "Actually, now that I've refactored a bit more, it seems that the string parsing was only a small bit of the performance issue. The biggest performance issue seems to have been the use of the C++ input and output streams. Replacing these with C-style file pointers (which I had done to some extent while fixing the string parsing code) is what really makes the biggest difference." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T18:41:01.050", "Id": "35195", "ParentId": "33689", "Score": "5" } } ]
{ "AcceptedAnswerId": "35195", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T05:17:36.707", "Id": "33689", "Score": "5", "Tags": [ "c++", "performance", "c", "c++11", "bioinformatics" ], "Title": "SAM mapped reads" }
33689
<p>I'm going to post some of my solutions to common interview questions. I would love it if you could critique me from a C++ purist's standpoint. Also, tell me if there's a better algorithm for each one of these. </p> <p><strong>Find the mode (most common element) of an array.</strong></p> <p>Note: My solution returns an arbitrary mode if there's a tie; assumes the array is non-empty, too</p> <pre><code>int mode(int* arr, int sz) { std::map&lt;int,int&gt; cntMap; int most = arr[0]; for (int i = 0; i &lt; sz; i++) { if (!cntMap.count(arr[i])) { cntMap[arr[i]] = 0; } else { cntMap[arr[i]]++; } if (cntMap[arr[i]] &gt; most) { most = cntMap[arr[i]]; } } return most; } </code></pre> <p><strong>Sum the largest 2 largest elements of an array.</strong></p> <p>Note: Assumes the array contains at least 2 elements</p> <pre><code>int largest2(int* arr, int sz) { int largest(arr[0]), secondLargest[arr[0]]; for (int i = 0; i &lt; sz; i++) { if (arr[i] &gt; largest) { secondLargest = largest; largest = arr[i]; } else if (arr[i] &gt; secondLargest &amp;&amp; arr[i] &lt;= largest) { secondLargest = arr[i]; } } return (largest + secondLargest); } </code></pre> <p><strong>Find whether an array as repeated elements, where it's known that the numbers of the array are between 1 and 100.</strong></p> <pre><code>bool contains_repeats(int* arr, int sz) { std::vector&lt;bool&gt; booVec(100,false); for (int i = 0; i &lt; sz; i++) { if (booVec[arr[i]-1]) { return true; } else { booVec[arr[i]-1] = true; } } return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T09:39:42.560", "Id": "53960", "Score": "1", "body": "a) It is unlikely that you would be asked for algorithmic alternatives in the interview b) everything in here revolves around arrays/\"list\"-structures. Unlikely as well during the interview c) You will not be asked in an interview to perform \"puristically\" or guru-istically. d) Top positions require long-standing previous initiative in the form of community-help, projects, formal endorsements, and publications. e) Breathe, relax, focus on your strong suits." } ]
[ { "body": "<ul>\n<li><p>Is the signature of the function imposed ? Your solution would work for any kind of iterable objects and would be probably more idiomatic than passing a pointer and a size. Also, the logic would work for any (comparable) types and not just <code>int</code> so it might be worth making it a templated function.</p></li>\n<li><p>In your search of the most common element, do you want to return the number of occurences or the element itself ?</p></li>\n<li><p>In your sum of the two biggest, I think you can compare to <code>largest</code> only once.</p></li>\n</ul>\n\n<p>You just need to do something like :</p>\n\n<pre><code> if (arr[i] &gt; secondLargest) {\n if (arr[i] &gt; largest) { \n secondLargest = largest; \n largest = arr[i];\n } else {\n secondLargest = arr[i]; \n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T10:42:01.047", "Id": "53963", "Score": "0", "body": "Correct. Good catch." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T10:14:22.397", "Id": "33698", "ParentId": "33690", "Score": "2" } }, { "body": "<p>Your <code>largest2</code> function has at least 3 errors, one of them will prevent the code from compiling: assignments like <code>secondLargest = largest</code>, comparision <code>arr[i] &gt; secondLargest</code> would not compile because the variable <code>secondLargest</code> is declared as an array:</p>\n\n<pre><code>secondLargest[arr[0]];\n</code></pre>\n\n<p>The same causes the final addition in</p>\n\n<pre><code>return (largest + secondLargest);\n</code></pre>\n\n<p>to become a pointer arithmetics, whose result may surprise you when converted to the function's return type (<code>int</code>).</p>\n\n<p>IMHO using parenthesized expression as an initializer for simple arithmetic types is a syntactic overkill compared to the old, good C-style 'equals' form. </p>\n\n<p>When you fix it, either by replacing with <code>secondLargest(arr[0])</code> or <code>secondLargest=arr[0]</code>, the function will produce incorrect result, for example for input array</p>\n\n<pre><code>int testarr[3] = {7, 2, 1};\n</code></pre>\n\n<p>It is quite obvious the largest term in this three-item array is 7 and the second-largest one is 2, isn't it? But your code will store <code>arr[0]</code>, which is <code>7</code>, both in <code>largest</code> and in <code>secondLargest</code>, so the value 2 will not get into account (it is not greater than 7, stored in <code>secondLargest</code>), and the result will be 14 = 7+7 instead of 9=7+2.</p>\n\n<p>You need to store <em>two</em> terms of the input array in your local variables instead of duplicating the first one. Of course, you need to sort them, so that the initial values of the <code>largest</code> and <code>secondLargest</code> actually are what variables' names say:</p>\n\n<pre><code> int largest = max(arr[0], arr[1]),\n secondLargest = min(arr[0], arr[1]);\n</code></pre>\n\n<p>That, however, does not cure the code yet! The routine still returns 14 for my <code>testarr</code>. The reason is a wrong starting point of your <code>for</code> loop.</p>\n\n<p>Once we store 7 in <code>largest</code> and 2 in <code>secondLargest</code>, you start a loop with <code>i = 0</code> ...and you compare <code>arr[0]</code> (which is 7) to <code>largest</code> first, then to <code>secondLargest</code>. As a result of those comparisions the apparently 'new' value gets stored as a new second-largest, thus making answer 14=7+7.</p>\n\n<p>The corrected code is:</p>\n\n<pre><code>int largest2(int* arr, int sz) { \n int largest = max(arr[0], arr[1]),\n secondLargest = min(arr[0], arr[1]);\n\n for (int i = 2; i &lt; sz; i++) { \n if (arr[i] &gt; largest) {\n secondLargest = largest; \n largest = arr[i];\n }\n else if (arr[i] &gt; secondLargest) { \n secondLargest = arr[i];\n }\n }\n return (largest + secondLargest);\n}\n</code></pre>\n\n<p>We may also simplify initialization a bit by putting a small value to both local variables - if it only is small enough, it will get overwritten by the actual largest and second-largest term of the array.\nSuch 'small enough' must be smaller than, or at most equal to the smaller of two first terms. Then we can start iteration from index <code>0</code> to consider all terms as candidates:</p>\n\n<pre><code>int largest2(int* arr, int sz) { \n int largest = min(arr[0], arr[1]),\n secondLargest = largest;\n\n for (int i = 0; i &lt; sz; i++) { \n if (arr[i] &gt; largest) {\n secondLargest = largest; \n largest = arr[i];\n }\n else if (arr[i] &gt; secondLargest) { \n secondLargest = arr[i];\n }\n }\n return (largest + secondLargest);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-04T23:30:46.857", "Id": "148944", "ParentId": "33690", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T05:49:32.983", "Id": "33690", "Score": "4", "Tags": [ "c++", "interview-questions" ], "Title": "Classic programming interview questions" }
33690
<pre><code>var textarea = document.getElementById("textarea"), statusBar = document.getElementById("status-bar"); function updateStatusBar() { var text = textarea.value, chars = text.length, words = text.split(/\b\S+\b/g).length - 1, lines = text.split("\n").length; statusBar.value = lines + " lines, " + words + " words, " + chars + " characters"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T06:24:14.053", "Id": "53954", "Score": "0", "body": "Well, looks good :) But it is better to add at least a few words on what you want to expect us to do..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T06:25:49.500", "Id": "53955", "Score": "0", "body": "possible duplicate of [Review of status bar code](http://codereview.stackexchange.com/questions/33637/review-of-status-bar-code)" } ]
[ { "body": "<p>I will give it a try:</p>\n\n<ul>\n<li><p>These days I would recommend using <em>document.querySelector</em>, to write generic code which is well amenable to code re-factoring without introducing bugs.</p>\n\n<p>So either:</p>\n\n<pre><code>var textarea = document.querySelector(\"#my-textarea\")\n ,statusBar = document.querySelector(\"#status-bar\");\n</code></pre>\n\n<p>or in later JavaScript versions, I believe >=1.6 (i.e. OK Server-side, when a specific JS-runtime can be guaranteed):</p>\n\n<pre><code>var [eltxtarea, elstatusbar] = document.querySelectorAll(\"#my-textarea,#status-bar\");\n</code></pre></li>\n<li><p>Do not assign elements to Id's that are also keywords/attributes in the HTML specification (as such not <em>textarea</em> but e.g. <em>my-textarea</em> )</p></li>\n<li><p>Bind the invocation of your function to an event or directly to underlying data-changes(requiring additional frameworks such as <a href=\"http://backbonejs.org/\" rel=\"nofollow\">backbone.js</a>). Do not use the respective exposed handler attribute but rather the <em>attachEventHandler</em>.</p>\n\n<pre><code>elstatusbar.attachEventHandler( \"change\", changeHandlerStatusbarUpdate);\n</code></pre></li>\n</ul>\n\n<p><strong>The Handler:</strong></p>\n\n<pre><code> var changeHandlerStatusbarUpdate = function(evt){\n if(evt instanceof Event &amp;&amp; evt.target instanceof HTMLTextAreaElement){ \n //you can be more specific. Event is just the Baseclass.\n //for instance you may test for \"KeyboardEvent\" only\n\n //the following logic should be improved: See threads of how to count words in a language/culture-specific fashion\n var text = textarea.value,\n chars = text.length,\n words = text.split(/\\b\\S+\\b/g).length - 1,\n lines = text.split(\"\\n\").length,\n stat = lines + \" lines, \" + words + \" words, \" + chars + \" characters\";\n evt.target.value = stat;\n }\n }\n</code></pre>\n\n<ul>\n<li>Do not put the <em>updateStatusBar</em> function in the global or window scope when the function relies upon <em>textarea</em> in the outside-scope, but use scope-encapsulation via closures (<a href=\"https://github.com/lsauer/KeyBoarder/blob/master/keyboarder.js\" rel=\"nofollow\">example</a>), or a retrieve the target element within the function or through the event-target in a handler-function.</li>\n</ul>\n\n<p>As pointed out in the source-comment, the word-counting is much to trivial and not \"culture-invariant\" as is the case right now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T10:27:25.393", "Id": "33700", "ParentId": "33691", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T06:11:09.833", "Id": "33691", "Score": "1", "Tags": [ "javascript", "html", "dom", "statistics" ], "Title": "Calculate number of words and characters (/statistics) from an HTML Textarea" }
33691
<p>I'm making a database program that reads from a file info on tennis players. Everything works, but is there a simpler way of doing this? Is there anything I can improve here? </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; const int MAX_PLAYERS = 5; struct player { char *fullname[2]; int age; double rating; char *racketBrand; }; typedef struct player tPlayer; void readData(tPlayer *player){ FILE *file = fopen("database", "r"); if(!file){ perror("File not found"); return; } int idx = 0; char buffer[50]; while(fgets(buffer, sizeof(buffer), file)){ player[idx].fullname[0] = malloc(20); player[idx].fullname[1] = malloc(20); player[idx].racketBrand = malloc(20); sscanf(buffer, "%s %s %d %lf %s", player[idx].fullname[0], player[idx].fullname[1], &amp;player[idx].age, &amp;player[idx].rating, player[idx].racketBrand); idx++; } fclose(file); } void printInfo(tPlayer *player){ int idx; for(idx = 0; idx &lt; MAX_PLAYERS; idx++){ printf("***Name: %s %s ***Age: %d ***Rating: %.1lf ***Racket Brand: %s\n", player[idx].fullname[0], player[idx].fullname[1], player[idx].age, player[idx].rating, player[idx].racketBrand); } } int main(){ tPlayer player[MAX_PLAYERS]; readData(player); printInfo(player); } </code></pre>
[]
[ { "body": "<p>This part hardly makes sense to me:</p>\n\n<pre><code> player[idx].fullname[0] = malloc(20);\n player[idx].fullname[1] = malloc(20);\n player[idx].racketBrand = malloc(20);\n</code></pre>\n\n<p>If you are always allocating 20 bytes for your strings, why bothering with a dynamic allocation? Simply declare your strings as <code>char whatever[20];</code>. If you want your dynamically allocated strings to actually allocate as much memory as is needed, things will go far more complicated (see my old answer <a href=\"https://codereview.stackexchange.com/a/31098/26493\">here</a>, although you'll need to adapt it).</p>\n\n<p>Your code does not allow for a tennis player to have more than one name and one surname, but I'll assume that this is on purpose. However, if we assume that your data file is not broken in a very specific way (i.e., having one player's data spread across more than one line), we could simply do this (assuming we also abandon dynamic memory allocation):</p>\n\n<pre><code>while (fscanf(file, \"%19s %19s %d %lf %19s\", player[idx].fullname[0], player[idx].fullname[1], &amp;player[idx].age, &amp;player[idx].rating, player[idx].racketBrand) == 5) idx++;\n</code></pre>\n\n<p>Unless there is a reason to assume that there are at most <code>MAX_PLAYERS</code> in the file, it would be better to dynamically allocate <code>player</code> (the main array), using <a href=\"http://linux.die.net/man/3/realloc\" rel=\"nofollow noreferrer\">realloc</a>. This is, of course, more complicated than your attempt, but it is also less limiting for the user.</p>\n\n<p>If you want to keep the limit on the number of players, you should also check it when reading the data, i.e., you should replace <code>idx++</code> with</p>\n\n<pre><code>if (idx++ &gt;= MAX_PLAYERS) break;\n</code></pre>\n\n<p>And a minor technical notion. You can replace</p>\n\n<pre><code>struct player {\n char *fullname[2];\n int age;\n double rating;\n char *racketBrand; \n}; typedef struct player tPlayer;\n</code></pre>\n\n<p>with</p>\n\n<pre><code>typedef struct player {\n char *fullname[2];\n int age;\n double rating;\n char *racketBrand; \n} tPlayer;\n</code></pre>\n\n<p>I am all for using <code>typedef</code>, but it is fair to warn you that <a href=\"https://stackoverflow.com/q/252780/1667018\">there are some disagreements about it</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T09:56:43.317", "Id": "33697", "ParentId": "33695", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T07:40:22.573", "Id": "33695", "Score": "2", "Tags": [ "c" ], "Title": "Reading in different datatypes from a file" }
33695
<p>I wrote a small Java class with documentation that is going to be a part of a library I am writing. I learned Java as my first programming language from many different sources on the web, and therefore I have developed my own style without any direct criticism along the way. So I would like some feedback on the class because I am unsure of what is good practice and what is just unnecessary. I am thinking mainly of the design and style, especially on the javadoc, but any other corrections or suggestions are also welcome.</p> <p>Some specific questions:</p> <ol> <li>Are the <code>DEFAULT_ACCEPT_TEXT</code> and <code>DEFAULT_CANCEL_TEXT</code> variables<br> overkill?</li> <li>Should I create methods for common operations on hidden<br> objects (e.g. <code>setAcceptText()</code>) or should I just add a method that<br> returns the object? In this case I did both.</li> <li>Should I merge the <code>accept()</code> and <code>cancel()</code> methods to something like: <code>setAccepted(boolean accepted)</code>? Like <code>java.awt.Window</code>'s <code>show()</code> and <code>hide()</code> methods were replaced by <code>setVisible(boolean visible)</code>.</li> </ol> <p>I realize that a lot of what I am asking is about personal preference and that as long as I am persistent, it is fine.</p> <p><strong>Test.java</strong></p> <pre><code>import java.awt.FlowLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import com.myname.gutil.ConfirmDialog; import com.myname.gutil.LookAndFeel; public class Test { public static void main(String[] args) { JPanel content = new JPanel(new FlowLayout()); JTextField input = new JTextField(12); content.add(new JLabel("Enter name:")); content.add(input); ConfirmDialog dialog = new ConfirmDialog("Test dialog", content); boolean yes = dialog.display(); System.out.println(input.getText() + " " + (yes ? "accepted" : "did not accept") + "."); } } </code></pre> <p><strong>ConfirmDialog.java</strong></p> <pre><code>package com.myname.gutil; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; /** * A dialog that lets the user either confirm or cancel. * * Display the dialog to the user by calling the {@link #display()} method. The text on the option * buttons can be changed by modifying the buttons returned by {@link #getAcceptButton()} and * {@link #getCancelButton()}. * */ public class ConfirmDialog extends JDialog { /** * The default accept button text. */ private static final String DEFAULT_ACCEPT_TEXT = "Accept"; /** * The default cancel button text. */ private static final String DEFAULT_CANCEL_TEXT = "Cancel"; /** * Whether the dialog is going to be accepted or not. */ private boolean accepted; /** * The main component of the dialog. */ private JComponent body; /** * The accept button. */ private JButton acceptButton; /** * The cancel button. */ private JButton cancelButton; /** * Creates a new confirm dialog without a body. */ public ConfirmDialog() { this(null, null, null); } /** * Creates a new confirm dialog without a body. * * @title the title */ public ConfirmDialog(String title) { this(title, null, null); } /** * Creates a new confirm dialog. * * @title the title * @param body the main component */ public ConfirmDialog(String title, JComponent body) { this(title, body, null); } /** * Creates a new confirm dialog with a location relative to the parent. * * @param title the title * @param body the main component * @param parent the parent */ public ConfirmDialog(String title, JComponent body, JFrame parent) { // Accept button acceptButton = new JButton(DEFAULT_ACCEPT_TEXT); acceptButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { accept(); } }); // Cancel button cancelButton = new JButton(DEFAULT_CANCEL_TEXT); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { cancel(); } }); // Add the option buttons JPanel optionPanel = new JPanel(); optionPanel.add(acceptButton); optionPanel.add(cancelButton); // Create the panel JPanel panel = new JPanel(); panel.setBorder(new EmptyBorder(5, 5, 5, 5)); panel.setLayout(new BorderLayout(0, 5)); if (body != null) panel.add(body, BorderLayout.CENTER); panel.add(optionPanel, BorderLayout.SOUTH); // Prepare the dialog setContentPane(panel); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); getRootPane().setDefaultButton(acceptButton); pack(); setLocationRelativeTo(parent); setMinimumSize(getPreferredSize()); setModal(true); setTitle(title); } /** * Accepts the dialog. */ public void accept() { accepted = true; dispose(); } /** * Cancels the dialog. */ public void cancel() { accepted = false; dispose(); } /** * Display the dialog until it is closed. * * @return true if it closed because the accept option was chosen */ public boolean display() { setVisible(true); return accepted; } /** * Returns the accept button. * * @return the button */ public JButton getAcceptButton() { return acceptButton; } /** * Returns the cancel button. * * @return the button */ public JButton getCancelButton() { return cancelButton; } /** * Returns the main component. * * @return the body */ public JComponent getBody() { return body; } /** * Sets the text of the accept button. * * @param text the text */ public void setAcceptText(String text) { acceptButton.setText(text); } /** * Sets the text of the cancel button. * * @param text the text */ public void setCancelText(String text) { cancelButton.setText(text); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T13:53:37.247", "Id": "73072", "Score": "0", "body": "Variables `DEFAULT_ACCEPT_TEXT, DEFAULT_CANCEL_TEXT` follows java naming convention for constants." } ]
[ { "body": "<p>You ask specific questions and the answers you get to them will be opinionated and subjective... but ...</p>\n\n<ol>\n<li>Using constants for the Defaults is a good thing. This will make subsequent efforts like i18n (internationalization) easier as the values can be replaced with resource lookups in just one place.</li>\n<li>You should not do both. Object Oriented programming guidelines suggest that you should encapsulate the internals of your object. You should not expose the inner workings. 'publishing' the actual inner objects is likely going to lead to issues later on. You should only allow others to do things to your object that you need to let them do, and they don't need. In your case I would remove the <code>getAcceptButton()</code> method, but this is subjective, and you may just need to remove the setAcceptText() and let the user customize the button fully. Doing both is a mistake though.</li>\n<li>The accept and cancel methods are fine, in principal, but what I worry about is why they are public. They should be private since the only place they should be called from is the <code>actionPerformed()</code> methods. How you do things in the private methods is up to you.</li>\n</ol>\n\n<p>As a general comment I think you have too many comments.... ;-) When methods and fields are private, and not part of the JavaDoc of the class then I suggest you use a less verbose style for your comments. This is especially true for obvious methods and variables.</p>\n\n<p>There is a lot of clutter in your code that relates to obvious things that just make it harder to read.</p>\n\n<p>All your private members have good names, and, for example, the code: </p>\n\n<pre><code>/**\n * Whether the dialog is going to be accepted or not.\n */\nprivate boolean accepted;\n........\n/**\n * The cancel button.\n */\nprivate JButton cancelButton;\n</code></pre>\n\n<p>is much better to be expressed as :</p>\n\n<pre><code>private boolean accepted;\nprivate JComponent body;\nprivate JButton acceptButton;\nprivate JButton cancelButton;\n</code></pre>\n\n<p>This is obvious, and there's no way for this to become a problem over time where the comments do not match the code. Your code should be self-documenting, which your code <strong>is</strong>, and as a result the actual comments are redundant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T14:34:37.940", "Id": "54024", "Score": "0", "body": "There are reasons to write javadoc for a private field. `accepted` might benefit from javadoc describing when and how the value gets set. `body` is not immediately obvious, so Peter's javadoc is beneficial. I agree that the javadoc for `acceptButton` and `cancelButton` is redundant; to quote Sun's [How to Write Doc Comments](http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html): **Add description beyond the API name.**… The ideal comment goes beyond those words and should always reward you with some bit of information that was not immediately obvious from the API name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T14:40:55.343", "Id": "54026", "Score": "0", "body": "Yes, there are reasons for private field comments, my point is that if you use 'self documenting' variable names (which essentially these are) then the comment is redundant. Adding a comment means you have two places to change when maintaining code. Getting the right balance is an art, and a fuzzy boundary. Perhaps I err too much to one side." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T21:44:32.930", "Id": "54049", "Score": "0", "body": "The `accepted` variable name is not self-documenting. The comment should stay or the variable be renamed. The `cancelButton` comment is completely redundant." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T18:05:46.747", "Id": "33714", "ParentId": "33699", "Score": "4" } }, { "body": "<p>My Points:</p>\n\n<ol>\n<li>No</li>\n<li>Yes</li>\n<li>Yes</li>\n</ol>\n\n<p>Other points:</p>\n\n<ul>\n<li>Cohesion is low. Please extrude the Listeners to seperate classes using an interface to change accepted/cancel captions.</li>\n<li>If you use a WeakReference to the dialog and call dispose, you never find out if the user clicked Accept or Cancel.</li>\n<li>Open-Close Principle sais you must depend on abstractions, so <code>parent</code> should be <code>Component</code> because <code>Component</code> is more abstract that <code>JComponent</code>. Also JButton is not abstract. The constructors should be AbstractButton instead. (I advise to not use CharSequence over String by the way).</li>\n<li>Demeters law is respected by 80%, thats another good thing. To improve that, drop the <code>setAcceptText</code> and <code>setCancelText</code> methods.</li>\n<li>I like to know more about the fields, you could documentate if null values are allowed and what happens if they are (in example a null title will be an empty title).</li>\n<li>Constructors are initialized async, if you call all constructors in one block, they will be executed mostly synthetic paralell.</li>\n<li>The package ends with <code>gutil</code>... Is gutil a abbrev for something else than Utils? If not that lets assume ConfirmDialog is a component, not a util class.</li>\n<li>ISP not affected here.</li>\n<li>SRP solved good.</li>\n<li>In the class javadoc please use a <code>&lt;p&gt;</code> tag for the second paragraph (only the open tag, not the close tag).</li>\n<li>Class is not thread-safe, please point that out.</li>\n<li>Class is not final, a possible superclass might be ConfirmRetryDialog but as I have no access to the <code>optionPanel</code>, I cant add a Retry-Button.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-01T10:31:41.310", "Id": "195626", "ParentId": "33699", "Score": "1" } } ]
{ "AcceptedAnswerId": "33714", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-11-02T10:18:55.320", "Id": "33699", "Score": "2", "Tags": [ "java", "swing", "library" ], "Title": "Swing UI confirmation dialog" }
33699
<p>I've written some code to solve <a href="http://projecteuler.net/problem=13" rel="nofollow">this problem</a>:</p> <blockquote> <p>Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.</p> </blockquote> <p>My solution functions correctly, but I'm having some trouble deciding how I should be handling exceptions, especially with regards to the class's constructor.</p> <p>I went the route of creating a <code>BigNumber</code> class, even though it's not necessary, as I've never solved a problem involving arbitrary-length numbers before. Here's the class, sans constructors:</p> <pre><code>class BigNumber { public static int MaxComponentValue = 999999999; public static int MaxComponentDigits = MaxComponentValue.ToString().Length; public bool Add(string source) { List&lt;int&gt; comps = this.SplitIntoComponents(source); // Not sure about this if (comps == null) return false; this.AllocateComponentSpace(comps.Count); for (int i = 0; i &lt; comps.Count; i++) { int componentSpace = MaxComponentValue - this.components[i]; int amountToCarry = comps[i] - componentSpace; if (amountToCarry &gt; 0) { while (amountToCarry &gt; MaxComponentValue) { amountToCarry -= MaxComponentValue + 1; this.components[i + 1]++; } this.components[i] = 0; this.components[i + 1]++; this.components[i] += amountToCarry - 1; } else this.components[i] += comps[i]; } return true; } public override string ToString() { if (this.components.Count() &gt; 1) { StringBuilder output = new StringBuilder(); var activeComponents = this.components.Reverse().SkipWhile(i =&gt; i == 0).ToList(); output.Append(activeComponents[0].ToString()); // Skip the first element as we've already added output for it. foreach (var c in activeComponents.Skip(1)) output.Append(String.Format("{0:000000000}", c)); return output.ToString(); } return this.components[0].ToString(); } private List&lt;int&gt; SplitIntoComponents(string source) { if (source == null) throw new ArgumentNullException("source"); List&lt;int&gt; comps = new List&lt;int&gt;(); for (int i = source.Length; i &gt; 0; i -= MaxComponentDigits) { string token; if (i &lt; MaxComponentDigits) token = source.Substring(0, i); else token = source.Substring(i - MaxComponentDigits, MaxComponentDigits); int comp; if (int.TryParse(token, out comp)) comps.Add(comp); else return null; } return comps; } private void AllocateComponentSpace(int count) { // The + 1 accounts for the possibility that there // will be an amount to carry over from the last token. // E.g 99 + 99 would result in the need for two components // to store the result 198 - the first one for 98 and the second for 1. if (this.components.Length &lt; count) Array.Resize(ref this.components, count + 1); } private int[] components = new int[1]; } </code></pre> <p><strong>Problem 1</strong></p> <p>In the private method <code>SplitIntoComponents</code>, if <code>int.TryParse</code> fails, I'm failing early and returning <code>null</code>. In the <code>Add</code> method, I call <code>SplitIntoComponents</code>, check if it has returned <code>null</code> and then return <code>false</code> to the caller if it has. The consequence of that is the <code>Add</code> method fails early, before modifying the data stored in the <code>BigNumber</code> instance.</p> <p>I have two questions. Firstly, should <code>SplitIntoComponents</code> be throwing instead of returning <code>null</code>? Secondly, should <code>Add</code> return <code>false</code> to the caller, or should that really be throwing an <code>ArgumentException</code>? I'm thinking <code>SplitIntoComponents</code> should stay as it is and then I should throw from <code>Add</code>.</p> <p><strong>Problem 2</strong></p> <p>I want to define a constructor that takes a string argument. This is what I have so far:</p> <pre><code>public BigNumber(string source) { if (source == null) throw new ArgumentNullException("source"); List&lt;int&gt; comps = this.SplitIntoComponents(source); if (comps == null) throw new ArgumentException(); // Not implemented yet } </code></pre> <p>In this case, I feel as though I should be throwing the <code>ArgumentException</code> because I'm unable to return anything to the caller. The problem here is obviously the inconsistency between how I'm handling the return value of <code>SplitIntoComponents</code> in the constructor and in the <code>Add</code> method.</p> <p>Should I opt for that and throw <code>ArgumentException</code>?</p> <p><strong>General Observations</strong></p> <ol> <li>I should overload the '+' operator to allow addition of multiple <code>BigNumber</code>s.</li> <li>Add some support for Linq (would that even work for <code>Sum</code>?)</li> </ol> <p>Any other suggestions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T14:21:20.267", "Id": "53969", "Score": "0", "body": "What was wrong with [`System.Numerics.BigInteger`](http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T14:22:14.873", "Id": "53970", "Score": "0", "body": "@GarethRees I wanted to learn something new. My algorithmic skills are a little weaker than I'd like, so this was a good exercise for me." } ]
[ { "body": "<p><strike>IMHO returning <code>null</code> as error handling is a misconception.</strike>\nI was wrong there, it is ok, but you have to use it consequently!</p>\n\n<p>Because you may have to make the \"exception handling\" in the consumer class twice. \nOne time for <code>Exceptions</code> and another time for <code>null</code> as return value. </p>\n\n<p>And as i can already see in your code it may cause you to make only a part of the exeption handling. \nSince your <code>Add</code> method handles the case that <code>SplitIntoComponents</code> returns <code>null</code> but doesn't handle the case that it may throw an <code>ArgumentNullException</code>.\nThis may be intentional i can't tell that because i can't see the call for <code>Add</code>.</p>\n\n<p>Use <code>TryParse</code> and throw a meaningfull <code>exeption</code>, instead of returning null .\n<strong>Or</strong> return null, instead of throwing an exception if source is null. \nBoth ways are ok, but only when they aren't used at the same time. \n(Which results in two Ways of exception handling in the consumer again.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:00:19.767", "Id": "54446", "Score": "0", "body": "Thank you for the response. `Since your Add method handles the case that SplitIntoComponents returns null but doesn't handle the case that it may throw an ArgumentNullException.` This is basically where my confusion lies, which is probably why my intention is unclear. My specific thinking was that as I'm checking for `source` being `null`, when it's passed to `Add`, does it still make sense to check for `source` being `null` when it's passed to `SplitIntoComponents`, bearing in mind that it's a private method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:08:10.290", "Id": "54447", "Score": "0", "body": "In fact, that problem is the whole reason I decided to return `bool` from `Add` - to signify whether or not the operation was successful. However, that also seems unintuitive. It seems to make more sense for `Add` to have a void return type, simply throwing exceptions where necessary. So in that sense, perhaps it would be better to check for `source` being `null` and then `if (comps == null) throw new ArgumentException(\"Must only contain numbers.\", \"source\");`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T15:09:18.250", "Id": "54448", "Score": "0", "body": "As for your last point about `TryParse`, I'm not sure I understand. `TryParse` doesn't throw, which is why I chose it. My thinking was that if I throw from `SplitIntoComponents`, because of `source` being an invalid argument, the real problem lies in what was passed to `Add`, so throwing from `SplitIntoComponents`, rather than `Add`, obfuscates the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T09:14:25.710", "Id": "54555", "Score": "0", "body": "\" \nIn fact, that problem is the whole reason I decided to return bool from Add - to signify whether or not the operation was successful. However, that also seems unintuitive.\" Some my say that, but i like to do it that way ,too. Just make sure it doesnt throw an exception in any case, or you have to handle two cases again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T09:28:07.230", "Id": "54559", "Score": "0", "body": "@John H I edited my answere to be more clear, i hope it includes your comments now." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T09:45:02.687", "Id": "33911", "ParentId": "33706", "Score": "1" } }, { "body": "<p>I'll self-answer this as my approach now is quite different from anything else mentioned here.</p>\n\n<p>The constructor idea was essentially the root of the problem, because I was asking it to do too much. With that said, I decided to create a static method to separately handle the parsing of a string:</p>\n\n<pre><code>public static BigNumber Parse(string source)\n{\n //\n}\n</code></pre>\n\n<p>This now means two things:</p>\n\n<ol>\n<li>I can make the exception handling logic consistent between the <code>Parse</code> and <code>Add</code> methods, allowing me to refactor it further at some point. </li>\n<li>The constructor is no longer responsible for handling parsing (which it shouldn't have been to begin with).</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:54:21.657", "Id": "36520", "ParentId": "33706", "Score": "1" } } ]
{ "AcceptedAnswerId": "36520", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T14:16:40.173", "Id": "33706", "Score": "1", "Tags": [ "c#", "project-euler" ], "Title": "Project Euler: Problem 13 - Large Sum" }
33706
<p>Might there be a simpler way to write this code? I'd like to learn to write code more efficiently.</p> <pre><code>def leaves_and_internals(self): """(BTNode) -&gt; ([object], [object]) Return a pair of lists: (list of all the items stored in the leaves of the subtree rooted at this node, list of all the items stored in the internal nodes of the subtree rooted at this node). """ leaves = [] internal = [] if self.left is None and self.right is None: leaves.append(self.item) else: internal.append(self.item) if self.left: subleaf, subinternal = self.left.leaves_and_internals() leaves.extend(subleaf) internal.extend(subinternal) if self.right: subleaf, subinternal = self.right.leaves_and_internals() leaves.extend(subleaf) internal.extend(subinternal) return (leaves, internal) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T22:16:48.103", "Id": "54050", "Score": "0", "body": "You don't seem to have taken the comments on [your previous question](http://codereview.stackexchange.com/q/33662/11728) into account." } ]
[ { "body": "<p>In the docstring, I would mention that the traversal is done using pre-order.</p>\n\n<p>I suggest handling leaf nodes as a base case and returning early.</p>\n\n<p>The left and right child nodes can be handled using common code.</p>\n\n<pre><code>def leaves_and_internals(self):\n \"\"\"(BTNode) -&gt; ([object], [object])\n Return a pair of lists: (list of all the items stored in the leaves of\n the subtree rooted at this node, list of all the items stored in the\n internal nodes of the subtree rooted at this node), according to a\n pre-order traversal.\n \"\"\"\n\n if self.left is None and self.right is None:\n return ([self.item], [])\n\n leaves, internal = [], [self.item]\n for child in [self.left, self.right]:\n if child is not None:\n subleaf, subinternal = child.leaves_and_internals()\n leaves.extend(subleaf)\n internal.extend(subinternal)\n return (leaves, internal)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T22:27:44.243", "Id": "54051", "Score": "0", "body": "It's a bit O(n^2), though, isn't it?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T22:23:05.660", "Id": "33758", "ParentId": "33711", "Score": "0" } }, { "body": "<p>Here's a more efficient version that avoids copying list elements. Instead, it creates just two empty lists and appends to them during the traversal.</p>\n\n<pre><code>def leaves_and_internals(self):\n \"\"\"(BTNode) -&gt; ([object], [object])\n Return a pair of lists: (list of all the items stored in the leaves of\n the subtree rooted at this node, list of all the items stored in the\n internal nodes of the subtree rooted at this node), according to a\n pre-order traversal.\n \"\"\"\n def helper(self, leaves, internal):\n if self.left is None and self.right is None:\n leaves.append(self.item)\n else:\n internal.append(self.item)\n for child in [self.left, self.right]:\n if child is not None:\n helper(child, leaves, internal)\n return (leaves, internal)\n return helper(self, [], [])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T09:10:19.217", "Id": "54097", "Score": "0", "body": "+1, but this approach is prone to stack overflow for big trees, as I pointed out in [my answer to the OP's other question](http://codereview.stackexchange.com/a/33701/11728)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T22:55:12.547", "Id": "33760", "ParentId": "33711", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T16:06:02.190", "Id": "33711", "Score": "0", "Tags": [ "python", "python-3.x", "tree", "depth-first-search" ], "Title": "How to enumerate the internal nodes and leaves of a tree more elegantly?" }
33711
<p>In an old project I tinker with from time to time, I have a DOM-like structure in an MMF database. I'd like the nodes to <em>act</em> like they have some C++ typing based on the content, and accessor methods that go along with that. Yet in actuality, the data is independent of the type system in C++.</p> <p><em>The problems with trying to do this are pretty analogous to situations like <a href="http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch" rel="nofollow noreferrer">Object Relational Impedance Mismatch</a>. So it's not going to be perfect; it's more of a helpful bookkeeping tool than anything. Some background reading of prior feedback: <a href="https://stackoverflow.com/questions/11167483/deriving-from-a-base-class-whose-instances-reside-in-a-fixed-format-database-m">first</a>, <a href="https://stackoverflow.com/questions/11219159/make-interchangeable-class-types-via-pointer-casting-only-without-having-to-all">second</a></em></p> <p>Another thing I wanted was to get solid control of the nodes. I don't want client code to leak them, or store handles to them past certain clearly delineated phases. This means I need something akin to smart pointers...and all factory creation with private destructors that are friends of <code>std::default_delete</code>. I also have to bundle some context information with the handle instances that are passed into user code.</p> <p>I've simplified the pattern down a single-file example that with a really basic datatype that you can compile, if you like:</p> <p><strong><a href="https://gist.github.com/hostilefork/7280477#file-facade-cpp" rel="nofollow noreferrer">facade.cpp (gist.github.com)</a></strong></p> <p>But I've included the relevant classes in a reduced form here. There's an internal class called <strong>FooPrivate</strong>, which is very simple; representing our basic behavior of the data item:</p> <pre><code>class FooPrivate final { /* ... */ private: FooPrivate (int value) : _value (value) { } ~FooPrivate () { } private: static unique_ptr&lt;FooPrivate&gt; create(int value) { return unique_ptr&lt;FooPrivate&gt; (new FooPrivate (value)); } public: FooPrivate * consume(unique_ptr&lt;FooPrivate&gt; &amp;&amp; other) { _value += other-&gt;_value; FooPrivate * result (other.release()); consumed.push_back(result); return result; } void setValue(int value) { _value = value; } int getValue() const { return _value; } private: int _value; vector&lt;FooPrivate *&gt; consumed; }; </code></pre> <p>Simple case here for the data is you can access an integer with <code>getValue()</code> and <code>setValue()</code>. A <code>consume()</code> function is an example of something that takes transfer of ownership to the data structure.</p> <p>The next step is a handle and accessor for client use called <strong>Foo</strong>. For simplicity, the context is just a boolean. Each Foo contains a raw FooPrivate pointer and a shared pointer to a <strong>Context</strong>.</p> <pre><code>class Context final { /* ... */ private: Context (bool valid) : _valid (valid) { } private: bool _valid; }; </code></pre> <p>Foo has a method matching every method in FooPrivate. But there is added checking of the Context, as well as preventing raw FooPrivate pointers from leaking into user code:</p> <pre><code>class Foo { /* ... */ private: void setInternals(FooPrivate * fooPrivate, shared_ptr&lt;Context&gt; context) { _fooPrivate = fooPrivate; _context = context; } protected: Foo () { setInternals(nullptr, nullptr); } private: Foo (FooPrivate * fooPrivate, shared_ptr&lt;Context&gt; context) { setInternals(fooPrivate, context); } FooPrivate const &amp; getFooPrivate() const { if (not _context-&gt;_valid) { throw "Attempt to dereference invalid Foo handle."; } return *_fooPrivate; } FooPrivate &amp; getFooPrivate() { if (not _context-&gt;_valid) { throw "Attempt to dereference invalid Foo handle."; } return *_fooPrivate; } public: template&lt;class FooType&gt; Reference&lt;FooType&gt; consume(Owned&lt;FooType&gt; &amp;&amp; foo) { return Reference&lt;FooType&gt; ( getFooPrivate().consume(move(foo.extractFooPrivate())), shared_ptr&lt;Context&gt; (new Context (false)) ); } void setValue(int value) { getFooPrivate().setValue(value); } int getValue() const { return getFooPrivate().getValue(); } private: FooPrivate * _fooPrivate; shared_ptr&lt;Context&gt; _context; }; </code></pre> <p>Further up from that is a template for <strong>Reference</strong>. It's basically equivalent to a Foo, but is parameterized by a subclass of Foo. It uses the pointer dereference operator to invoke methods coming from that subclass.</p> <pre><code>template&lt;class FooType&gt; class Reference { /* ... */ private: Reference (FooPrivate * fooPrivate, shared_ptr&lt;Context&gt; context) { /* ... */ _foo.setInternals(fooPrivate, context); } public: Reference (Foo &amp; foo) : _foo (foo) { } template&lt;class OtherFooType&gt; Reference (Reference&lt;OtherFooType&gt; &amp; other) { /* ... */ _foo.setInternals(other._fooPrivate, other._context); } FooType * operator-&gt; () { return &amp;_foo; } FooType const * operator-&gt; () const { return &amp;_foo; } FooType &amp; getFoo() { return _foo; } FooType const &amp; getFoo() const { return _foo; } private: FooType _foo; }; </code></pre> <p>Finally there is <strong>Owned</strong>; an analogue to unique_ptr that has similar behavior to FooReference. The Foo version of consume--for instance--takes an <code>Owned&lt;FooType&gt;</code> instead of a <code>unique_ptr&lt;FooPrivate&gt;</code>.</p> <pre><code>template&lt;class FooType&gt; class Owned { /* ... */ private: Owned ( unique_ptr&lt;FooPrivate&gt; &amp;&amp; fooPrivate, shared_ptr&lt;Context&gt; context ) { /* ... */ _foo.setInternals(fooPrivate.release(), context); } unique_ptr&lt;FooPrivate&gt; extractFooPrivate() { unique_ptr&lt;FooPrivate&gt; result (_foo._fooPrivate); _foo.setInternals(nullptr, nullptr); return result; } /* ... */ public: static Owned&lt;FooType&gt; create(int value) { return Owned&lt;FooType&gt; ( FooPrivate::create(value), shared_ptr&lt;Context&gt; (new Context (true)) ); } template&lt;class OtherFooType&gt; Owned (Owned&lt;OtherFooType&gt; &amp;&amp; other) { /* ... */ _foo.setInternals( other.extractFooPrivate().release(), other._foo._context ); } template&lt;class OtherFooType&gt; Owned&lt;FooType&gt; operator= (Owned&lt;OtherFooType&gt; &amp;&amp; other) { /* ... */ return Owned&lt;FooType&gt; (other.extractFooPrivate(), other._context); } FooType * operator-&gt; () { return &amp;_foo; } FooType const * operator-&gt; () const { return &amp;_foo; } FooType &amp; getFoo() { return _foo; } FooType const &amp; getFoo() const { return _foo; } private: FooType _foo; }; </code></pre> <p>To make things extra boring for this reduced example, you can't use that Reference for anything after the transfer <em>(to demonstrate an instance of expiring a Context without adding more methods or other classes)</em>.</p> <p>Here is a useless demonstration:</p> <pre><code>class DoublingFoo : public Foo { public: int getDoubleValue() const { return Foo::getValue() * 2; } Reference&lt;Foo&gt; consumeHelper(int value) { return consume(Owned&lt;Foo&gt;::create(value * 2)); } }; int main() { auto parent (Owned&lt;DoublingFoo&gt;::create(10)); auto child (Owned&lt;Foo&gt;::create(20)); parent-&gt;consumeHelper(30); Reference&lt;Foo&gt; childReference (parent-&gt;consume(move(child))); cout &lt;&lt; "The value is " &lt;&lt; parent-&gt;getDoubleValue() &lt;&lt; "\n"; return 0; } </code></pre> <p>I guess some of my big questions would be:</p> <ul> <li><p>Have any existing library authors faced a similar desire and done it better?</p></li> <li><p>Any undefined behavior or other Really Bad Things I'm setting myself up for?</p></li> <li><p>The technique seems to require those making Foo-derived classes to inherit publicly from Foo. But narrowing the methods vs. just adding to them could be useful too. How could one do something like this with protected inheritance?</p></li> <li><p>Is putting the <code>create()</code> method as a static member of Owned the right place for it? Is there a good way to make it so that the authors of a Foo subclass could more elegantly make their own construction methods, while keeping the tight control of making sure everything is wrapped in an Owned?</p></li> </ul> <p>But all feedback is welcome. So if anyone wants to get out a red pen and suggest better style on something not directly related to the pattern, that's great too...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T14:44:59.697", "Id": "67499", "Score": "0", "body": "Would you mind including the other classes from Github into the text of this question? I'm having a hard time understanding it based on only your descriptions of these classes, without seeing the code on Github. For details please read [Can I put my code on a third party site and link to the site in my question?](http://meta.codereview.stackexchange.com/a/1309/34757)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:13:56.457", "Id": "67575", "Score": "0", "body": "@ChrisW Wasn't aware of the FAQ issue. I'm still linking the code for those who might want to tinker with it in a fully compilable way, but have put in all the participating classes, minus static asserts / friend declarations / comments. Thanks!" } ]
[ { "body": "<p>At least right now, I have only a few comments, and they're about style, not the pattern you've devised. First, I'm rather bothered by the number and redundancy of access specifiers in your code. For example:</p>\n\n<pre><code>class FooPrivate final { \n\n friend class Foo;\n template&lt;class&gt; friend class Reference;\n template&lt;class&gt; friend class Owned;\n template&lt;class&gt; friend struct std::default_delete;\n\nprivate:\n FooPrivate (int value) : _value (value) { }\n\n virtual ~FooPrivate () { }\n\nprivate:\n static unique_ptr&lt;FooPrivate&gt; create(int value) {\n return unique_ptr&lt;FooPrivate&gt; (new FooPrivate (value));\n }\n\npublic:\n FooPrivate * consume(unique_ptr&lt;FooPrivate&gt; &amp;&amp; other) {\n _value += other-&gt;_value;\n\n FooPrivate * result (other.release());\n _consumed.push_back(result);\n return result;\n }\n\n void setValue(int value) { _value = value; }\n\n int getValue() const { return _value; }\n\nprivate:\n int _value;\n vector&lt;FooPrivate *&gt; _consumed;\n};\n</code></pre>\n\n<p>I'd rather see code that sorted the members so I can see all the public \"stuff\" together, and as soon as I get to a <code>private:</code> access specifier, know that the rest of the class is private.</p>\n\n<pre><code>struct FooPrivate final {\n FooPrivate * consume(unique_ptr&lt;FooPrivate&gt; &amp;&amp; other) {\n _value += other-&gt;_value;\n\n FooPrivate * result(other.release());\n _consumed.push_back(result);\n return result;\n }\n\n void setValue(int value) { _value = value; }\n\n int getValue() const { return _value; }\n\nprivate:\n friend class Foo;\n template&lt;class&gt; friend class Reference;\n template&lt;class&gt; friend class Owned;\n template&lt;class&gt; friend struct std::default_delete;\n\n FooPrivate(int value) : _value(value) { }\n\n virtual ~FooPrivate() { }\n\n static unique_ptr&lt;FooPrivate&gt; create(int value) {\n return unique_ptr&lt;FooPrivate&gt;(new FooPrivate(value));\n }\n\n int _value;\n vector&lt;FooPrivate *&gt; _consumed;\n};\n</code></pre>\n\n<p>Second (shown in the code above), <code>setValue</code> and <code>getValue</code> bug the heck out of me. As it stands right, they provide no real encapsulation. You have, in effect, a public <code>int</code>, but with really ugly syntax. If the intent is really that <code>_value</code> be publicly accessible, just make it publicly accessible. Lots of people get religious about making data private, then having get/set pairs to essentially make it public again. It's a pointless waste of code not only in the class but also (worse) in the client code.</p>\n\n<p>Yes, it's generally better to provide higher-level, more meaningful actions that simply retrieve the value and set the value--but in some cases that's really all you want or need--and when/if that's the case, don't try to hide it behind the subterfuge of a get/set pair. Do what it's going to do directly and cleanly by making that member public.</p>\n\n<p>Conversely, if you're going to encapsulate that value, truly encapsulate it. Don't just hide it behind an accessor and mutator, but provide some <em>meaningful</em> higher-level constructs that keep the value truly hidden, and provide a higher level of abstraction to the outside world. </p>\n\n<p>As it stands right now, the user gets the worst of both worlds--a low-level interface and ugly syntax, so (for example) code that could have been <code>x._value += 5;</code> ends up as: <code>s.setValue(x.getValue() + 5);</code>. This is <em>not</em> an improvement in any way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-08T14:53:58.010", "Id": "99407", "Score": "0", "body": "Thanks for the feedback. This question has been around for a long time, and bountied twice, but as nobody seems to think it causes undefined behavior or anything, I'm going to assume it's okay. :-) I've been on the fence about whether to put all private members/methods at the end of class definitions. It does make it easier for others to use the header as documentation of a public interface, but it's not always an ideal grouping of related things while developing. I can't allow direct member access in the actual case, but I did lose the \"get\" so the pattern is more `s.setValue(x.value()+5);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-08T18:03:55.420", "Id": "99462", "Score": "0", "body": "Incidentally, if you are feeling generous and just want to weigh in on *\"hmm, I've seen something like that before\"* or *\"hey wait...that is a terrible idea\"* or *\"you know what might be better?\"* I did eventually put a completely gutted version of this project on GitHub, and I wrote a little blurb about it today: http://methyl.hostilefork.com/" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-29T15:37:28.623", "Id": "55614", "ParentId": "33713", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T17:11:09.170", "Id": "33713", "Score": "10", "Tags": [ "c++", "design-patterns", "c++11" ], "Title": "Proxy/Facade Implementation Concept in C++11, impedance matching DB with classes" }
33713
<p>I started learning OOP in JavaScript at school and I have to do my homework in OOP. It is a shopping list, one fills in a product and price and that is put into an array, the array its contents are put in a table in HTML. The list also has got delete buttons for every product, I have thought about using <code>this</code> in JavaScript, as I am working in OOP, but I am sceptic because of the scope.</p> <p>The idea is that one clicks "verwijder" on the webpage (EDIT: in the corresponding row) and the table row is gone. I have thought about using <code>this</code> but also about dynamically updating the table after removing the selected row from the array.</p> <p>Who can advise me about what to do and how to do that correctly? I have uploaded my JavaScript here: <a href="http://jsfiddle.net/hNAZ9/" rel="nofollow">http://jsfiddle.net/hNAZ9/</a></p> <p>Mainly, it is about this piece of code:</p> <pre><code> function ShoppingList(){ this.items = []; this.setItem = function(product, price){ var item = new Item(product, price); this.items.push(item); }; this.render = function(){ var placeHolder = document.getElementById("shoppingList"); placeHolder.innerHTML = ""; for(var i = 0; i &lt;this.items.length; i++){ var tr = document.createElement("tr"); tr.id = i; var tdProduct = document.createElement("td"); tdProduct.innerHTML = this.items[i].product; tr.appendChild(tdProduct); var tdPrice = document.createElement("td"); tdPrice.innerHTML = this.items[i].price; tr.appendChild(tdPrice); var tdDel = document.createElement("td"); tdDel.innerHTML = "Verwijder"; tdDel.addEventListener("click", delItem, false); tr.appendChild(tdDel); placeHolder.appendChild(tr); } }; } function delItem(e){ e.preventDefault(); // What do I have to do here? } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T18:42:03.383", "Id": "53984", "Score": "3", "body": "You actually have a decent start right there with proper separation of concerns - actually better than most code I see in the web so for starters - good work. \n\nSome things I'd do differently:\n\n - That `getElementById` call inside `.render` is not needed. You can make that DOM query once and then have a reference to that element. Also, the function you're looking for for removing elements from the array is `.splice`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T19:27:23.243", "Id": "53985", "Score": "0", "body": "@BenjaminGruenbaum: Wow, thank you for your response, I am glad to hear that you are very content. :)\nI will look into the `getElementById` inside of `.render` and I will also look into the function `.splice` and its usage. Thank you a lot for your very helpful comment!" } ]
[ { "body": "<p>The trick is linking a row to its item object and vice-versa, so both are removed/added in lockstep.</p>\n\n<p>There are <em>a lot</em> of ways of going about that, but given your original code, the following should be a pretty good way to go.</p>\n\n<p>I'd suggest using a closure when defining the event handler to make things simpler. <a href=\"http://jsfiddle.net/4u7gE/1/\" rel=\"nofollow\">Here's a simple demo</a> and here's the code</p>\n\n<pre><code>function ShoppingList() {\n var that = this, // keep a scope reference\n table = document.getElementById(\"shoppingList\"); // find this once (only works if the page has been loaded already)\n\n this.items = [];\n\n // this adds an item to the array and a row to the table\n this.addItem = function (product, price) {\n var item = new Item(product, price);\n this.items.push(item);\n table.appendChild(buildRow(item));\n };\n\n // this removes the given item from the array and the table\n this.removeItem = function (item) {\n for(var i = 0 ; i &lt; this.items.length ; i++) {\n if(this.items[i] === item) {\n this.items.splice(i, 1);\n break; // skip the rest of the loop, since we've found what we need\n }\n }\n table.removeChild(item.row); // remove the row\n }\n\n // this isn't actually needed as rows get added by addItem,\n // but it'll work just fine regardless\n this.render = function(){\n table.innerHTML = \"\";\n for(var i = 0; i &lt; this.items.length; i++){\n table.appendChild(buildRow(this.items[i]));\n }\n };\n\n // an internal helper. This can be moved to the Item prototype\n // since it's not actually dependent on anything in ShoppingList\n function buildRow(item) {\n // an internal, internal helper\n function buildCell(text) {\n var td = document.createElement(\"td\");\n td.innerHTML = text;\n return td;\n }\n\n // store the table row object on the item itself\n item.row = document.createElement(\"tr\");\n\n item.row.appendChild(buildCell(item.product));\n item.row.appendChild(buildCell(item.price));\n\n var deleteCell = buildCell(\"Verwijder\");\n item.row.appendChild(deleteCell);\n\n // set the event listener here, where we can access `item` and `tr`\n deleteCell.addEventListener(\"click\", function () {\n that.removeItem(item); // remove the item. Here we need the `that` var\n }, false);\n\n return item.row;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T14:01:58.880", "Id": "33737", "ParentId": "33715", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T18:09:23.543", "Id": "33715", "Score": "3", "Tags": [ "javascript", "object-oriented", "html5" ], "Title": "Deleting a table row in JavaScript with OOP" }
33715
<p>I understand that if you don't know the trick, it's not easy create a solution with a complexity of \$O(N)\$. However, I would like to ask you how to solve this tricky question:</p> <blockquote> <p>You are given two non-empty zero-indexed arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river. The fish are numbered from 0 to N − 1, fish number P is represented by <code>A[P]</code> and <code>B[P]</code>, and if P &lt; Q then fish P is initially upstream of fish Q. Initially, each fish has a unique position. Array A contains the sizes of the fish. All its elements are > unique. Array B contains the directions of the fish. It contains only 0s and/or 1s, where:</p> <pre><code>0 represents a fish flowing upstream 1 represents a fish flowing downstream </code></pre> <p>If two fish move in opposite directions and there are no other (living) fish between them, they will eventually meet each other. Then only one fish can stay alive − the larger fish eats the smaller one. More precisely, we say that two fish P and Q meet each other when P &lt; Q, <code>B[P]</code> = 1 and <code>B[Q]</code> = 0, and there are no living fish between them. After they meet:</p> <pre><code>If A[P] &gt; A[Q] then P eats Q, and P will still be flowing downstream, If A[Q] &gt; A[P] then Q eats P, and Q will still be flowing upstream. </code></pre> <p>We assume that all the fish are flowing at the same speed. That is, fish moving in the same direction never meet. The goal is to calculate the number of fish that will stay alive.</p> <p>For example, consider arrays A and B such that:</p> <pre><code>A[0] = 4 B[0] = 0 A[1] = 3 B[1] = 1 A[2] = 2 B[2] = 0 A[3] = 1 B[3] = 0 A[4] = 5 B[4] = 0 </code></pre> <p>Initially all the fish are alive and all except fish number 1 are moving upstream. Fish > number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too. Finally, it meets fish number 4 and is eaten by it. The remaining two fish, numbers 0 and 4, never meet and therefore stay alive.</p> <p>Write a function:</p> <pre><code>class Solution { public int solution(int[] A, int[] B); } </code></pre> <p>that, given two non-empty zero-indexed arrays A and B consisting of N integers, returns the number of fish that will stay alive.</p> <p>For example, given the arrays shown above, the function should return 2, as explained above.</p> <p>Assume that:</p> <p>N is an integer within the range [1..100,000], where each element of array A is an integer within the range [0..1,000,000,000], where each element of array B is an integer that can have one of the following values: 0, 1, where the elements of A are all distinct.</p> <p>Complexity:</p> <p>expected worst-case time complexity is O(N); <br> expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).</p> </blockquote> <p>My solution:</p> <pre><code>import java.util.Stack; class Solution { public int solution(int[] A, int[] B) { int n = A.length; if (n&lt;1 || n&gt;100000) return -1; int alive = n; Stack&lt;Integer&gt; down = new Stack&lt;Integer&gt;(); // array to check if a fish has died boolean[] lives = new boolean[n]; for (int i=0;i&lt;n;i++) lives[i]=true; // the first fish with 1 is going to the right and will try // to eat other fishes in opposite direction // but if the fish is bigger it will comeback and it will eat other fishes in opposite direction for (int i=0,k=i+1; i&lt;n-1;i++) { if (B[i]==0) continue; for (;k&lt;n;k++){ // I save in a stack all the fishes in the same direction so in this way //I don't have to check again back if there is some fish //that is bigger than the fish that has been capable to eat the "i" fish if (B[i]==B[k] &amp;&amp; B[i]==1) down.push(k); if (A[i]&gt;A[k] &amp;&amp; B[i]!=B[k] &amp;&amp; B[i]==1 &amp;&amp; lives[k]){ alive--; lives[k]=false; } else if (A[i]&lt;A[k]&amp;&amp;B[i]!=B[k]&amp;&amp;B[i]==1 &amp;&amp; lives[i]) { alive--; lives[i]=false; //k fish eat i fish and I try to check if exists some i+1 to i-1 //fish that is opposite to k fish and could eat "k" fish while(!down.empty() &amp;&amp; i!=down.peek()){ i=down.pop(); if (A[i]&lt;A[k] &amp;&amp; lives[i]) { alive--; lives[i]=false; } else if (A[i]&gt;A[k] &amp;&amp; lives[k]){ alive--; lives[k]=false; break; } } } } } return alive; } } </code></pre> <p>This solution is not completely right! I found the right solution but in \$O(N^2)\$ time. I was trying to reach \$O(N)\$. If you want to test, check <a href="http://codility.com/demo/take-sample-test/fish" rel="noreferrer">this URL</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T19:53:29.130", "Id": "53990", "Score": "2", "body": "Would you mind summarizing what the problem is asking for and a brief explanation of your algorithm? That's way too much junk to try to figure out what's going on for ourselves." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T21:20:51.153", "Id": "53994", "Score": "0", "body": "In bold I tried to explain what I was looking for. Thank you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T03:32:11.283", "Id": "54004", "Score": "0", "body": "you should avoid naming the variables as A, B, n etc" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T16:44:57.250", "Id": "54034", "Score": "0", "body": "I used the same variable of the prototype method" } ]
[ { "body": "<pre><code>import java.util.Stack;\nclass Solution {\n /* A POD struct to aggregate fish that will be eaten or not eaten together */\n /* If the front fish is larger than any fish in the school (ie they are ordered) */\n /* and the front fish is eaten, the rest of the school will also definitely be */\n /* eaten. Any fish that the front fish can eat will not be able to eat the rest */\n /* of the school. */\n /* Technically this does not help with O(n) since, if all fish are out of order */\n /* there will only be n schools of 1 fish, just like keeping a stack of ints. */\n /* However, in the average case this will cut out a lot of comparisons */\n private class School {\n public int count;\n public int largest;\n public School() {\n this.count = 0;\n this.largest = 0;\n }\n public School(int size) {\n this.count = 1;\n this.largest = size;\n }\n }\n private final int UP = 0, DOWN = 1;\n public int solution(int[] A, int[] B) {\n /* number of fish swimming toward i=0 whose index &lt; i that are alive */\n int alive = 0;\n int i = 0, n = A.length;\n /* All live fish swimming toward i=n whose index &lt; i are accounted for here */\n Stack&lt;School&gt; down = new Stack&lt;School&gt;();\n /* Simpler if down is never empty, so push an empty school */\n down.push(new School());\n /* Fish swimming toward 0 with no opposite-swimming fish are in the clear */\n while (i &lt; n &amp;&amp; B[i] == UP) {\n alive++;\n i++;\n }\n while (i &lt; n) {\n if (B[i] == DOWN) {\n School top = down.peek();\n /* is fish i big enough to protect the School behind it? */\n if (A[i] &gt;= top.largest) {\n top.count++;\n top.largest = A[i];\n } else {\n /* or is it on its own? */\n down.push(new School(A[i]));\n }\n } else {\n School top = down.pop(); \n /* This inner loop is ok for linear time - see below */\n /* Fish i will meet the stack's top and either eat it or be eaten */\n /* It keeps eating fish from the stack until emptied or it's eaten */\n while (top.largest &lt; A[i] &amp;&amp; !down.empty()) {\n top = down.pop();\n }\n /* If it wasn't eaten by now, it's in the clear */\n if (top.largest &lt; A[i]) {\n alive++;\n /* hackish, but it works to ensure that the stack is never empty */\n down.push(new School());\n } else {\n down.push(top);\n }\n }\n i++;\n }\n /* All the fish swimming toward increasing i are alive, too */\n while (!down.empty()) {\n alive += down.pop().count;\n }\n return alive;\n }\n}\n</code></pre>\n\n<p>Let \\$X(i)\\$ be the number of iterations of the inner loop actually performed for iteration \\$i\\$ of the outer loop. \\$X(i)\\$ may be at most \\$i\\$, but \\$X(i+1)\\$ is at most \\$1 + i - X(i)\\$ because each additional comparison beyond 1 removes an element from the stack. Therefore, the sum of \\$X(0)\\$ to \\$X(i)\\$ can be no greater than \\$i\\$. That is, the sum of iterations of the inner loop can't exceed \\$N\\$ for \\$N\\$ elements. The rest (assuming \\$k\\$ time allocation, etc etc) is \\$k\\$ time per iteration, so the outer loop turns out \\$O(n)\\$.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T16:43:04.817", "Id": "54033", "Score": "0", "body": "/* All live fish swimming toward i=n whose index < i are accounted for here */\n Stack<School> down = new Stack<School>(); is better :) Great job! Now I will study it! I was thinking why did you need to model an object for that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T07:48:05.603", "Id": "54087", "Score": "0", "body": "@200_success I wrote it with the idea in my head that `UP` was increasing `i` and `DOWN` was decreasing `i`, because that's what made sense to me. If that contradicts which end of the stream `i=0` is supposed to be, you are absolutely right. There are probably also a lot of factoring improvements I could make (e.g. put a `boolean tryToAddFish(int size)` in `School`, and what you suggested) if I was more into Java. This might be out of scope, but what difference would static make to `School`?(sqykly == Dave Hand, btw)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T08:06:54.323", "Id": "54088", "Score": "0", "body": "@user31565 I made the correction you suggested - good catch! I also added a big comment to clarify my reasoning for using `School`. Seems like it should reduce unnecessary comparisons in the average case where half of the fish swimming in the `i++` direction are ordered and have their fate determined by the fish in front of them. Someone who likes Java and math more than me should be able to verify or disprove me on that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T09:04:21.557", "Id": "54096", "Score": "1", "body": "A `static` inner class ensures that the inner class does not depend on any instance variables in the outer class, i.e. it is an independent class that just happens to be defined here because it was convenient, not because it needs to capture any variables from its environment. Adding the `static` keyword aids readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T20:54:31.120", "Id": "54166", "Score": "0", "body": "You are a great coder! So School for you means a number of fish that is moving toward the i=n! You collect it in the stack and see if there is someone that is able to defend it! Am I right? However at the end could you let's have a look on this? http://bit.ly/1hedWld Thank you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T23:14:26.440", "Id": "54178", "Score": "0", "body": "@200_success thanks for explaining! Will edit." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T01:54:55.747", "Id": "33722", "ParentId": "33716", "Score": "9" } }, { "body": "<p>Unfortunately, both solutions are wrong as they don't pass the following JUnit tests: </p>\n\n<pre><code>@Test\npublic void testSolution() {\n FishSurvivor fs = new FishSurvivor();\n int[] a = { 4, 3, 2, 1, 5 };\n int[] b = { 0, 1, 0, 0, 0 };\n assertEquals(2, fs.solution(a, b));\n a = new int[] { 4, 3, 2, 1, 5 };\n b = new int[] { 0, 1, 0, 1, 0 };\n assertEquals(2, fs.solution(a, b));\n a = new int[] { 4, 3, 2, 1, 5 };\n b = new int[] { 0, 0, 0, 0, 0 };\n assertEquals(5, fs.solution(a, b));\n a = new int[] { 4, 3, 2, 1, 5 };\n b = new int[] { 1, 1, 1, 1, 1 };\n assertEquals(5, fs.solution(a, b));\n a = new int[] { 4, 3, 2, 1, 5 };\n b = new int[] { 0, 0, 0, 1, 1 };\n assertEquals(5, fs.solution(a, b));\n a = new int[] { 5, 3, 2, 1, 4 };\n b = new int[] { 1, 0, 0, 0, 0 };\n assertEquals(1, fs.solution(a, b));\n a = new int[] { 1, 2, 3, 4, 5 };\n b = new int[] { 1, 1, 1, 1, 0 };\n assertEquals(1, fs.solution(a, b));\n}\n</code></pre>\n\n<p>The right answer with time and space complexity O(n) is shown below: </p>\n\n<pre><code>package com.atreceno.it.javanese.codility;\n\nimport java.util.Stack;\n\n/**\n * You are given two non-empty zero-indexed arrays A and B consisting of N\n * integers. Arrays A and B represent N voracious fish in a river, ordered\n * downstream along the flow of the river...\n * \n * @author atreceno\n * \n */\npublic class FishSurvivor {\n\n /**\n * Given two non-empty zero-indexed arrays A and B consisting of N integers,\n * this function returns the number of fish that will stay alive.\n * \n * @param a\n * array representing the size.\n * @param b\n * array representing the direction.\n * @return the number of fish that will stay alive.\n */\n public int solution(int[] a, int[] b) {\n int survivors = 0;\n Stack&lt;Integer&gt; ones = new Stack&lt;Integer&gt;();\n for (int i = 0; i &lt; a.length; i++) {\n if (b[i] == 0) {\n if (ones.size() == 0) {\n survivors++;\n } else { // Duel\n while (!ones.empty()) {\n if (a[i] &gt; ones.peek()) { // \"One\" dies\n ones.pop();\n } else { // \"Zero\" dies\n break;\n }\n }\n if (ones.empty()) { // \"Zero\" survives\n survivors++;\n }\n }\n } else {\n ones.push(a[i]);\n }\n }\n return survivors + ones.size();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T00:48:28.943", "Id": "54787", "Score": "0", "body": "It's partly my fault for breaking @DaveHand's solution! His rev 4 worked, but his UP/DOWN usage was backwards and his constants were also misnamed, so two wrongs make a right. I half-fixed it in [Rev 5](http://codereview.stackexchange.com/revisions/33722/5), which broke it. [Rev 6](http://codereview.stackexchange.com/revisions/33722/6) should work now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T00:55:30.510", "Id": "54788", "Score": "2", "body": "I'd suggest `if (ones.empty()) { survivors++; } ...` instead of `if (ones.size() == 0) { survivors++; } ...`, to be consistent with the two other similar conditions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T23:23:26.343", "Id": "34081", "ParentId": "33716", "Score": "10" } } ]
{ "AcceptedAnswerId": "33722", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T19:26:17.780", "Id": "33716", "Score": "10", "Tags": [ "java", "algorithm", "interview-questions", "complexity", "programming-challenge" ], "Title": "Fish Food Chain of complexity O(N)" }
33716
<p>I've tried to write a configurable OOP-style FizzBuzz program in PHP for learning purposes. I hope everything is quite easy to understand.</p> <ol> <li>What do you think of the overall architecture?</li> <li>Are OOP principles kept well?</li> <li>What can be improved?</li> <li>How could error-handling and input-checking (i.e. currently you can break the program with ill-formed <code>$multipliers</code> array) be improved?</li> </ol> <p></p> <pre><code>&lt;?php interface FizzBuzzable { public function printMe(); } class NumberFizzBuzzItem implements FizzBuzzable { private $number; public function __construct($number) { $this-&gt;number = $number; } public function printMe() { return (string) $this-&gt;number; } } class WordFizzBuzzItem implements FizzBuzzable { private $word; public function __construct($word) { $this-&gt;word = $word; } public static function check($number, $multiplier) { return !($number % $multiplier); } public function printMe() { return $this-&gt;word; } } class FizzBuzzPrinter { private $items = array(); public function add(FizzBuzzable $item) { $this-&gt;items[] = $item; } public function printMe() { $output = ''; foreach ($this-&gt;items as $item) { $output .= $item-&gt;printMe(); } return $output; } public function __toString() { return $this-&gt;printMe(); } public function isEmpty() { return empty($this-&gt;items); } } class FizzBuzzFactory { private static $multipliers = array(); public static function init(array $multipliers) { self::$multipliers = $multipliers; } public static function create($number) { $printer = new FizzBuzzPrinter(); foreach (self::$multipliers as $multiplier =&gt; $word) { if (WordFizzBuzzItem::check($number, $multiplier)) { $printer-&gt;add(new WordFizzBuzzItem($word)); } } if ($printer-&gt;isEmpty()) { $printer-&gt;add(new NumberFizzBuzzItem($number)); } return $printer; } } class FizzBuzzIterator implements Iterator { private $from; private $to; private $number; public function __construct($from, $to, $multipliers) { $this-&gt;from = $from; $this-&gt;to = $to; FizzBuzzFactory::init($multipliers); } public function current() { return FizzBuzzFactory::create($this-&gt;number); } public function rewind() { $this-&gt;number = $this-&gt;from; } public function key() { return null; } public function next() { ++$this-&gt;number; } public function valid() { return $this-&gt;number &lt;= $this-&gt;to; } } foreach (new FizzBuzzIterator(1, 100, array(3 =&gt; 'Fizz', 5 =&gt; 'Buzz')) as $fb) { echo $fb . "\n"; } </code></pre> <p><strong>Update:</strong></p> <p>I modified the code according to @ChrisWue suggestions. The <code>FizzBuzzPrinter</code> class is gone as we don't actually need concatenation by the rules (this was premature optimization), <code>check()</code> method has been moved to <code>FizzBuzzFactory</code> which isn't static anymore. <code>FizzBuzzable</code> interface became <code>FizzBuzzItem</code> abstract class because a <code>__toString()</code> method implementation which was removed along with <code>FizzBuzzPrinter</code> is still needed for all concrete classes. Business logic was also changed a bit: <code>krsort()</code> is applied to <code>$multipliers</code> array in a factory constructor to ensure that bigger multipliers are processed first.</p> <pre><code>&lt;?php abstract class FizzBuzzItem { abstract public function printMe(); public function __toString() { return $this-&gt;printMe(); } } class NumberFizzBuzzItem extends FizzBuzzItem { private $number; public function __construct($number) { $this-&gt;number = $number; } public function printMe() { return (string) $this-&gt;number; } } class WordFizzBuzzItem extends FizzBuzzItem { private $word; public function __construct($word) { $this-&gt;word = $word; } public function printMe() { return $this-&gt;word; } } class FizzBuzzFactory { private $multipliers = array(); public function __construct(array $multipliers) { $this-&gt;multipliers = $multipliers; krsort($this-&gt;multipliers); } public static function check($number, $multiplier) { return !($number % $multiplier); } public function create($number) { foreach ($this-&gt;multipliers as $multiplier =&gt; $word) { if (self::check($number, $multiplier)) { return new WordFizzBuzzItem($word); } } return new NumberFizzBuzzItem($number); } } class FizzBuzzIterator implements Iterator { private $from; private $to; private $number; private $factory; public function __construct($from, $to, $multipliers) { $this-&gt;from = $from; $this-&gt;to = $to; $this-&gt;factory = new FizzBuzzFactory($multipliers); } public function current() { return $this-&gt;factory-&gt;create($this-&gt;number); } public function rewind() { $this-&gt;number = $this-&gt;from; } public function key() { return null; } public function next() { ++$this-&gt;number; } public function valid() { return $this-&gt;number &lt;= $this-&gt;to; } } foreach (new FizzBuzzIterator(1, 100, array(3 =&gt; 'Fizz', 5 =&gt; 'Buzz', 15 =&gt; 'FizzBuzz')) as $fb) { echo $fb . "\n"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T04:15:52.803", "Id": "54005", "Score": "1", "body": "Wow, this is even more over-engineered than the solution I proposed: [Fizz Buzz interview question](http://codereview.stackexchange.com/questions/6957/fizz-buzz-interview-question-code)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T08:43:51.007", "Id": "54015", "Score": "1", "body": "Of course at first I had wrote this straight-forward one: http://codepad.org/hDSKRbv6, but then I wanted to try a configurable and extendable object-oriented solution instead of hard-coded procedural conditions." } ]
[ { "body": "<p>First of: I like the iterator approach. We use the FizzBuzz problem as part of our interview process and to this date nobody went down that route.</p>\n\n<p>The main points I have:</p>\n\n<ol>\n<li>Apparently your solution is quite over-engineered for a problem like this so I just assume you did it for the lack of a proper example (to be honest I usually find it quite difficult to come up with simple, comprehensive examples where the application of more complex designs doesn't seem over-engineered so fair enough :)).</li>\n<li>Your <code>FizzBuzzFactory</code> should not be static. This for example prevents running multiple FizzBuzz games simultaneously. Just create an instance with the specific multipliers as a member and store it as an additional member of your iterator. Static classes which hold states are evil (there are probably sensible applications for it but in general terms they are bad) as they create problems with unit testing, parallelization, re-use, modularity, etc.</li>\n<li>You have hidden the actual business logic in the <code>WordFizzBuzzItem</code> class as a static method. A more central place to have that function would be the <code>FizzBuzzFactory</code> as it is the one which effectively decides which <code>FizzBuzzable</code> to create.</li>\n<li><p>The most common definition of the FizzBuzz game I know of is <a href=\"http://rosettacode.org/wiki/FizzBuzz\">this</a>:</p>\n\n<blockquote>\n <p>Write a program that prints the integers from 1 to 100. But for multiples of three print \"Fizz\" instead of the number and for the multiples of five print \"Buzz\". For numbers which are multiples of both three and five print \"FizzBuzz\"</p>\n</blockquote>\n\n<p>However you have implemented this:</p>\n\n<blockquote>\n <p>Write a program that prints the integers from 1 to 100. But for multiples of three print \"Fizz\" instead of the number and for the multiples of five print \"Buzz\". For numbers which are multiples of both three and five print the concatenation of both.</p>\n</blockquote>\n\n<p>Effectively this means you only have to write <code>array(3 =&gt; 'Fizz', 5 =&gt; 'Buzz')</code> as rules instead of <code>array(3 =&gt; 'Fizz', 5 =&gt; 'Buzz', 15 =&gt; 'FizzBuzz')</code> so you saved yourself some typing work by reducing a case to a combination of the existing ones.</p>\n\n<p>Why does it matter? If you consider the problem as the business logic given provided by a customer then approx. 5sec after the deployment of your solution the customer will come back and say: \"Ah yes, I forgot, if it's divisible by 3 and 5 you have to print FixBugz because some of our legacy applications which we can't change have a typo in their parsing code.\" Now instead of just changing <code>array(3 =&gt; 'Fizz', 5 =&gt; 'Buzz', 15 =&gt; 'FizzBuzz')</code> into <code>array(3 =&gt; 'Fizz', 5 =&gt; 'Buzz', 15 =&gt; 'FixBugz')</code> you have to change a whole bunch of implementation code and unit tests.</p>\n\n<p>In the end you have generalized a solution which might not fit the requirements because the requirements have changed (they always do).</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T08:41:52.747", "Id": "54014", "Score": "0", "body": "Thanks a lot! I thought about some of your points (3, 4) but was unsure. Now if I implement these suggestions and simplify the 15 case, there's no longer a need for `FizzBuzzPrinter` which was effectively a wrapper for concatenation, the factory can return a `FizzBuzzable` instance directly. Hence this part was indeed over-engineered and prematurely assumed about the logic. Your point 2 is also very valuable, I usually see factories as static in examples over the web so I perhaps blindly copied that approach, a factory instance can be really beneficial here for modularity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-12T21:49:36.583", "Id": "101376", "Score": "2", "body": "I was first introduced to FizzBuzz (or rather, an game isomorphic to it, called \"Buzz\") in 1978. The game has many variations, but all the ones I know of follow the principle that when multiple patterns are matched, you concatenate the words associated with those patterns. The \"most common\" definition above is not necessarily the _best_ definition. If you want that definition to be taken literally, not parsed as \"concatenate the words as in other variations of this game\", I would recommend that the initial requirements map multiples of 15 to some word other than \"FizzBuzz\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T04:12:41.467", "Id": "33724", "ParentId": "33717", "Score": "12" } } ]
{ "AcceptedAnswerId": "33724", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T21:05:37.747", "Id": "33717", "Score": "7", "Tags": [ "php", "object-oriented", "fizzbuzz" ], "Title": "OOP-style FizzBuzz program in PHP" }
33717
<p>I've just created a script in Google Spreadsheet in order to archive some things. I have data from four countries. If something is marked done, then that line could be archived into that country's archive.</p> <p>My code is pretty ugly. Is there a clearer way to do this?</p> <pre><code>function CroatianArchive() { var source_sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('original'); var target_sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('croatian_backup'); var lastRow = source_sheet.getLastRow(); var source_range = source_sheet.getDataRange(); var target_range = target_sheet.getDataRange(); var rowsToBeDeleted = []; var i = 2; while (i &lt;= lastRow) { if (source_sheet.getRange("A"+i).getValue() == "CRO" &amp;&amp; source_sheet.getRange("M"+i).getValue() == "DONE" ) { var office = source_sheet.getRange("A"+i).getValue(); var title = source_sheet.getRange("B"+i).getValue(); var imdbId = source_sheet.getRange("C"+i).getValue(); var channel = source_sheet.getRange("D"+i).getValue(); var type = source_sheet.getRange("E"+i).getValue(); var added = source_sheet.getRange("F"+i).getValue(); var deadline = source_sheet.getRange("G"+i).getValue(); var airing = source_sheet.getRange("H"+i).getValue(); var link = source_sheet.getRange("I"+i).getValue(); var picture = source_sheet.getRange("J"+i).getValue(); var comment = source_sheet.getRange("K"+i).getValue(); var portId = source_sheet.getRange("L"+i).getValue(); var status = source_sheet.getRange("M"+i).getValue(); var data = [office,title,imdbId,channel,type,added,deadline,airing,link,picture,comment,portId,status]; target_sheet.appendRow(data); rowsToBeDeleted.push(i); i++; } else { i++; } } rowsToBeDeleted.reverse(); for (var j = 0; j &lt; rowsToBeDeleted.length; j++) { source_sheet.deleteRow(rowsToBeDeleted[j]); } SpreadsheetApp.getActiveSpreadsheet().toast('Archivation finished.', 'Status'); } function SerbianArchive() { var source_sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('original'); var target_sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('serbian_backup'); var lastRow = source_sheet.getLastRow(); var source_range = source_sheet.getDataRange(); var target_range = target_sheet.getDataRange(); var rowsToBeDeleted = []; var i = 2; while (i &lt;= lastRow) { if (source_sheet.getRange("A"+i).getValue() == "SER" &amp;&amp; source_sheet.getRange("M"+i).getValue() == "DONE" ) { var office = source_sheet.getRange("A"+i).getValue(); var title = source_sheet.getRange("B"+i).getValue(); var imdbId = source_sheet.getRange("C"+i).getValue(); var channel = source_sheet.getRange("D"+i).getValue(); var type = source_sheet.getRange("E"+i).getValue(); var added = source_sheet.getRange("F"+i).getValue(); var deadline = source_sheet.getRange("G"+i).getValue(); var airing = source_sheet.getRange("H"+i).getValue(); var link = source_sheet.getRange("I"+i).getValue(); var picture = source_sheet.getRange("J"+i).getValue(); var comment = source_sheet.getRange("K"+i).getValue(); var portId = source_sheet.getRange("L"+i).getValue(); var status = source_sheet.getRange("M"+i).getValue(); var data = [office,title,imdbId,channel,type,added,deadline,airing,link,picture,comment,portId,status]; target_sheet.appendRow(data); rowsToBeDeleted.push(i); i++; } else { i++; } } rowsToBeDeleted.reverse(); for (var j = 0; j &lt; rowsToBeDeleted.length; j++) { source_sheet.deleteRow(rowsToBeDeleted[j]); } SpreadsheetApp.getActiveSpreadsheet().toast('Archivation finished.', 'Status'); } </code></pre>
[]
[ { "body": "<p>You have a lot of repeated code when creating the <code>data</code> array. Note that the names of each cell value are ultimately irrelevant. That part could also be expressed as:</p>\n\n<pre><code>var columns = [\"A\" // office\n ,\"B\" // title\n ,\"C\" // imdbId\n ,\"D\" // channel\n ,\"E\" // type\n ,\"F\" // added\n ,\"G\" // deadline\n ,\"H\" // airing\n ,\"I\" // link\n ,\"J\" // picture\n ,\"K\" // comment\n ,\"L\" // portId\n ,\"M\" // status\n ];\nvar data = columns.map(function (col) {\n return source_sheet.getRange(col + i).getValue();\n});\n</code></pre>\n\n<p>Less redundant code, same level of documentation.</p>\n\n<p>Code like</p>\n\n<pre><code>if (...) {\n ...;\n i++;\n} else {\n i++;\n}\n</code></pre>\n\n<p>is usually better written as:</p>\n\n<pre><code>if (...) {\n ...;\n}\ni++;\n</code></pre>\n\n<p>However, we now have</p>\n\n<pre><code>var i = 2;\nwhile (i &lt;= lastRow) {\n ...;\n i++;\n}\n</code></pre>\n\n<p>which is a more complicated formulation of</p>\n\n<pre><code>for (var i = 2; i &lt;= lastRow; i++) {\n ...;\n}\n</code></pre>\n\n<p>Similarly,</p>\n\n<pre><code>rowsToBeDeleted.reverse();\nfor (var j = 0; j &lt; rowsToBeDeleted.length; j++) \n{\n source_sheet.deleteRow(rowsToBeDeleted[j]);\n}\n</code></pre>\n\n<p>is the same as:</p>\n\n<pre><code>for (var i = rowsToBeDeleted.length - 1; i &gt;= 0; i--) {\n source_sheet.deleteRow(rowsToBeDeleted[i]);\n}\n</code></pre>\n\n<p>If I see that correctly, your two function only differ in the strings <code>croatian_backup</code> vs. <code>serbian_backup</code> and <code>CRO</code> vs. <code>SER</code>. Instead of copy-pasting that code, take those strings from the function parameters. Now we have a general <code>archive</code> function:</p>\n\n<pre><code>function archive(outputSheet, languageCode) { ... }\n</code></pre>\n\n<p>If you need two seperate funtions that don't take any arguments, we can use the <a href=\"https://en.wikipedia.org/wiki/Currying\" rel=\"nofollow\"><em>currying</em> technique</a> (also known as partial application) to pre-fill the arguments:</p>\n\n<pre><code>function CroatianArchive() {\n return archive(\"croatian_backup\", \"CRO\");\n}\n</code></pre>\n\n<p>Some of your names use underscores, other capitalization to separate words:</p>\n\n<pre><code>source_range\nlastRow\n</code></pre>\n\n<p>You should settle for one style – Javascript tends to prefer capitalization rather than underscores.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T17:15:53.053", "Id": "54129", "Score": "0", "body": "I wouldn't call it currying or partial application since there's nothing partial about it. Your example doesn't curry a function; it just calls one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T18:01:06.193", "Id": "54138", "Score": "0", "body": "@Flambino You are technically correct, and I lied in my answer in order to pin a name on this specialization technique. I picked “*currying*” because I couldn't think of anything better, and because it is effectively a similar abstraction. Because JavaScript has side effects, I transformed `archive :: (String, String) → ()` into `CroatianArchive :: () → ()`, which can be seen as the end step of `CroatianArchive' :: String → String → () → ()`. The word “*priming*” might be a better alternative (which is what [Perl6 calls this](http://perlcabal.org/syn/S06.html#Priming), and which I emulated)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T21:53:33.280", "Id": "54172", "Score": "0", "body": "Priming's a good name for it. To be honest, I never thought of what one might call it; I'd probably just call it a \"shortcut\" or something :) But it's funny, I reasoned the same as you when I wrote my comment. If currying means reducing the arity of a function, then reducing the arity to zero would be \"currying\". But then every function invocation would fall in that category and it'd sorta lose its meaning" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T18:32:51.787", "Id": "33749", "ParentId": "33718", "Score": "4" } } ]
{ "AcceptedAnswerId": "33749", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T21:13:36.510", "Id": "33718", "Score": "0", "Tags": [ "google-apps-script", "google-sheets" ], "Title": "Country data archiving script using Google Spreadsheet" }
33718
<p>A "DOMNodeList grouper" (<code>groupList()</code> function below) is a function that envelopes a set of nodes into a tag. Example:</p> <p>INPUT</p> <pre><code> &lt;root&gt;&lt;b&gt;10&lt;/b&gt;&lt;a/&gt;&lt;a&gt;1&lt;/a&gt;&lt;b&gt;20&lt;/b&gt;&lt;a&gt;2&lt;/a&gt;&lt;/root&gt; </code></pre> <p>OUTPUT of <code>groupList($dom-&gt;getElementsByTagName('a'),'G')</code></p> <pre><code> &lt;root&gt;&lt;b&gt;10&lt;/b&gt; &lt;G&gt;&lt;a/&gt;&lt;a&gt;1&lt;/a&gt;&lt;a&gt;2&lt;/a&gt;&lt;/G&gt; &lt;b&gt;20&lt;/b&gt;&lt;/root&gt; </code></pre> <p>There are many ways to implement it, what is the better?</p> <pre><code> // my "in use" version function groupList(DOMDocument &amp;$dom, DOMNodeList &amp;$list, $tag, $place=0) { $n = $list-&gt;length; if ($n &amp;&amp; $place&lt;$n) { $rmList=array(); $T = $dom-&gt;createElement($tag); for($i=0; $i&lt;$n; $i++) { $T-&gt;appendChild( clone $list-&gt;item($i) ); if ($i!=$place) $rmList[]=$list-&gt;item($i); } $dom-&gt;documentElement-&gt;replaceChild($T,$list-&gt;item($place)); foreach($rmList as $e) $dom-&gt;documentElement-&gt;removeChild($e); }//if return $n; }//func function groupList_v2(DOMDocument &amp;$dom, DOMNodeList &amp;$list, $tag, $place=0) { // use iterator_to_array, Fragment, cloneNode, and replaceChild at end. $n = $list-&gt;length; if ($n &amp;&amp; $place&lt;$n) { $list=iterator_to_array($list); $T = $dom-&gt;createDocumentFragment(); $T-&gt;appendChild($dom-&gt;createElement($tag)); for($i=0; $i&lt;$n; $i++) $T-&gt;firstChild-&gt;appendChild( $list[$i]-&gt;cloneNode() ); for($i=0; $i&lt;$n; $i++) if ($i!=$place) $dom-&gt;documentElement-&gt;removeChild($list[$i]); $dom-&gt;documentElement-&gt;replaceChild($T,$list[$place]); }//if return $n; }//func function groupList_v3(DOMDocument &amp;$dom, DOMNodeList &amp;$list, $tag, $place=0) { // use importNode $n = $list-&gt;length; if ($n &amp;&amp; $place&lt;$n) { $rmList = array(); $d2 = new DOMDocument; $T = $d2-&gt;createElement($tag); for($i=0; $i&lt;$n; $i++) { $e = $list-&gt;item($i); $T-&gt;appendChild( $d2-&gt;importNode($e, true) ); if ($i!=$place) $rmList[] = $e; } foreach($rmList as $e) $dom-&gt;documentElement-&gt;removeChild($e); $dom-&gt;documentElement-&gt;replaceChild( $dom-&gt;importNode($T, true), $list-&gt;item($place) ); }//if return $n; }//func </code></pre> <hr> <p>The <a href="https://stackoverflow.com/q/19710238/287948">little problems</a> and dilemmas about "best decisions" are <a href="https://softwareengineering.stackexchange.com/q/216329/84349">summarized here</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T22:49:16.380", "Id": "33719", "Score": "1", "Tags": [ "php", "dom" ], "Title": "DOMDocument grouping nodes, with clone, nodeClone, importNode, fragment... What the better way?" }
33719
<p>I have coded my own lightbox for the sake of my own custom needs because I want to be able to do this kind of thing myself and learn all the various things involved. I realize I could use a plugin, but that is not the point here.</p> <p>Last week I posted <a href="https://codereview.stackexchange.com/questions/33346/is-this-javascript-jquery-methodology-good">this vague question</a> to get some feedback on the style, and ultimately the code I am posting here now is really a much better question I think:</p> <p><strong>Is my method of making the lightbox an object filled with different independent methods valid?</strong></p> <ul> <li>I like doing it this way because it allows me to make a bunch of isolated individual functions that I can call on and reference when<br> needed.</li> <li>When I need to modify part of the process, most things are isolated and easy to work on.</li> <li>Sometimes I may have difficulty drawing the line between separating functions and keeping them combined for simplicities sake.</li> </ul> <p>As you look at the code you might want to say "Why didn't you do this, or why didn't you do that" Or you might say "Why are you doing it like this" to which I will say, that will not be constructive for me. I am doing it this way because I have found it to be a nice way of doing things and frankly I am not as adept at writing the code other ways. I have been on a JS/Jquery crash course for about two years now trying to make the best I can of it.</p> <pre><code>var lightbox={ start: function(){ $('body').on('click','img',function(){ var target = $(this).attr('src'); lightbox.createScreen(); lightbox.getDimensions(); lightbox.createImageBackDrop(target); lightbox.listenForClose(); }); }, createScreen: function(){ var $screenElement = $('&lt;div&gt;&lt;/div&gt;').attr('id','modalscreen') .css( { position:'absolute', width:'100%', height:'100%', zIndex:10000, backgroundColor: '#000000', opacity: '0.8' } ) lightbox.prependScreen($screenElement); }, prependScreen: function($e){ ($e).prependTo(document.body); }, createImageBackDrop: function($image){ var $backDrop = $('&lt;div&gt;&lt;/div&gt;').attr('id','imageback') lightbox.sizeBackDrop($backDrop,$image); }, sizeBackDrop: function($e,src){ //original height / original width x new width = new height var width = lightbox.getDimensions('x'); var imgWidth = Math.round(width*.52); var imgHeight = Math.round(750/1000*imgWidth); var bdWidth = imgWidth+20; var bdHeight = imgHeight+20; var bdMarginTop = -Math.abs(bdHeight/2); var bdMarginLeft = -Math.abs(bdWidth/2); $e.css( { position:'absolute', top:'50%', left:'50%', marginTop:bdMarginTop, marginLeft:bdMarginLeft, width: bdWidth+'px', height:bdHeight+'px', zIndex:10001, backgroundColor: '#FFF', padding:'10px' } ) lightbox.prependBackDrop($e); lightbox.insertImage(src,imgWidth,imgHeight); }, insertImage: function(src,w,h){ var imgMarginTop = -Math.abs(h/2); var imgMarginLeft = -Math.abs(w/2); var $image = $('&lt;img&gt;') .attr({ 'src':src, 'height':h, 'width':w }) .css({ position:'absolute', top:'50%', left:'50%', marginTop:imgMarginTop, marginLeft:imgMarginLeft, }); ($image).appendTo('#imageback'); }, prependBackDrop: function($e){ ($e).prependTo(document.body); }, getDimensions: function(e){ var width = screenwidth.checkSize(); var height = screenwidth.checkHeight(); if(e == 'y'){ return height; } else if (e == 'x'){ return width; } }, listenForClose: function(){ $('body').on('click','#modalscreen',function(){ $('#modalscreen').remove(); $('#imageback').remove(); }); } } //end lightbox $(document).ready(screenwidth.start); //another object that returns screen size info $(document).ready(lightbox.start); </code></pre>
[]
[ { "body": "<p>First of all, this may be a matter of opinion (my CTO totally disagrees on this, for instance), but I think <strong>splitting a long method / function into tiny ones with a single, simple purpose is the right way of doing things.</strong> </p>\n\n<p>Actually, this is also the position held by <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\">the \"Clean Code\" book</a> and many people out there.</p>\n\n<p>The benefits you state do exist, and other reasons to code this way can be found in aforementioned book. What i really like about this though :</p>\n\n<ul>\n<li>your code becomes <em>self-documenting</em>, so that it's easier for other people to understand what you <em>intend to do</em>. </li>\n<li>it helps to get an <em>overview</em> of a complex process without having to deal with all the low-level details, except if you want it. </li>\n<li>Perhaps more importantly, it helps scoping things (for example, in long functions you sometimes have to crawl all the way up because you don't remember what this or that var is, in which state it is, etc.). </li>\n<li>I also find it helps reasoning about the problem you're dealing with, because with this method you tend to split the problem into smaller problems, which is about the very essence of programming.</li>\n</ul>\n\n<p>That said, I have a few pointers that you might consider helpful.</p>\n\n<h3>Use closures</h3>\n\n<p>Your <code>lightbox</code> object is not really necessary, and sometimes it obfuscates the code a bit.</p>\n\n<p>In fact, as your script only evaluates once (no subsequent call after <code>start</code>), you could replace your object with a closure :</p>\n\n<pre><code> (function(){\n\n // initialize stuff\n\n })();\n</code></pre>\n\n<p>What happens here is that you create a function that you immediately call ; all vars in the function body are in a local scope that is not accessible from the outside (this prevents conflicts with other scripts). </p>\n\n<p>Using a closure, you will be able to run intialization code without having to stuff all your functions inside an object or worrying to pollute the global namespace :</p>\n\n<pre><code>// the bang! is just another way to create a closure... \n// with one less character to type (closing parens)\n!function(){\n\n // I like to put init stuff on top, this is debatable\n doThis();\n doThat();\n doThose();\n\n // these functions are local to the scope ;\n // they are also callable from anywhere in this scope \n // (search 'javascript variable lifting' for more info)\n function doThis(){}; \n function doThat(){};\n function doThose(){};\n\n}();\n</code></pre>\n\n<h3>Use closure-local variables</h3>\n\n<p>In your code, your init stuff is called every time the user clicks on an image. This is bad because, for instance, you call <code>createScreen</code> every time, creating a new element an appending it to body over and over. As you will only need one screen throughout the entire app lifecycle, it would be sensible to do something like this : </p>\n\n<pre><code>!function(){\n\n // we will only create this once, and operate on this only element\n var screen = createScreen();\n\n function createScreen(){ \n //... create your element \n };\n\n function showScreen(){\n screen.prependTo(document.body);\n };\n\n // remove() only removes the element from the DOM,\n // it remains usable and accessible through the var\n function hideScreen(){\n screen.remove();\n }\n\n}();\n</code></pre>\n\n<p>You can even get a bit more object-oriented on this one :</p>\n\n<pre><code>!function(){\n\n // ad-hoc object, could be a real \"class\" with elaborate \n // constructor and prototype\n var screen = {\n element: createScreen(),\n show: function(){ this.element.prependTo(document.body); },\n hide: function(){ this.element.remove(); }\n };\n\n $(document)\n .on('click','img', open)\n .on('click','#modalscreen', close);\n\n function open(){\n screen.show();\n // insert image and stuff\n };\n\n function close(){\n screen.hide();\n };\n\n}();\n</code></pre>\n\n<p>same method applies to other parts of your script (for instance, only create the modal once, then show/hide/resize it, and change image inside).</p>\n\n<h3>Style considerations</h3>\n\n<p>Just a last minor remark : when declaring many vars, you can do :</p>\n\n<pre><code>var foo = 'foo',\n bar = 'bar',\n baz = 'baz';\n</code></pre>\n\n<p>It saves typing and it is a bit more clear. In fact, some recommend using the <code>var</code> keyword <a href=\"http://wonko.com/post/try-to-use-one-var-statement-per-scope-in-javascript\" rel=\"nofollow\">only once and on top of the scope</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T23:50:12.763", "Id": "54060", "Score": "0", "body": "Outstanding answer. exactly what I was looking for...I will reply with more direct comments and questions once I have had time to study your suggestions further." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T04:01:31.307", "Id": "54798", "Score": "0", "body": "You are completely right about only needing one screen throughout the life cycle and I will be changing the code to reflect that. Would you say it is okay to create the image holder each time though? Reason being it is supposed to be dynamic and take viewport size into account which may change." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T19:56:51.637", "Id": "33754", "ParentId": "33720", "Score": "3" } } ]
{ "AcceptedAnswerId": "33754", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T23:41:17.317", "Id": "33720", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "jQuery lightbox" }
33720
<p>How do I improve the below code, which takes input from a file and does some word analysis? I find a lot of redundancy in it. I want to know a better way of implementing it.</p> <pre><code>analysis = {} wordanalysis = {} found = True for line in sys.stdin: (n1,n2,n3,n4,n5,n6) = re.split("\t+",line.strip()) tweet = re.split("\s+", n6.strip().lower()) #adding tweet id to a dictionary for i in range(0, len(tweet)): print "{", n1, wordanalysis,"}" wordanalysis["word"] = tweet[i] wordanalysis["charcount"]= len(tweet[i]) if len(tweet[i]) &gt; 7: wordanalysis["longword"] = found else: wordanalysis["longword"] = not(found) #if 1st char is UpperCase if tweet[i].istitle(): wordanalysis["title"] = found else: wordanalysis["title"] = not(found) if tweet[i].isupper(): wordanalysis["uppercase"] = found else: wordanalysis["uppercase"] = not(found) </code></pre>
[]
[ { "body": "<p>First, I see some odd behaviour that seems buggy, and if it is intended then it deserves a comment:</p>\n\n<ul>\n<li>Variables <code>n2</code>, <code>n3</code>, <code>n4</code>, and <code>n5</code> are never used. A comment with some sample lines of the expected input would be very helpful.</li>\n<li>When you print <code>wordanalysis</code>, you are printing the analysis from the previous iteration of the loop.</li>\n</ul>\n\n<p>The main simplification to apply is that the tests themselves are boolean values, and can therefore be assigned directly.</p>\n\n<pre><code>wordanalysis[\"longword\"] = (len(tweet[i]) &gt; 7)\n# Is 1st char UpperCase?\nwordanalysis[\"title\"] = tweet[i].istitle()\nwordanalysis[\"uppercase\"] = tweet[i].isupper()\n</code></pre>\n\n<p>Furthermore, I would iterate over the list items rather than over the indexes of the list.</p>\n\n<pre><code>tweets = re.split(\"\\s+\", n6.strip().lower())\nfor tweet in tweets:\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T00:22:44.457", "Id": "54071", "Score": "0", "body": "Thanks a lot. I really like this one: wordanalysis[\"longword\"] = (len(tweet[i]) > 7) They are boolean values so that makes total sense." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T04:31:43.777", "Id": "33725", "ParentId": "33721", "Score": "2" } }, { "body": "<ol>\n<li><p>I would wrap the entire part of analyzing in a function:</p>\n\n<pre><code>def analyze_twees(tweets):\n</code></pre>\n\n<p>Then you could pass in content, from whichever source. It doesn't matter, whether the input comes from <code>sys.stdin</code> or a string, which you just generated. This makes the function easier to test, since you do not need passing a file into your function.</p></li>\n<li><p>As 200_success said, </p>\n\n<pre><code>for i in range(0, len(tweet)):\n</code></pre>\n\n<p>is considered poor style in Python. According to (1) you should iterate over the <code>tweets</code> as suggested: </p>\n\n<pre><code>for tweet in tweets.\n</code></pre></li>\n<li><p>Your variable naming is very obscure. Think of <code>future you</code> coming up in 6 Months fixing a bug - do you understand your code at first glance? I doubt that.</p>\n\n<pre><code>n6.strip().lower()\n</code></pre>\n\n<p>One can only guess, what this is about. But if you wrote something like</p>\n\n<pre><code>tweeted_text = re.split(\"\\s+\", tweet.strip().lower())\n</code></pre>\n\n<p>one could imagine, what you intended to do.</p></li>\n<li><p>You should split your concerns:</p>\n\n<ol>\n<li>you are going to read a file line by line. So that should be one function.</li>\n<li>you are printing something to the console. That would be another function.</li>\n<li><p>you are analyzing the <code>tweeted text</code>. That would be the third function.</p>\n\n<pre><code>def print_tweet_analysis(dataset):\n for row in dataset:\n console_out(analyze(row))\n</code></pre>\n\n<p>That would be your complete algorithm in three lines of code.\nIf you come in 10 years from now back to your code, you unterstand, what this script is about: it takes data, analyzes it and puts the result to the console.\nIf you want to know, what <code>analyze</code> means, you look at the function and will see.\nThe same goes for your analyze function. You could fine grain your logic into small pieces, each sitting on the top of the other and if you read the code, you drill down as far as necessary to understand the code and maybe finding later on bugs and fixing those.</p></li>\n</ol></li>\n<li><p>Instead of using a dictionary for your algorithm, I would recommend <a href=\"http://docs.python.org/2/library/collections.html#collections.namedtuple\" rel=\"nofollow\">namedtuple</a>. You could easily define your analysis-tuple as</p>\n\n<pre><code>Analysis = namedtuple(\"Analysis\", \"word charcount longword title uppercase\")\n</code></pre>\n\n<p>and return simply:</p>\n\n<pre><code>return Analysis(tweet, len(tweet), len(tweet)&gt;7, tweet.istitle(), tweet.isupper())\n</code></pre>\n\n<p>And you are done.</p>\n\n<p>If you wrote your code like this, everybody including <code>future you</code> would know, what this is all about.</p>\n\n<p>One thing, I still do not understand is:</p>\n\n<p>You are defining <code>tweet</code> as</p>\n\n<pre><code>tweet = re.split(\"\\s+\", n6.strip().lower())\n</code></pre>\n\n<p>iterating over it and checking for </p>\n\n<pre><code>tweet[i].isupper()\n</code></pre>\n\n<p>Am I overseeing something or does this make no sense only to me?</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T21:26:46.520", "Id": "54046", "Score": "0", "body": "Very helpful. Thanks a lot. How do I pass the lines that I am reading from standard input between functions? That is the only reason I am not using functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T22:48:40.273", "Id": "54053", "Score": "0", "body": "Like any other variable. You could iterate over it like over any other iterable. It is even possible to use something in other languages called `stringstream` c.f. http://docs.python.org/2/library/stringio.html" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T10:32:17.057", "Id": "33732", "ParentId": "33721", "Score": "4" } } ]
{ "AcceptedAnswerId": "33732", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T00:20:52.443", "Id": "33721", "Score": "3", "Tags": [ "python", "hash-map", "file" ], "Title": "Word analysis on input from a file" }
33721
<p>My project uses at least 100 helper classes like the below:</p> <pre><code>.pa5 {padding:5px} .pa10 {padding:10px} /* ... */ .pt5 {padding-top:5px} .pt10 {padding-top:10px} /* ... */ .pr5 {padding-right:5px} .pr10 {padding-right:10px} /* ... */ /* ... */ </code></pre> <p>It comes handy in some cases like <code>&lt;div class="pa10"&gt;...&lt;/div&gt;</code> but I think we overused it or, even worse, misused it.</p> <p>For example, the below <code>&lt;a&gt;</code> tag contains 8 classes to define how it display (background, background hover, padding, border radius, diplay inline block, margin and float left). It looks like the way you use <code>style="..."</code> to inline style it:</p> <pre><code>&lt;a href="#" class="bg1 bg2H pa10 rounded5 dpib mb10 fl mr10"&gt;&lt;/a&gt; </code></pre> <p>In other case, even when we had the class <code>profileInfo</code>, we still use it with a lot of helper classes:</p> <pre><code>&lt;div class="profileInfo bd2 clearfix pa5 tac ol1 por"&gt;&lt;/div&gt; </code></pre> <p>I think this is a worse practice and could cause significant performance overhead on page rendering. Since I haven't worked a lot with CSS, I could not explain it clearly to make us change the way of using it. What do you think? Does your project have an explicit rule to limit the number of CSS classes for one element?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T16:58:10.533", "Id": "54122", "Score": "1", "body": "Related: http://stackoverflow.com/questions/4354921/css-is-there-a-limit-on-how-many-classes-an-html-can-have" } ]
[ { "body": "<p>The use of that many classes is a sign of incorrect CSS usage, but not because of performance. I doubt eight or ten classes on an element will be a noticeable performance issue.</p>\n\n<p>I've never heard of an explicit limit on the number of classes assigned to an element, but that may due to a common understanding that it is not correct to create a class for every visual attribute.</p>\n\n<p>An important (and possibly the primary) purpose of CSS is to associate rendering characteristics with conceptual (semantic) markup. Classes should be named for the concepts they represent, not their appearance. Like this:</p>\n\n<pre><code>.tableofcontents {\n padding-left: 10px;\n padding-top: 5px;\n}\n</code></pre>\n\n<p>If the goal is to avoid duplication (though I honestly don't think duplicating a few lines of declarations in various blocks is harmful), one can assign multiple conceptual classes to a block:</p>\n\n<pre><code>.menu,\n.logo,\n.heading,\n.tableofcontents {\n padding-top: 5px;\n}\n\n.menu,\n.tableofcontents {\n padding-left: 10px;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T17:02:30.150", "Id": "54126", "Score": "0", "body": "It's worth noting that consolidated selectors *can* lead to larger CSS files, depending on length of selectors and the number of styles they share: http://codereview.stackexchange.com/a/27910/26722" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T14:20:47.533", "Id": "33738", "ParentId": "33727", "Score": "6" } } ]
{ "AcceptedAnswerId": "33738", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T05:10:06.577", "Id": "33727", "Score": "2", "Tags": [ "performance", "html", "css" ], "Title": "Number of HTML classes for one element" }
33727
<p>I need help making this code run faster. I am using it to import a CSV file into Excel. It works, but it is very slow. The file is almost 20MB.</p> <pre><code>{Sub OpenTextFile() Dim FilePath As String Dim linitem As Variant FilePath = "filepath.txt" Open FilePath For Input As #1 row_number = 0 Do Line Input #1, LineFromFile LineItems = Split(LineFromFile, "|") ActiveCell.Offset(row_number, 30).Value = LineItems(0) ActiveCell.Offset(row_number, 29).Value = LineItems(1) ActiveCell.Offset(row_number, 28).Value = LineItems(2) ActiveCell.Offset(row_number, 27).Value = LineItems(3) ActiveCell.Offset(row_number, 26).Value = LineItems(4) ActiveCell.Offset(row_number, 25).Value = LineItems(5) ActiveCell.Offset(row_number, 24).Value = LineItems(6) ActiveCell.Offset(row_number, 23).Value = LineItems(7) ActiveCell.Offset(row_number, 22).Value = LineItems(8) ActiveCell.Offset(row_number, 21).Value = LineItems(9) ActiveCell.Offset(row_number, 20).Value = LineItems(10) ActiveCell.Offset(row_number, 19).Value = LineItems(11) ActiveCell.Offset(row_number, 18).Value = LineItems(12) ActiveCell.Offset(row_number, 17).Value = LineItems(13) ActiveCell.Offset(row_number, 16).Value = LineItems(14) ActiveCell.Offset(row_number, 15).Value = LineItems(15) ActiveCell.Offset(row_number, 14).Value = LineItems(16) ActiveCell.Offset(row_number, 13).Value = LineItems(17) ActiveCell.Offset(row_number, 12).Value = LineItems(18) ActiveCell.Offset(row_number, 11).Value = LineItems(19) ActiveCell.Offset(row_number, 10).Value = LineItems(20) ActiveCell.Offset(row_number, 9).Value = LineItems(21) ActiveCell.Offset(row_number, 8).Value = LineItems(22) ActiveCell.Offset(row_number, 7).Value = LineItems(23) ActiveCell.Offset(row_number, 6).Value = LineItems(24) ActiveCell.Offset(row_number, 5).Value = LineItems(25) ActiveCell.Offset(row_number, 4).Value = LineItems(26) ActiveCell.Offset(row_number, 3).Value = LineItems(27) ActiveCell.Offset(row_number, 2).Value = LineItems(28) ActiveCell.Offset(row_number, 1).Value = LineItems(29) ActiveCell.Offset(row_number, 0).Value = LineItems(30) row_number = row_number + 1 Loop Until EOF(1) Close #1 End Sub } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T05:59:44.560", "Id": "54011", "Score": "0", "body": "Have you tried setting `Application.ScreenUpdating` to `False` and then back to `True` once you're done with the file?" } ]
[ { "body": "<p>Not sure about the \"faster\" thing but you can replace the 31 lines of assignments with a 3 line for loop:</p>\n\n<pre><code>For r As Integer = 0 To 30\n ActiveCell.Offset(row_number, 30 - r).Value = LineItems(r)\nNext\n</code></pre>\n\n<p>Programming is about automating repetitive tasks, this should also apply to the code you write.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T16:41:41.697", "Id": "54032", "Score": "0", "body": "True, i am a beginner. I tried a loop but i could not write one that works. Grateful for your help" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T17:35:20.823", "Id": "54036", "Score": "2", "body": "I would hesitate to tag this as an answer. If your new here as well, you might want to wait awhile for answers to your actual question: How to make the code faster... vs this honestly good answer to an unasked question: How to make the code cleaner." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T19:02:26.553", "Id": "54039", "Score": "0", "body": "I have to agree with @WernerCD, I don't really think this solves your problem. Although to be fair codereview is not about solving programing problems, it's about reviewing existing code ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T23:25:09.857", "Id": "54059", "Score": "0", "body": "Point well taken." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T08:00:16.240", "Id": "33730", "ParentId": "33728", "Score": "5" } }, { "body": "<p>If I were to rewrite your code, I'd do it like this:</p>\n\n<pre><code>Option Explicit\n</code></pre>\n\n<p>Step one, always be explicit. Nobody likes seeing a variable being used that they never saw declared anywhere.</p>\n\n<pre><code>Public Sub ImportTextFile()\n</code></pre>\n\n<p>Step two, name the procedure after what it's doing, and make it do that.</p>\n\n<pre><code> Dim filePath As String\n filePath = \"filepath.txt\"\n\n Dim fileNumber As Long\n fileNumber = FreeFile\n</code></pre>\n\n<p><code>FreeFile</code> will give you a file number that's ok to use. Hard-coding a file number is never a good idea, even if you're only using one file.</p>\n\n<pre><code> Dim inputData As String\n Dim lineCount As Long\n\n On Error Goto ErrHandler\n ToggleWaitMode True, \"Importing text file...\"\n</code></pre>\n\n<p><code>On Error Goto ErrHandler</code> means if anything wrong happens (file not found, more data in the file than can fit on the worksheet, or whatever), we'll skip straight to an error-handling subroutine where we'll take good care of closing our file and toggle \"wait mode\" back off.</p>\n\n<pre><code> Open filePath For Input As #fileNumber\n\n Do Until EOF(fileNumber)\n\n Line Input #fileNumber, inputData\n lineCount = lineCount + 1\n\n WriteLineContentToActiveSheet inputData, lineCount\n\n Loop\n\n Close #fileNumber\n</code></pre>\n\n<p>So the <code>ImportTextFile</code> procedure does nothing but reading the file's content. <code>WriteLineContentToActiveSheet</code> will do the worksheet-writing part.</p>\n\n<pre><code>ErrHandler:\n ToggleWaitMode\n\n If Err.Number &lt;&gt; 0 Then\n Close 'closes any file left open\n MsgBox Err.Description\n Err.Clear\n End If\n\nEnd sub\n</code></pre>\n\n<p>The code under this <em>label</em> will execute even if no error occurred, this is why we're checking for <code>Err.Number</code> being other than 0. But regardless of whether there's an error or not, we always want to <code>ToggleWaitMode</code>.</p>\n\n<pre><code>Private Sub ToggleWaitMode(Optional ByVal wait As Boolean = False, Optional ByVal statusBarMessage As String = vbNullString)\n\n Application.ScreenUpdating = True 'ensure status message gets displayed\n Application.StatusBar = statusBarMessage\n Application.Cursor = IIf(wait, xlWait, xlDefault)\n Application.ScreenUpdating = Not wait\n Application.EnableEvents = Not Wait\n\nEnd Sub\n</code></pre>\n\n<p>This small procedure takes two optional parameters. If none are specified, \"wait mode\" is toggled off - this means the status bar message is reset, the mouse cursor goes back to default, Excel resumes redrawing the screen and fires events whenever something happens. \"Wait mode\" is just all that reversed :)</p>\n\n<pre><code>Private Sub WriteLineContentToActiveSheet(ByVal inputData As String, ByVal targetRow As Long)\n Dim lineFields() As String\n lineFields = Split(inputData, \"|\")\n\n Dim fieldCount As Integer\n fieldCount = UBound(lineFields)\n\n Dim currentField As Integer\n Dim targetColumn As Integer\n Dim fieldValue As String\n\n With ActiveSheet\n For currentField = 0 To fieldCount\n\n fieldValue = lineFields(currentField)\n targetColumn = fieldCount - currentField + 1\n\n .Cells(targetRow, targetColumn).Value = fieldValue\n\n Next\n End With\n\nEnd Sub\n</code></pre>\n\n<p>This small procedure takes a single line of data, splits it into as many fields as it has, and writes each field value into a cell of the active sheet. Using <code>UBound</code> we're no longer tied to a specific number of fields - if the file format changes, the procedure should still work. And if it doesn't, the procedure that called it will cleanly handle the error for us.</p>\n\n<p>Local variables <code>currentField</code>, <code>targetColumn</code> and <code>fieldValue</code> are not necessary - they could all be inlined, but having them makes code easier to follow and allows you to place breakpoints to validate their values as you run the code line-by-line with <kbd>F8</kbd> when you're debugging.</p>\n\n<hr>\n\n<p>Couple observations:</p>\n\n<ul>\n<li>You need to <strong>indent</strong> your code. Indentation makes it much easier to read, for yourself and anyone looking at it. Give that <kbd>Tab</kbd> button some lovin'!\n<ul>\n<li>Procedures define a <em>scope</em>, anything under it should be indented.</li>\n<li>Within a scope, <em>code blocks</em> should also be indented - this includes <code>If</code> blocks, <code>With</code> blocks and any code that runs inside a loop.</li>\n</ul></li>\n<li><code>OpenTextFile</code> is a bad name for a procedure that actually <em>imports</em> a text file.</li>\n<li>Be consistent with your naming: chose a convention, and stick to it.</li>\n<li>You're reading a file, that's an I/O operation and by <a href=\"http://en.wikipedia.org/wiki/Murphy%27s_law\" rel=\"nofollow\">Murphy's Law</a> this is going to fail one day or another. Make sure your code properly handles any error that could happen while processing the file, you don't want to leave a file handle opened by mistake.</li>\n<li>Importing a 20mb text file will take a while, even with screen updating turned off. Tell your user you're working, give'em a hourglass cursor, and you can even update the statusbar message every couple thousand lines read/written (just call <code>ToggleWaitMode True</code> with a new status message) so they know it's not frozen.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T16:38:34.887", "Id": "54030", "Score": "0", "body": "Thank you, i am here to learn. I will take the advice / critique and learn from it. Thank you for taking the time to look at my \"code\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T20:36:33.317", "Id": "54044", "Score": "0", "body": "Thanks retailcoder, i appreciate your help. I learned a lot. I tried your code, and i am getting a \"Array expected\" @ Ubound(inputData). It just freeses" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T21:30:00.847", "Id": "54047", "Score": "0", "body": "oops my bad, typo - should read `UBound(lineFields)`... fixed now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T21:40:38.817", "Id": "54048", "Score": "0", "body": "UBound stands for \"upper bound\" and returns the upper boundary of an array. That's the number of fields we have in `LineFields` after the `Split`, and so it represents the number of fields we have - hence `fieldCount`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T23:16:20.607", "Id": "54058", "Score": "0", "body": "Thanks, i tried it. it works but not faster. It gets stuck in imporitng the file. It is a large file so it might be that it will take time no matter what. Thanks a lot for your help, i appreciate it. God Bless" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T00:08:37.500", "Id": "54070", "Score": "0", "body": "@user25830 As I said, `Importing a 20mb text file will take a while, even with screen updating turned off. Tell your user you're working, give'em a hourglass cursor, and you can even update the statusbar message every couple thousand lines read/written` - this is VBA, you can't have a *background thread* doing work in the background. So the best thing to do is update the statusbar every X lines read/written so the user knows your code isn't frozen." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T16:05:47.867", "Id": "54118", "Score": "0", "body": "See below answer from @DickKusleika, instead of `WriteLineContentToActiveSheet` you could have `ExtractLineContentToArrayIndex` and add an index to an array and then have `DumpArrayToActiveSheet` - I don't think it gets any faster :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T16:08:00.860", "Id": "33743", "ParentId": "33728", "Score": "7" } }, { "body": "<p>You can also use the <code>With</code> statement this way:</p>\n\n<pre><code>With ActiveCell\n For r As Integer = 0 To 30\n .Offset(row_number, 30 - r).Value = LineItems(r)\n Next\nEnd With\n</code></pre>\n\n<p>Thus, Excel doesn't have to call the <code>ActiveCell</code> object at each loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T17:34:06.623", "Id": "54035", "Score": "0", "body": "It's still calling it - the `with` block is just sort-of hiding it, hence the readability debate around that keyword :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T19:35:52.440", "Id": "54042", "Score": "0", "body": "@retailcoder: are you sure it calls it in each line, or does it call it once and maintain a reference to it? Given that ActiveCell is a function, it should do the later, which should be a bit faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T19:52:38.753", "Id": "54043", "Score": "0", "body": "After [verification](http://msdn.microsoft.com/en-us/library/aa266330(v=vs.60).aspx), it seems you're right about this. Sorry!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T04:03:54.400", "Id": "54083", "Score": "2", "body": "@Jmax: Assuming that VBA and VB.net do the same thing, that should be faster. See this SO answer: http://stackoverflow.com/a/18288030/234954" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T13:41:52.280", "Id": "54110", "Score": "0", "body": "Yup. +1 and I'm stealing this, I really thought `With` was merely syntactic sugar. Thanks @jmoreno for that link." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T13:55:06.450", "Id": "54111", "Score": "0", "body": "Thanks for all your insights and @jmoreno for the link. `With` can be tricky depending on which language you use (in javascript for instance, it should be avoided because it is very slow)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T16:57:39.047", "Id": "33745", "ParentId": "33728", "Score": "5" } }, { "body": "<p>An alternative approach would be to code the import of the file as a separate sheet. Then select used range and copy to where those values have to go.</p>\n\n<p>This way you will let Excel do the hard part.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T13:41:07.350", "Id": "33791", "ParentId": "33728", "Score": "0" } }, { "body": "<p>One of the slowest parts of Excel VBA is writing to the grid. Whenever you have a lot of data to write you should put that data in an array and write it all at once. Here's how I would rewrite your code to do that.</p>\n\n<pre><code>Sub OpenTextFile()\n\n Dim sFilePath As String\n Dim sInput As String\n Dim vaLines As Variant\n Dim vaLineItems As Variant\n Dim aNew() As Variant\n Dim i As Long, j As Long\n Dim lCnt As Long\n\n sFilePath = \"filepath.txt\"\n Open sFilePath For Input As #1\n\n 'Read in whole file at one, then close it\n sInput = Input$(LOF(1), 1)\n Close #1\n\n 'Split the lines and the first line to set up aNew\n vaLines = Split(sInput, vbNewLine)\n vaLineItems = Split(vaLines(0), \"|\")\n ReDim aNew(LBound(vaLines) To UBound(vaLines), LBound(vaLineItems) To UBound(vaLineItems))\n\n 'Loop through the lines\n For i = LBound(vaLines) To UBound(vaLines)\n vaLineItems = Split(vaLines(i), \"|\")\n\n 'Loop through the items, add to aNew in reverse\n For j = LBound(vaLineItems) To UBound(vaLineItems)\n aNew(lCnt, UBound(vaLineItems) - j) = vaLineItems(j)\n Next j\n\n lCnt = lCnt + 1\n Next i\n\n 'Write to the range all at once\n Sheet1.Range(\"A1\").Resize(UBound(aNew, 1) + 1, UBound(aNew, 2) + 1).Value = aNew\n\nEnd Sub\n</code></pre>\n\n<p>aNew is a poorly named variable that will hold the array that gets written to the sheet. By reading in the whole text file at once, you can redimension aNew to the right number of rows. Then by reading in the first line and splitting it, you get the number of columns for aNew (assuming they're all the same number of columns).</p>\n\n<p>The loops simply fill aNew with the info in the order we want it. Finally, the array is assigned to the Value property.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T15:52:00.500", "Id": "33796", "ParentId": "33728", "Score": "5" } } ]
{ "AcceptedAnswerId": "33730", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T05:25:19.763", "Id": "33728", "Score": "5", "Tags": [ "optimization", "vba", "csv", "excel" ], "Title": "Importing a CSV file into Excel" }
33728
<p>So I introduced myself to templates in C++11 and I have to say it's really confusing, but also very fascinating. I just need to get my head around what happens at compile time so that I don't wind up making one line of driver code amount to a megabyte of asm...</p> <p>Anyway, to teach myself I wrote a little container class. It's a container that locks and unlocks a mutex on each read/write operation on a group of data. There's still a few features I want to add to it, but that will take a lot of forced templating beyond compile-time recursion (more on this at the end).</p> <p>Here is the code (updated 11/5):</p> <pre><code>#include &lt;mutex&gt; #include &lt;tuple&gt; #include &lt;cstring&gt; #include "pack_size.hpp" #include "pack_size_index.hpp" #include "pod_test.hpp" template &lt;typename... item_t&gt; class lockbox { static_assert(sizeof...(item_t) &gt; 0, "empty lockboxes are not permitted."); private: pod_test&lt;item_t...&gt; _test; //No data, tests to make sure item_t parameters are pod-only public: char _items[pack_size&lt;item_t...&gt;::value]; std::mutex _mutex; template &lt;size_t index, typename type_t, typename... args&gt; static inline const void set_all(char* dest, const type_t&amp; value, const args&amp;... values) { type_t* align = (type_t*)&amp;dest[pack_size_index&lt;index, item_t...&gt;::value]; *align = value; set_all &lt;index + 1, args...&gt; (dest, values...); } template &lt;size_t index, typename type_t&gt; static inline const void set_all(char* dest, const type_t&amp; value) { type_t* align = (type_t*)&amp;dest[pack_size_index&lt;index, item_t...&gt;::value]; *align = value; } template &lt;size_t index, typename type_t, typename... args&gt; static inline const void get_all(char* src, type_t&amp; value, args&amp;... values) { type_t* align = (type_t*)&amp;src[pack_size_index&lt;index, item_t...&gt;::value]; value = *align; get_all &lt;index + 1, args...&gt; (src, values...); } template &lt;size_t index, typename type_t&gt; static inline const void get_all(char* src, type_t&amp; value) { type_t* align = (type_t*)&amp;src[pack_size_index&lt;index, item_t...&gt;::value]; value = *align; } template &lt;size_t index, size_t... indices&gt; static inline const void set_indices(char* dest, typename std::tuple_element&lt;index, std::tuple&lt;item_t...&gt; &gt;::type&amp; value, typename std::tuple_element&lt;indices, std::tuple&lt;item_t...&gt; &gt;::type&amp;... values) { typedef typename std::tuple_element&lt;index, std::tuple&lt;item_t...&gt; &gt;::type type_t; type_t* align = (type_t*)&amp;dest[pack_size_index&lt;index, item_t...&gt;::value]; *align = value; set_indices &lt;indices...&gt; (dest, values...); } template &lt;size_t index&gt; static inline const void set_indices(char* dest, typename std::tuple_element&lt;index, std::tuple&lt;item_t...&gt; &gt;::type&amp; value) { typedef typename std::tuple_element&lt;index, std::tuple&lt;item_t...&gt; &gt;::type type_t; type_t* align = (type_t*)&amp;dest[pack_size_index&lt;index, item_t...&gt;::value]; *align = value; } template &lt;size_t index, size_t... indices&gt; static inline const void get_indices(char* src, typename std::tuple_element&lt;index, std::tuple&lt;item_t...&gt; &gt;::type&amp; value, typename std::tuple_element&lt;indices, std::tuple&lt;item_t...&gt; &gt;::type&amp;... values) { typedef typename std::tuple_element&lt;index, std::tuple&lt;item_t...&gt; &gt;::type type_t; type_t* align = (type_t*)&amp;src[pack_size_index&lt;index, item_t...&gt;::value]; value = *align; get_indices &lt;indices...&gt; (src, values...); } template &lt;size_t index&gt; static inline const void get_indices(char* src, typename std::tuple_element&lt;index, std::tuple&lt;item_t...&gt; &gt;::type&amp; value) { typedef typename std::tuple_element&lt;index, std::tuple&lt;item_t...&gt; &gt;::type type_t; type_t* align = (type_t*)&amp;src[pack_size_index&lt;index, item_t...&gt;::value]; value = *align; } public: lockbox(void) { _mutex.lock(); memset(_items, 0, pack_size&lt;item_t...&gt;::value); _mutex.unlock(); } inline lockbox(const lockbox&lt;item_t...&gt;&amp; other) { operator=(other); } lockbox(item_t... items) { _mutex.lock(); set_all &lt;0, item_t...&gt; (_items, items...); _mutex.unlock(); } ~lockbox(void) {} lockbox&lt;item_t...&gt;&amp; operator= (lockbox&lt;item_t...&gt;&amp; rhs) { char buffer[pack_size&lt;item_t...&gt;::value]; rhs._mutex.lock(); memcpy(buffer, rhs._items, pack_size&lt;item_t...&gt;::value); rhs._mutex.unlock(); _mutex.lock(); memcpy(_items, buffer, pack_size&lt;item_t...&gt;::value); _mutex.unlock(); return *this; } lockbox&lt;item_t...&gt;&amp; set(item_t... items) { _mutex.lock(); set_all &lt;0, item_t...&gt; (_items, items...); _mutex.unlock(); return *this; } template &lt;size_t... indices&gt; lockbox&lt;item_t...&gt;&amp; set(typename std::tuple_element&lt;indices, std::tuple&lt;item_t...&gt; &gt;::type... values) { _mutex.lock(); set_indices &lt;indices...&gt; (_items, values...); _mutex.unlock(); return *this; } inline lockbox&lt;item_t...&gt;&amp; set(lockbox&lt;item_t...&gt;&amp; other) { return operator=(other); } lockbox&lt;item_t...&gt;&amp; get(item_t&amp;... ref_items) { _mutex.lock(); get_all &lt;0, item_t...&gt; (_items, ref_items...); _mutex.unlock(); return *this; } template &lt;size_t... indices&gt; lockbox&lt;item_t...&gt;&amp; get(typename std::tuple_element&lt;indices, std::tuple&lt;item_t...&gt; &gt;::type&amp;... ref_values) { _mutex.lock(); get_indices &lt;indices...&gt; (_items, ref_values...); _mutex.unlock(); return *this; } inline lockbox&lt;item_t...&gt;&amp; get(lockbox&lt;item_t...&gt;&amp; other) { return other = *this; } static inline const size_t bytes(void) { return pack_size&lt;item_t...&gt;::value; } }; </code></pre> <p>pack_size:</p> <pre><code>template &lt;typename... args&gt; struct pack_size; template &lt;&gt; struct pack_size &lt;&gt; { static const size_t value = 0; }; template &lt;typename type_t, typename... args&gt; struct pack_size &lt;type_t, args...&gt; { static const size_t value = sizeof(type_t) + pack_size&lt;args...&gt;::value; }; </code></pre> <p>pack_size_index:</p> <pre><code>template &lt;size_t index, typename... args&gt; struct pack_size_index; template &lt;size_t index, typename type_t, typename... args&gt; struct pack_size_index &lt;index, type_t, args...&gt; { static_assert(sizeof...(args) &gt; 0, "index specified is out of bounds."); static constexpr size_t value = sizeof(type_t) + pack_size_index&lt;index - 1, args...&gt;::value; }; template &lt;typename type_t, typename... args&gt; struct pack_size_index &lt;0, type_t, args...&gt; { static constexpr size_t value = 0; }; </code></pre> <p>pod_test:</p> <pre><code>#include &lt;type_traits&gt; template &lt;typename... args&gt; struct pod_test; template &lt;typename type_t, typename... args&gt; struct pod_test&lt;type_t, args...&gt; { static_assert(std::is_pod&lt;type_t&gt;::value, "parameter pack contains non-pod types."); static pod_test&lt;args...&gt; node; }; template &lt;typename type_t&gt; struct pod_test&lt;type_t&gt; { static_assert(std::is_pod&lt;type_t&gt;::value, "parameter pack contains non-pod types."); }; </code></pre> <p>Usage:</p> <pre><code>#include "lockbox.hpp" int main(int argc, char** argv) { lockbox&lt;float, double&gt; box(3.5f, 6.7777899); float a; double b; lockbox.get&lt;0, 1&gt;(a, b) //get the items at indices 0 and 1 and //store them in the variables specified std::cout &lt;&lt; a &lt;&lt; ", " &lt;&lt; b &lt;&lt; std::endl; //output: 3.5, 6.7777899 lockbox.set&lt;1&gt; (5.67); //set the item at index 1 to the value specified lockbox.get(a, b) //get all items and store them in the variables //specified (works the same with set as well) std::cout &lt;&lt; a &lt;&lt; ", " &lt;&lt; b &lt;&lt; std::endl; //output: 3.5, 5.67 return 0; } </code></pre> <p>What inefficiencies are present here? I think set_all, get_all, set_indices, and get_indices might be creating an inordinate amount of functions, but that's all I can think of. Is my format readable, naming conventions and spacing considered?</p>
[]
[ { "body": "<p>I might be misreading things so correct me if I'm wrong but Ithink your assignment operator can deadlock. A <code>lockbox</code> only makes sense when accessed from multiple threads, doesn't it (otherwise what would be the point)? </p>\n\n<ul>\n<li>Let's say we have two boxes <code>box1</code> and <code>box2</code> and two threads A and B.</li>\n<li>Both threads get a reference to both boxes.</li>\n<li>Each thread tries to copy the contents of one box into the other for some reason, so\n<ul>\n<li>Thread A executes: <code>box1 = box2</code> in order to assign the contents of <code>box2</code> to <code>box1</code></li>\n<li>Thread B executes: <code>box2 = box1</code> in order to assign the contents of <code>box1</code> to <code>box2</code></li>\n</ul></li>\n<li>Now if the timing is right the following could happen:\n<ul>\n<li>Thread A executes the assignment operator and locks the right hand side first so <code>box2</code> is now locked.</li>\n<li>Thread A gets interrupted or Thread B just manages to sneak in the next step on another CPU core</li>\n<li>Thread B executes the assignment operator and locks the right hand side first so <code>box1</code> is now locked.</li>\n<li>Thread B tries to lock the left hand side which is <code>box1</code> but that's already locked so it waits</li>\n<li>Thread A picks up again and now tries to lock the left hand side which is <code>box2</code> but that's locked so it waits</li>\n<li>Kaputt</li>\n</ul></li>\n<li>It's probably pretty rare but deadlocks often have the habit of being rare and non-determinsistic</li>\n</ul>\n\n<p><strong>Update</strong>: As mentioned by Loki in the comments you can use <a href=\"http://en.cppreference.com/w/cpp/thread/lock\" rel=\"nofollow\"><code>std::lock</code></a> to obtain multiple locks. It's employing a deadlock avoidance algorithm (I guess effectively something like: \"try to lock all objects, if one failed, unlock all obtained locks and try again until you succeed\").</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T03:11:56.050", "Id": "54188", "Score": "0", "body": "Actually you are right, I'm not sure how to efficiently avoid that though. Locking the this->_mutex and then rhs would do the same thing... I could make a copy of rhs._items in a local char array, but for large lockboxes this could be quite slow..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T20:09:18.770", "Id": "54345", "Score": "0", "body": "Scratch that, that's my only choice. Code updated to reflect this change." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T02:13:45.937", "Id": "54383", "Score": "0", "body": "@NmdMystery: Could you not change the code you originally posted? Otherwise the provided answers will become useless. Either include the revised code further down in your question or ask a new question with your revised code for further comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T12:47:18.733", "Id": "54433", "Score": "1", "body": "@NmdMystery: This problem is solved by locking the resources in a specific order. If you use `std::lock()` and pass multiple objects it will always make sure that they are locked in a (unspecified but) specific order that avoids deadlock." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T00:44:15.233", "Id": "54513", "Score": "0", "body": "@ChrisWue Woops, I was thinking the opposite in that the post would be too long and nobody would want to read it. The original code is lost now, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T00:51:15.433", "Id": "54516", "Score": "0", "body": "@LokiAstari Ah, didn't realize there was a static lock." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T07:47:33.597", "Id": "33782", "ParentId": "33731", "Score": "2" } }, { "body": "<ol>\n<li>Your internal storage field <code>char _items[pack_size&lt;item_t...&gt;::value];</code> may not be aligned properly, i.e. a <code>double</code> has an alignment of 8, but <code>lockbox&lt;double&gt;::_items</code> is only aligned by 4 (on 32-bit platforms).</li>\n<li>Using <code>memset</code> and <code>memcpy</code> means your class only works for POD types and has undefined behaviour for non-POD types.</li>\n<li>Since you're using C++11, why not just use <code>std::tuple</code>?</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T03:04:31.033", "Id": "54186", "Score": "0", "body": "Actually I revised this to use tuple in a few places. I wasn't aware of how tuple worked, I thought it was just sort of a container but it has all these extra meta-programming features I had no idea were there. Will post an update in a moment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T20:07:26.143", "Id": "54344", "Score": "0", "body": "I decided that only pod types should be used, since by design the lockbox makes it impossible to call methods of a non-pod anyway. What should I do to fix the alignment problem, though? I only own 64-bit machines so I can't go and test this on a 32-bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T20:11:12.113", "Id": "54346", "Score": "0", "body": "Also, testing sizeof(lockbox) gives me strange results - it seems to force an alignment of 8, is this just what sizeof does with non-pods or is this an issue I should be trying to fix?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T23:11:52.613", "Id": "33808", "ParentId": "33731", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T09:39:44.497", "Id": "33731", "Score": "3", "Tags": [ "c++", "c++11", "template-meta-programming" ], "Title": "lockbox (a boost-like container)" }
33731
<p>I want to collect all fields which have given Modifier(s) of a class. I have written following pieces of codes:</p> <pre><code>/** * Method getFields * @author TapasB * @since 03-Nov-2013 - 2:03:17 pm * @version DAM 1.0 * @param instanceClass * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static List&lt;Field&gt; getFields(Class&lt;?&gt; instanceClass) { List&lt;Field&gt; fields = new ArrayList&lt;Field&gt;(); Class&lt;?&gt; searchType = instanceClass; while (!Object.class.equals(searchType) &amp;&amp; searchType != null) { fields.addAll(Arrays.asList(searchType.getDeclaredFields())); searchType = searchType.getSuperclass(); } return Collections.unmodifiableList(new ArrayList(selectDistinct(fields, "name"))); } /** * Method getFields * @author TapasB * @since 03-Nov-2013 - 2:31:59 pm * @version DAM 1.0 * @param instanceClass * @param includedModifiers * @param excludedModifiers * @return */ public static List&lt;Field&gt; getFields(Class&lt;?&gt; instanceClass, int[] includedModifiers, int[] excludedModifiers) { List&lt;Field&gt; fields = getFields(instanceClass); List&lt;Field&gt; filteredFields = new ArrayList&lt;Field&gt;(); if(ArrayUtils.isEmpty(includedModifiers)) { filteredFields.addAll(fields); } else { for(Field field : fields) { boolean fieldCanBeAdded = false; for(int includedModifier : includedModifiers) { if((includedModifier &amp; field.getModifiers()) != 0) { fieldCanBeAdded = true; } } if(fieldCanBeAdded) { filteredFields.add(field); } } } if(ArrayUtils.isNotEmpty(excludedModifiers)) { Iterator&lt;Field&gt; fieldIterator = filteredFields.iterator(); while (fieldIterator.hasNext()) { Field field = fieldIterator.next(); boolean fieldNeedsToBeRemoved = false; for(int excludedModifier : excludedModifiers) { if((excludedModifier &amp; field.getModifiers()) != 0) { fieldNeedsToBeRemoved = true; } } if(fieldNeedsToBeRemoved) { fieldIterator.remove(); } } } return Collections.unmodifiableList(filteredFields); } </code></pre> <p>The method <code>getFields(Class&lt;?&gt; instanceClass)</code> searchs for fields in an iterative manner to all the super classes of the given class and stops at <code>Object</code>. </p> <p>Here the <code>selectDistinct</code> is the method of LambdaJ API. It removes the fields with same name which is present in the parent class also in child class.</p> <p>I was wondering if it is a good way to achieve what I want.</p> <p>To run it:</p> <pre><code>public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { int[] includedModifiers = new int[]{Modifier.PRIVATE}; int[] excludedModifiers = new int[]{Modifier.FINAL}; List&lt;Field&gt; fields = getFields(ArrayList.class, includedModifiers, excludedModifiers); for(Field field : fields) { System.out.println(field.getName()); } } </code></pre> <p>The <code>main</code> will print only the fields which have modifier only <code>private</code> and exclude the <code>private final</code>.</p> <p>There is no issue so far I found with this code. I just want to know if there is any better solution exists or not.</p>
[]
[ { "body": "<p>I've played with your code and have a few broad observations....</p>\n\n<ol>\n<li>The code is neat enough and generally readable.</li>\n<li>JavaDocs are not complete - return values are not documented</li>\n<li>@since JavaDoc tag traditionally records a version number, not a date.</li>\n</ol>\n\n<p>I don't think there is a generally 'better' way to do what you are doing, but I think some of the specific details are worth commenting on..... and my last paragraph is an important one, so please make sure you consider it....</p>\n\n<p>Some more specific comments:</p>\n\n<ol>\n<li>Just check that you really need both getFields methods to be public. Exposing just the second version may be a better option and make the <code>getFields(Class&lt;?&gt; instanceClass)</code> version private. This is a matter of style and usage. In general I feel people make things public when they shouldn't. Whether that is right this time or not is your decision though</li>\n<li>I feel you overuse the <code>Collections.unmodifiableList(...)</code>. Generally this is only useful to protect data that is encapsulated in your class. In this case, the data is not something you need to protect, and worse, you need to 'undo' the unmodifiable state of the list in your exclude/include function. In this case, there is no value in making the lists read-only and if a 'user' decides they want to change the list they can do it without damaging your class, and all you do is make it harder for them (and yourself).</li>\n<li><p>including the LambdaJ function dependency is perhaps unnecessary. The logic you want to do can be accomplished in a few lines with an iterator and a set. The burden of maintaining a dependency on an external library is potentially significant. If you have other needs for LambdaJ then sure, use it, but otherwise you may be satisfied with:</p>\n\n<pre><code>Iterator&lt;Field&gt; it = fields.iterator();\nSet&lt;String&gt; names = new HashSet&lt;String&gt;();\nwhile (it.hasNext()) {\n Field f = it.next();\n if (!names.add(f.getName())) {\n it.remove();\n }\n}\n</code></pre></li>\n</ol>\n\n<p>Finally, I have to question why you want to remove 'shadowed' fields at all. They are different fields and you are losing information if you remove them. Are you <strong><em>sure</em></strong> you want them gone?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T05:37:39.783", "Id": "54085", "Score": "0", "body": "Hello. Thank you very much for the explanations. I will take care the points you had mentioned. About the LmbdaJ usage; yes I have other usage of this API in my application. I didn't think that I might need the fields of the super classes. I am going to refactor them." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T15:47:47.867", "Id": "33741", "ParentId": "33733", "Score": "1" } } ]
{ "AcceptedAnswerId": "33741", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T11:30:03.430", "Id": "33733", "Score": "3", "Tags": [ "java", "reflection" ], "Title": "Collect all fields having given Modifier(s)" }
33733
<p>I've got a JavaScript object and I am not sure how to implement the last part: adding up all of the prices and putting that in the last row of the table. Besides this question, I would also like to ask you to look at the code and advice me if I can make the code slimmer, less lines of code.</p> <p>This is the code I would like reviewed:</p> <pre><code> function ShoppingList(){ this.items = []; this.setItem = function(product, price){ var item = new Item(product, price); this.items.push(item); }; this.render = function(){ var placeHolder = document.getElementById("shoppingList"); placeHolder.innerHTML = ""; var messageDiv = document.getElementById("message"); messageDiv.innerHTML = ""; var tr = document.createElement("tr"); tr.id = "header"; var thProduct = document.createElement("th"); thProduct.innerHTML = "Product"; tr.appendChild(thProduct); var thPrice = document.createElement("th"); thPrice.innerHTML = "Prijs"; tr.appendChild(thPrice); var thDel = document.createElement("th"); thDel.innerHTML = "Verwijder"; tr.appendChild(thDel); placeHolder.appendChild(tr); for(var i = 0; i &lt; this.items.length; i++){ var tr = document.createElement("tr"); tr.id = i; var tdProduct = document.createElement("td"); tdProduct.innerHTML = this.items[i].product; tr.appendChild(tdProduct); var tdPrice = document.createElement("td"); tdPrice.innerHTML = Number(this.items[i].price); tr.appendChild(tdPrice); var tdDel = document.createElement("td"); tdDel.innerHTML = "Verwijder"; tdDel.addEventListener("click", delItem, false); tr.appendChild(tdDel); placeHolder.appendChild(tr); } }; } </code></pre> <p>So, in short: how can I write a new table row to the table with the total price that updates when table rows are added or removed and how can I slim down my code?</p>
[]
[ { "body": "<p>I usually make some simple helper functions to simplify and shorten the code building html. (As your programme gets more complicated you can expand these to suit your needs, or if you prefer, switch to a library like jquery.) In the version below I have also added a few lines to add a total row to the table. However, think about whether you need to rewrite the entire table each time it changes, or could simply add or delete individual rows. If the latter, you would want something like <code>addRow</code>, <code>deleteRow</code> and <code>updateTotal</code> methods.</p>\n\n<pre><code>function build(parent, type, innerHTML) {\n // Make a new element, optionally fill it with html, append it to the parent,\n // and return it.\n var el = document.createElement(type);\n if (innerHTML) {\n el.innerHTML = innerHTML;\n }\n parent.appendChild(el);\n return el;\n}\n\nfunction E(id) {\n // This function has no purpose except to save typing\n return document.getElementById(id);\n}\n\nfunction ShoppingList() {\n var totalCell;\n this.items = [];\n this.setItem = function (product, price) {\n var item = new Item(product, price);\n this.items.push(item);\n };\n this.render = function () {\n E('shoppingList').innerHTML = \"\";\n E('message').innerHTML = \"\";\n var tr = build(E('shoppingList'), 'tr');\n tr.id = 'header';\n build(tr, 'th', 'Product');\n build(tr, 'th', 'Prijs');\n build(tr, 'th', 'Verwijder');\n var totalPrice = 0;\n for (var i = 0; i &lt; this.items.length; i++) {\n tr = build(E('shoppingList'), 'tr');\n tr.id = i;\n build(tr, 'td', this.items[i].product);\n build(tr, 'td', this.items[i].price);\n build(tr, 'td', 'Verwijder').addEventListener('click', delItem, false);\n totalPrice += this.items[i].price;\n }\n tr = build(E('shoppingList'), 'tr');\n build(tr, 'td', 'Total');\n totalCell = build(tr, 'td', totalPrice);\n build(tr, 'td', '');\n };\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T13:25:35.050", "Id": "54018", "Score": "0", "body": "I have looked at your code line by line and I assume there is one thing going to be wrong, I am not sure though.\n\nSetting `E('placeHolder').innerHTML = \"\";` and `E('message').innerHTML = \"\";` going to cause an error to show up?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T13:35:32.387", "Id": "54019", "Score": "0", "body": "No I haven't tested this code as a whole but those lines will definitely work. http://jsfiddle.net/N5wQw/1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T13:40:30.593", "Id": "54020", "Score": "0", "body": "Okay, your jsFiddle works like a charm indeed, but my developer tools in Chrome point out that \"Uncaught TypeError: Cannot set property 'innerHTML' of null\"\n\nSo I am not quite sure why Chrome gives me this error, because the two div's certainly exist and such." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T13:43:53.833", "Id": "54021", "Score": "0", "body": "I think you need to change `E('placeHolder')` to `E('shoppingList')`? I have edited the code above to make it match your OP" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T13:53:23.833", "Id": "54022", "Score": "0", "body": "Ah, thank you, I didn't see it had to be the element shoppingList instead of placeHolder!\nI am now trying to test it, I ran into one bug, being that if I add two products of price 1, it outputs a total price of 011, I am not sure how to solve that problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T14:24:37.853", "Id": "54023", "Score": "0", "body": "use `var item = new Item(product, parseFloat(price));` to make sure the prices are stored as numbers and not strings. Or else do the same conversion at a later stage: `totalPrice += parseFloat(this.items[i].price);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T14:34:57.390", "Id": "54025", "Score": "0", "body": "I changed the code to the use of parseFloat, but it still gives me this result: http://i.imgur.com/aKouAbp.png" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T14:44:22.387", "Id": "54027", "Score": "0", "body": "For some reason it is still treating the number as a string. Possibly due to regional settings and use of `,` versus `.` for decimals. I suggest posting your code (including where the input is coming from) as a new question here or in StackOverflow, preferably with jsfiddle to demonstrate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T14:46:33.530", "Id": "54028", "Score": "0", "body": "Thank you for your help, Stuart, very much appreciated! I will ask a new question about this specific issue!\n\nThank you a lot!" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T13:20:07.107", "Id": "33736", "ParentId": "33734", "Score": "2" } }, { "body": "<p>An alternative to @stuart's solution is to use a javascript template engine, like <a href=\"http://handlebarsjs.com/\" rel=\"nofollow noreferrer\">handlebars</a>.</p>\n\n<p>As a rule of thumb, I think that as soon as you create a <code>render</code> function, you should ask yourself if such a template engine would be useful. Template engines allow you to render html in a declarative way, which is often much more readable.</p>\n\n<p>There is plenty of existing engines, check <a href=\"https://stackoverflow.com/questions/7788611/what-javascript-template-engines-you-recommend\">this stackoverflow question</a> for more insight.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T17:26:32.213", "Id": "33747", "ParentId": "33734", "Score": "0" } } ]
{ "AcceptedAnswerId": "33736", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T11:39:42.247", "Id": "33734", "Score": "2", "Tags": [ "javascript", "object-oriented" ], "Title": "Object in JavaScript, superfluous?" }
33734
<p>I have the following SQL. I want to make that the SP should work under load. Means it should not have any synchronization issues.</p> <pre><code>ALTER PROCEDURE [dbo].[DeleteOldDeviceID] ( @OldDeviceID VARCHAR(500) ,@NewDeviceID VARCHAR(500) ) AS BEGIN SET NOCOUNT ON; DECLARE @TranCount INT; SET @TranCount = @@TRANCOUNT; BEGIN TRY IF @TranCount = 0 BEGIN TRANSACTION ELSE SAVE TRANSACTION DeleteOldDeviceID; IF @NewDeviceID &lt;&gt; '-1' AND NOT EXISTS(SELECT 1 FROM DeviceCatalog WHERE [UniqueID] = @NewDeviceID) BEGIN INSERT INTO [DeviceCatalog] ([os] ,[uniqueid] ,[address] ,[location] ,[culture] ,[city] ,[country] ,[other] ,[lastmodifieddate] ,[createddate] ,[IsActive] ,[IPAddress] ,[NativeDeviceID] ,[IsDeleted]) SELECT [os] ,@NewDeviceID ,[address] ,[location] ,[culture] ,[city] ,[country] ,[other] ,GETDATE() ,GETDATE() ,[IsActive] ,[IPAddress] ,[NativeDeviceID] ,[IsDeleted] FROM [DeviceCatalog] WHERE [UniqueID] = @OldDeviceID; END DELETE FROM DeviceCatalog WHERE [UniqueID] = @OldDeviceID; -- Always Delete old one LBEXIT: IF @TranCount = 0 COMMIT; END TRY BEGIN CATCH DECLARE @Error INT, @Message VARCHAR(4000), @XState INT; SELECT @Error = ERROR_NUMBER() ,@Message = ERROR_MESSAGE() ,@XState = XACT_STATE(); IF @XState = -1 ROLLBACK; IF @XState = 1 AND @TranCount = 0 rollback IF @XState = 1 AND @TranCount &gt; 0 ROLLBACK TRANSACTION DeleteOldDeviceID; RAISERROR ('DeleteOldDeviceID: %d: %s', 16, 1, @error, @message) ; END CATCH END </code></pre> <p><strong>Edit:</strong>, Is this equal to above SQL?</p> <pre><code>ALTER PROCEDURE [dbo].[DeleteOldDeviceID] ( @OldDeviceID VARCHAR(500) ,@NewDeviceID VARCHAR(500) ) AS BEGIN SET NOCOUNT ON; DECLARE @TranCount INT; SET @TranCount = @@TRANCOUNT; BEGIN TRY IF @TranCount = 0 BEGIN TRANSACTION ELSE SAVE TRANSACTION DeleteOldDeviceID; IF @NewDeviceID &lt;&gt; '-1' AND NOT EXISTS(SELECT 1 FROM DeviceCatalog WHERE [UniqueID] = @NewDeviceID) BEGIN UPDATE [DeviceCatalog] SET [UniqueID] = @NewDeviceID WHERE [UniqueID] = @OldDeviceID; END ELSE BEGIN DELETE FROM DeviceCatalog WHERE [UniqueID] = @OldDeviceID; -- Always Delete old one END LBEXIT: IF @TranCount = 0 COMMIT; END TRY BEGIN CATCH DECLARE @Error INT, @Message VARCHAR(4000), @XState INT; SELECT @Error = ERROR_NUMBER() ,@Message = ERROR_MESSAGE() ,@XState = XACT_STATE(); IF @XState = -1 ROLLBACK; IF @XState = 1 AND @TranCount = 0 ROLLBACK IF @XState = 1 AND @TranCount &gt; 0 ROLLBACK TRANSACTION DeleteOldDeviceID; RAISERROR ('DeleteOldDeviceID: %d: %s', 16, 1, @error, @message) ; END CATCH END </code></pre>
[]
[ { "body": "<p>No, the Second Query won't Delete anything.</p>\n\n<p>In the statement prior to the <code>delete</code> you change the <strong>oldID</strong> to the <strong>newID</strong> so there aren't any records with the <strong>oldID</strong> in that table.</p>\n\n<hr>\n\n<p><strong>Difference between the two Queries</strong></p>\n\n<p>The first Query, inserts new records into the table, then deletes the records with the <strong>oldID</strong></p>\n\n<p>The Second Query, updates all the records removing the <strong>oldID</strong>'s and replacing it with the <strong>newID</strong>'s, so instead of inserting and then deleting the old records, it updates the old records <code>UniqueID</code> column</p>\n\n<p>These both do very different things. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T22:54:20.340", "Id": "35387", "ParentId": "33735", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T11:50:52.503", "Id": "33735", "Score": "2", "Tags": [ "sql", "sql-server" ], "Title": "Checking Synchronization issue in SQL?" }
33735
<p>I would like you to review my regex. It's suppose to recognize common URLs like:</p> <pre><code>http://www.google.com http://www.sub1.sub2.google.com https://www.google.com http://www.google.com/path1/path2 http://www.google.com/path1/path2/ http://www.google.com/path1/path2/a=b&amp;c=d http://www.google.com/path1/path2/a=b&amp;c=d/ var url = new RegExp("^(?:https?:\/\/)?(?:[-a-z0-9]+\\.)+[-a-z0-9]+(?:(?:(?:\/[-=&amp;?.#a-z0-9]+)+)\/?)?$"); </code></pre>
[]
[ { "body": "<p>Your regex has many false positives (matches without a valid URL being there), and many false negativs (URLs you don't recognize). You should read the appropriate RFCs which contain relevant parts of the grammar.</p>\n\n<p>Here are some failure scenarios:</p>\n\n<ul>\n<li><p>⊖ You don't match schemes other than HTTP or HTTPS. Consider FTP, SFTP, data URLs, and other widespread schemes like <code>file:</code>, <code>mailto:</code>, <code>irc:</code> or <code>skype:</code>. Consider also that the scheme is sometimes omitted, so that the same protocol as the current document is assumed. Test cases:</p>\n\n<pre><code>ftp://example.com/\ndata:text/html,&lt;p&gt;Hello World!\nmailto:foo@example.com\n//example.com/\n</code></pre>\n\n<p>Every scheme has a slightly different syntax, so you'll have to decide which ones you support. Note that matching a HTTP(S) URL is different from matching all URLs. </p></li>\n<li><p>⊕ You match some domain names that are syntactically correct, but <em>semantically</em> only consist of a top level domain. You may or may not wish to rule these out:</p>\n\n<pre><code>http://co.uk/\n</code></pre>\n\n<p>See the <a href=\"https://wiki.mozilla.org/Public_Suffix_List\">Mozilla Public Suffix List</a> for the only reliable way to do this.</p></li>\n<li><p>⊖ Some host names don't have a TLD:</p>\n\n<pre><code>http://localhost/\n</code></pre></li>\n<li><p>⊕ You match loads of stuff that isn't ok, e.g.:</p>\n\n<pre><code>999.999.999.999/this-is-no-ip4-address\n-.-\n</code></pre></li>\n<li><p>⊖ You don't have support for ports:</p>\n\n<pre><code>http://example.com:80/\n</code></pre></li>\n<li><p>⊖ You don't have support for IPv6 IPs.</p>\n\n<pre><code>http://::1/\nhttp://[::1]:80/\n</code></pre></li>\n<li><p>⊖ You can't match any authority in the host part:</p>\n\n<pre><code>ftp://user:password@example.com/\n</code></pre></li>\n<li><p>⊖ You don't support URL-encoding:</p>\n\n<pre><code>http://example.com/some%20path\n</code></pre></li>\n<li><p>⊖ You don't support Unicode chars:</p>\n\n<pre><code>http://example.com/smørrebrød/greek-Λεττερς\n</code></pre>\n\n<p>Consider also that the host name may contain Unicode characters, but will have an equivalent punycode representation.</p></li>\n<li><p>⊖ Coming to think of it, you actually forbid quite a lot of (special) characters, although they would be perfectly valid (the host part is more restricted).</p>\n\n<pre><code>http://example.com/stuff_(in parens)/\n</code></pre></li>\n<li><p>⊖ In a URL, the path is followed by a single query string, introduced by a <code>?</code>. Note that the semicolon <code>;</code> is the more modern, but equivalent alternative to the <code>&amp;</code> separator. The <code>+</code> means a literal space here. The query string may only be followed by a fragment, which is separated by <code>#</code>. Other instances have to be encoded.</p></li>\n</ul>\n\n<hr>\n\n<p>For an overview of URL syntax, start with this <a href=\"https://en.wikipedia.org/wiki/URL\">Wikipedia article</a>. Also look at <a href=\"https://en.wikipedia.org/wiki/URI_scheme\">URI Schemes</a>. These articles also link to relevant specs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T16:15:03.700", "Id": "33744", "ParentId": "33739", "Score": "15" } }, { "body": "<p><strong>As an addentum to @amon's excellent answer:</strong></p>\n\n<p>The <em>Expression Library</em> of the <em>Expresso</em> RegEx tool has this pattern for URL's (C# syntax):</p>\n\n<pre><code>(?&lt;Protocol&gt;\\w+):\\/\\/(?&lt;Domain&gt;[\\w@][\\w.:@]+)\\/?[\\w\\.?=%&amp;=\\-@/$,]*\n</code></pre>\n\n<p>Putting it against @amon's test cases yields these results:</p>\n\n<p><img src=\"https://i.stack.imgur.com/wzH3t.png\" alt=\"url regex validation\"></p>\n\n<p>Stuff in parentheses isn't captured, nor IPV6 IP's. But I'd consider it a good <strong>starting point</strong> with fewer false positives, and it also matches all the common URL's in this question.</p>\n\n<p>Now your pattern doesn't match <em>any</em> of the URL's I've tested with that tool, and the above regex pattern certainly wouldn't work in JavaScript. Removing the named capture groups gives this (untested):</p>\n\n<pre><code>\\w+:\\/\\/[\\w@][\\w.:@]+\\/?[\\w\\.?=%&amp;=\\-@/$,]*\n</code></pre>\n\n<h3>Some ideas:</h3>\n\n<ul>\n<li>Use numbered <strong>capture groups</strong> to distinguish the URL parts. It makes it a little easier to debug a regular expression that doesn't do what it's supposed to be doing.</li>\n<li>Depending on how the result is used, I would also add a group that captures the <strong>query string</strong> independently, if the URL has one.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T18:59:57.450", "Id": "36371", "ParentId": "33739", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T14:16:38.790", "Id": "33739", "Score": "8", "Tags": [ "javascript", "regex", "url" ], "Title": "What do you think of my regex for URL validation?" }
33739
<p>We want to check if a URL is down or not. But sometimes, the environment is down for maintenance for 3-4 hours and we don't want to keep sending emails during that time.</p> <p>I have written a shell script for performing a URL check and running it every 30 mins using a cronjob.</p> <p>The actual requirements are:</p> <ol> <li>Check if the URL is up. If it is down, send an email.</li> <li>Cronjob will execute the script again. If Step 1 sent an email, then send an email again asking if the environment is under maintenance.</li> <li>Cronjob will execute the script again. If it is still down, don't do anything.</li> <li>Keep checking the URL, and if it is responding, don't do anything. But if it goes down again, follow step 1-3.</li> </ol> <p>The script works. Could you please review and suggest if there is a nicer way of writing the script? I'm learning shell script but don't know all the available options.</p> <pre><code>#!/bin/bash #Checking urls from urls.txt MAddr="jsing002@internalsvcs.pte.com" TIME=`date +%d-%m-%Y_%H.%M.%S` SCRIPT_LOC=/user/inf/ete4/eteabp4/eid_scripts/jsing002 for url in `awk '{print $1}' $SCRIPT_LOC/urls.txt` do /usr/bin/wget -t 0 --spider --no-check-certificate $url &gt; wget.output 2&gt;&amp;1 HTTPCode=`(/usr/bin/wget -t 0 --spider --no-check-certificate $url) 2&gt;&amp;1 | grep HTTP| tail -1|cut -c 41-43` ENV=`(grep $url $SCRIPT_LOC/urls.txt | awk '{print $2}')` echo $HTTPCode E1=`/bin/grep -ise 'refused' -ise 'failed' wget.output` if [ "$E1" != "" ] || [ $HTTPCode -ge 500 ] then status="DOWN" echo "Step 1" echo "${ENV}""_DOWN" if [ -f "${ENV}""_DOWN" ]; then echo "step 2" echo "Please check if $ENV in Maintanance window.The check for $url has failed twice.Next The next failure email will be sent if preceding test was SUCCESSFUL" | /bin/mail -s "Is $ENV in Maintanance Window ?" $MAddr mv "${ENV}""_DOWN" "${ENV}""_DOWN""_2" echo "Step 3" elif [ -f "${ENV}""_DOWN""_2" ]; then echo "this is elif statement" else echo "E1 is empty. Site is down" echo "Site is down. $url is not accessible" | /bin/mail -s "$ENV is $status" $MAddr touch "${ENV}""_DOWN" fi else if [ $HTTPCode -eq 200 ] then status="UP" echo $status rm "${ENV}""_DOWN""_2" fi fi done Content of urls.txt: http://mer01bmrim:30270/rim/web E2E-RIMLITE4 http://mer01csmap:18001/console ABP_WL-E2E1 http://mer02sitap:18051/console ABP_WL-E2E2 http://mer03sitap:18101/console ABP_WL_E2E3 </code></pre>
[]
[ { "body": "<ul>\n<li><strong>Quoting:</strong> Be in the habit of <em>always</em> double-quoting your variables when you use them, e.g. <code>\"$url\"</code> instead of <code>$url</code>. Otherwise, nasty vulnerabilities could happen if a variable's value contains spaces or shell metacharacters. URLs, especially, often contain special characters such as <code>&amp;</code> and <code>?</code>.</li>\n<li><p><strong>Structure:</strong> When processing input with multiple columns, one row at a time, the idiom to use is…</p>\n\n<pre><code>while read url env ; do\n # Do stuff here\ndone &lt; \"$SCRIPT_LOC/urls.txt\"\n</code></pre>\n\n<p>If the columns are delimited by something other than whitespace…</p>\n\n<pre><code>while IFS=: read user pwhash uid gid gecos homedir shell ; do\n # Do stuff here\ndone &lt; /etc/passwd\n</code></pre></li>\n<li><p><strong>Status of <code>wget</code>:</strong> You run <code>wget</code> twice for each URL. Instead of trying to get the HTTP status code, consider using just the <a href=\"http://www.gnu.org/software/wget/manual/html_node/Exit-Status.html\" rel=\"nofollow\">exit status</a> of <code>wget</code> to indicate success or failure.</p>\n\n<pre><code>if wget -q -t 0 --spider --no-check-certificate \"$url\" ; then\n # Handle success\nelse\n # Handle failure\nfi\n</code></pre>\n\n<p>I've used the <code>--quiet</code> flag here. Also, I think that an infinite timeout (<code>-t 0</code>) is a bad idea.</p></li>\n<li><strong>HTTP status interpretation:</strong> HTTP status codes other than 200 (e.g. 2xx or 3xx) could also indicate some kind of success.</li>\n<li><strong>Filesystem littering:</strong> You litter the current directory with temporary files <code>wget.output</code> and <code>\"${ENV}_DOWN\"</code> and <code>\"${ENV}_DOWN_2\"</code>. Perhaps you could append all the state to a single log file.</li>\n<li><code>SCRIPT_LOC</code> could probably be computed using <code>$(dirname $0)</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T15:56:59.347", "Id": "54116", "Score": "0", "body": "@200_suceess . Thank you for replying. I'm going to include Quoting,--quiet in wget and Filesystem littering suggestion.<br/> . For structure section,i am using 2nd column to indicate the environment being represented by url. Thats why im using awk to get the url and then 2 column value in email to notify which environment is down. Is a good way to implement like this ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T08:58:16.017", "Id": "33785", "ParentId": "33742", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T15:56:15.440", "Id": "33742", "Score": "3", "Tags": [ "bash", "http", "url", "shell" ], "Title": "Send an email if a URL is down twice only" }
33742
<p>I want to build a robust and highly scalable client server system. Here what I have so far(an echo server as my base of implementation)</p> <p>My Server</p> <pre><code> private void startServer_Click(object sender, RoutedEventArgs e) { if (anyIP.IsChecked == true) { listener = new TcpListener(IPAddress.Any, Int32.Parse(serverPort.Text)); Logger.Info("Ip Address : " + IPAddress.Any + " Port : " + serverPort.Text); } else { listener = new TcpListener(IPAddress.Parse(serverIP.Text), Int32.Parse(serverPort.Text)); Logger.Info("Ip Address : " + serverIP.Text + " Port : " + serverPort.Text); } try { listener.Start(); Logger.Info("Listening"); HandleConnectionAsync(listener, cts.Token); } //finally //{ //cts.Cancel(); //listener.Stop(); //Logger.Info("Stop listening"); //} //cts.Cancel(); } async Task HandleConnectionAsync(TcpListener listener, CancellationToken ct) { while (!ct.IsCancellationRequested) { Logger.Info("Accepting client"); //TcpClient client = await listener.AcceptTcpClientAsync(); TcpClient client = await listener.AcceptTcpClientAsync(); Logger.Info("Client accepted"); EchoAsync(client, ct); } } async Task EchoAsync(TcpClient client, CancellationToken ct) { var buf = new byte[4096]; var stream = client.GetStream(); while (!ct.IsCancellationRequested) { var amountRead = await stream.ReadAsync(buf, 0, buf.Length, ct); Logger.Info("Receive " + stream.ToString()); if (amountRead == 0) break; //end of stream. await stream.WriteAsync(buf, 0, amountRead, ct); Logger.Info("Echo to client"); } } private void stopServer_Click(object sender, RoutedEventArgs e) { cts.Cancel(); listener.Stop(); Logger.Info("Stop listening"); } </code></pre> <p>My Client</p> <pre><code> private void connect_Click(object sender, System.Windows.RoutedEventArgs e) { IPAddress ipAddress; int port; //TODO Check if ip address is valid ipAddress = IPAddress.Parse(serverIP.Text); //TODO port range is 0-65000 port = int.Parse(serverPort.Text); StartClient(ipAddress, port); } private static async void StartClient(IPAddress serverIpAddress, int port) { var client = new TcpClient(); //can i try/catch to catch await exception? try { await client.ConnectAsync(serverIpAddress, port); } catch (Exception e) { Logger.Info(e); } Logger.Info("Connected to server"); using (var networkStream = client.GetStream()) using (var writer = new StreamWriter(networkStream)) using (var reader = new StreamReader(networkStream)) { writer.AutoFlush = true; for (int i = 0; i &lt; 10; i++) { Logger.Info("Writing to server"); await writer.WriteLineAsync(DateTime.Now.ToLongDateString()); Logger.Info("Reading from server"); var dataFromServer = await reader.ReadLineAsync(); if (!string.IsNullOrEmpty(dataFromServer)) { Logger.Info(dataFromServer); } } } if (client != null) { client.Close(); Logger.Info("Connection closed"); } } </code></pre>
[]
[ { "body": "<ol>\n<li>The general issue with your code is that your client and server implementations reside in your control's code-behind. It is always a good idea to separate business logic from UI.</li>\n<li><p>This is copy-paste:</p>\n\n<pre><code>if (anyIP.IsChecked == true)\n{\n listener = new TcpListener(IPAddress.Any, Int32.Parse(serverPort.Text));\n Logger.Info(\"Ip Address : \" + IPAddress.Any + \" Port : \" + serverPort.Text);\n}\nelse\n{\n listener = new TcpListener(IPAddress.Parse(serverIP.Text), Int32.Parse(serverPort.Text));\n Logger.Info(\"Ip Address : \" + serverIP.Text + \" Port : \" + serverPort.Text);\n}\n</code></pre>\n\n<p>can be refactored to:</p>\n\n<pre><code>var ip = anyIP.IsChecked == true ? IPAddress.Any : IPAddress.Parse(serverIP.Text);\nvar port = Int32.Parse(serverPort.Text);\nlistener = new TcpListener(ip, port);\nLogger.Info(String.Format(\"Ip Address : {0} Port : {1}\", ip, port));\n</code></pre></li>\n<li><p>Its a good style to prefix fields with underscore, so they can be distinguished from local variables. So it should be <code>_listener</code> instead of <code>listener</code>.</p></li>\n<li><p>You should shut down your server on exit.</p></li>\n<li><p>Yes, as long, as you await the call you can catch exceptions.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T07:40:16.380", "Id": "54198", "Score": "0", "body": "Thank you. 1 and 2. I write it as fast as i can and i know its ugly. 3. I didnt know that. Thanks. 4. Youre right. 5. Thank you for that confirmation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T05:46:35.683", "Id": "33821", "ParentId": "33748", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T17:44:43.493", "Id": "33748", "Score": "6", "Tags": [ "c#", "tcp", "async-await" ], "Title": "WPF async await TcpClient/TcpListener sample" }
33748
<p>I'm trying to clean up my JQuery code for my tabs. I have 3 different styles. How do I make the following shorter?</p> <pre><code>$(document).ready(function () { $('.tabs-style1 li').click(function () { var tab_id = $(this).attr('data-tab'); $('.tabs-style1 li').removeClass('current'); $('.tab-content-style1').removeClass('current'); $(this).addClass('current'); $("#" + tab_id).addClass('current'); }) }) $(document).ready(function () { $('.tabs-style2 li').click(function () { var tab_id = $(this).attr('data-tab'); $('.tabs-style2 li').removeClass('current'); $('.tab-content-style2').removeClass('current'); $(this).addClass('current'); $("#" + tab_id).addClass('current'); }) }) $(document).ready(function () { $('.tabs-style3 li').click(function () { var tab_id = $(this).attr('data-tab'); $('.tabs-style3 li').removeClass('current'); $('.tab-content-style3').removeClass('current'); $(this).addClass('current'); $("#" + tab_id).addClass('current'); }) }) </code></pre> <p>Your help will be appreciated! <a href="http://michellecantin.ca/test/features/tabs/" rel="nofollow">http://michellecantin.ca/test/features/tabs/</a></p>
[]
[ { "body": "<p>The visual style of your tabs is actually independent of their functionality. That is, they all <em>behave</em> as tabs, regardless of how they look.</p>\n\n<p>So, while you could make your code more generic by making the selector strings on the fly (<code>$(\".tab-content-\" + styleName)</code> etc.), I'd recommend something different.</p>\n\n<p>I'd start by separating the classes that describe style from the ones that describe function. Then I'd use the structure of the markup to figure out the rest; not everything needs a class name.</p>\n\n<p>I.e. given this markup, which is slightly changed/simplified from yours</p>\n\n<pre><code>&lt;div class=\"tabs tabs-style1\"&gt;\n &lt;ul class=\"tabs-list\"&gt;\n &lt;li class=\"current\" data-tab=\"tab-1\"&gt;Tab One&lt;/li&gt;\n &lt;li data-tab=\"tab-2\"&gt;Tab Two&lt;/li&gt;\n &lt;li data-tab=\"tab-3\"&gt;Tab Three&lt;/li&gt;\n &lt;li data-tab=\"tab-4\"&gt;Tab Four&lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;div id=\"tab-1\" class=\"current\"&gt;\n &lt;p&gt;Lorem ipsum...&lt;/p&gt;\n &lt;/div&gt;\n\n &lt;div id=\"tab-2\"&gt;\n &lt;p&gt;Duis aute...&lt;/p&gt;\n &lt;/div&gt;\n\n &lt;div id=\"tab-3\"&gt;\n &lt;p&gt;Ut enim...&lt;/p&gt;\n &lt;/div&gt;\n\n &lt;div id=\"tab-4\"&gt;\n &lt;p&gt;Sed do eiusmod...&lt;/p&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>The code can be shortened to</p>\n\n<pre><code>$(\".tabs\").each(function () {\n var container = $(this);\n container.find(\".tabs-list li\").on(\"click\", function () {\n var tab = $(this),\n target = tab.data(\"tab\");\n tab.addClass(\"current\")\n .siblings().removeClass(\"current\");\n container.children(\"#\" + target).addClass(\"current\")\n .siblings(\"div\").removeClass(\"current\");\n });\n});\n</code></pre>\n\n<p>for any and all \"tab areas\" on the page. It'll also work if you add new styles later, or remove any of ones you have. I.e. the visual style is decoupled from the behavior. Also, you only need to change the class name in one place to re-style an entire tab area.</p>\n\n<p>CSS-wise, simply scope your rules to <code>.style1</code>, <code>.style2</code> etc. and perhaps use the direct-descendant operator, while keeping the base styling common for all styles</p>\n\n<pre><code>.tabs-style1 .tabs-list { ... }\n.tabs-style1 .tabs-list li { ... }\n.tabs-style1 &gt; div { /* tab content styling */ }\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/9dFzZ/1/\" rel=\"nofollow\">Here's a demo</a> (it's ugly - just demonstrating the functionality)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T20:33:16.877", "Id": "33756", "ParentId": "33751", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T18:53:03.243", "Id": "33751", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "How do I shorten my JQuery tabs?" }
33751
<p>So I ran into an issue where a client sent me a sample file and the line breaks were not preserved when reading the file using PHP from linux. So I wrote up a little function that should hopefully fix the issue for all platforms.</p> <p>This is from a larger File class. The function names are pretty self explanatory.</p> <pre><code>public function fixLineBreaks() { $this-&gt;openFile(); // replace all placeholder with proper \r\n $contents = str_replace("[%LINEBREAK%]", "\r\n", // replace all double place holder with single // in case both \r and \n was used. str_replace("[%LINEBREAK%][%LINEBREAK%]", "[%LINEBREAK%]", // replace all \n with place holder str_replace("\n", "[%LINEBREAK%]", // replace all \r with placeholder str_replace("\r", "[%LINEBREAK%]", // First, read the file. fread($this-&gt;fp, filesize($this-&gt;filename)) ) ) ) ); $this-&gt;closeFile(); $this-&gt;writeOpen(); fwrite($this-&gt;fp, $contents); $this-&gt;closeFile(); } </code></pre> <p><strong>EDIT</strong></p> <p>Okay, to clarify. I received a CSV file that was supposed to be parsed in PHP. Open it up in notepad and everything is on one line. Opening it with fopen and then reading with fgetcsv would also return the contents as one line. However, if you copy and paste the contents from notepad into NetBeans then all the line breaks are there. This made me realize that there are line breaks but they're not the ones that notepad or PHP recognize.</p> <p>This was the function that I wrote up which essentially re-writes the file with proper line breaks.</p> <p>I was posting this here to see if anyone possible had a better solution.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T21:20:10.920", "Id": "54045", "Score": "0", "body": "And what exactly are you after?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T23:04:43.517", "Id": "54056", "Score": "0", "body": "What is the expected behaviour? I'm not sure that this code does anything useful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T02:56:01.930", "Id": "54081", "Score": "0", "body": "@200_success I think it replaces all line breaks (Mac and Unix style) with windows line breaks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T03:28:01.173", "Id": "54082", "Score": "0", "body": "Have you considered enabling the [`auto_detect_line_endings`](http://php.net/manual/en/function.fgetcsv.php#refsect1-function.fgetcsv-returnvalues) setting?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-04T22:44:49.530", "Id": "506942", "Score": "0", "body": "This title is too vague. Can you provide a sample input string and show us what the desired output is? I am pretty sure I can give a better answer than the one provided, but I need to better understand the desired behavior. @Vit" } ]
[ { "body": "<p>This conversion can be done by simple apps from the <a href=\"http://waterlan.home.xs4all.nl/dos2unix.html#DOS2UNIX\" rel=\"nofollow noreferrer\">Dos2Unix package</a>.</p>\n<p>However, if you insist on writing your own converter, I'd suggest making fewer function calls. The function <a href=\"http://php.net/manual/en/function.str-replace.php\" rel=\"nofollow noreferrer\"><code>str_replace()</code></a> can accept arrays, so there is no need for embedded calls.</p>\n<pre><code>$contents = str_replace(\n array(&quot;\\r&quot;, &quot;\\n&quot;, &quot;[%LINEBREAK%][%LINEBREAK%]&quot;, &quot;[%LINEBREAK%]&quot;),\n array(&quot;[%LINEBREAK%]&quot;, &quot;[%LINEBREAK%]&quot;, &quot;[%LINEBREAK%]&quot;, &quot;\\r\\n&quot;),\n fread($this-&gt;fp, filesize($this-&gt;filename))\n);\n</code></pre>\n<p>However, you ought to be careful. For example, if your file has two Unix-standard newlines, i.e., <code>\\n\\n</code>, then your code will replace this with <code>\\r\\n</code>, which is only one Windows-standard newline.</p>\n<p>This regex (see about its syntax <a href=\"http://perldoc.perl.org/perlre.html\" rel=\"nofollow noreferrer\">here</a>) would probably do the trick:</p>\n<pre><code>preg_replace('#(?&lt;!\\r)\\n|\\r(?!\\n)#', &quot;\\r\\n&quot;, fread($this-&gt;fp, filesize($this-&gt;filename)));\n</code></pre>\n<p>But I still think it's better to use already existing and proven software, like the one from the beginning of this answer, or simply turn on the <a href=\"http://php.net/manual/en/function.fgetcsv.php#refsect1-function.fgetcsv-returnvalues\" rel=\"nofollow noreferrer\">auto_detect_line_endings</a> setting, as suggested in the comments by <a href=\"https://codereview.stackexchange.com/users/9357/200-success\">200_success</a>.</p>\n<p>By the way, if your files are huge, your <code>fread</code> will still (try to) read them whole at once, which is not pleasant for the computer memory and performance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-11-04T12:12:09.070", "Id": "33788", "ParentId": "33755", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T20:21:11.260", "Id": "33755", "Score": "1", "Tags": [ "php" ], "Title": "Fix line breaks, cross-platform" }
33755
<p>Please check this program that sorts an integer array. It doesn't look very efficient. Please tell me how to correct this.</p> <pre><code>int temp; for(int i=0;i&lt;nums.length-1;i++) { if(nums[i]&gt;nums[i+1])// if this is true, swap the value { temp=nums[i]; nums[i]=nums[i+1]; nums[i+1]=temp; i=-1;//If there is swap happen, loop will start again from 0th element } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:30:57.917", "Id": "54061", "Score": "0", "body": "Check the Program with nums={5,4,3,2,1}, does not work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:35:15.077", "Id": "54062", "Score": "0", "body": "The program works. `i-=1` would not work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:40:44.493", "Id": "54063", "Score": "0", "body": "Welcome to the wonderful world of code analysis. Which is outside the realm of stackoverflow. Efficiency depends on your expected input. If you expect sorted data then this is the best. If you expect unsorted data then it is close to being the worst." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T14:32:37.933", "Id": "60827", "Score": "0", "body": "Speaking of sorts, here is a nice visualization of sort algorithms http://www.youtube.com/watch?v=kPRA0W1kECg" } ]
[ { "body": "<p>Ok, you might not be aware, but you will be now, Arrays has its own sort method you can use if you want to. Look at the <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html\" rel=\"nofollow\">Arrays java documentation</a>!\nAnd in terms of efficiency I think java has that covered for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:32:47.477", "Id": "54064", "Score": "0", "body": "What if he wants to learn how to sort?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:36:25.093", "Id": "54065", "Score": "0", "body": "I would definitely go with implementing a merge sort algorithm. http://en.wikipedia.org/wiki/Merge_sort worst case is O(n log n)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:48:30.083", "Id": "54066", "Score": "0", "body": "@alex or quicksort - it's a classic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:51:06.123", "Id": "54067", "Score": "1", "body": "@AlexGoja: For small numbers of elements (where n is, say, less than a few hundred) it is not wrong to view the time complexity is `O(n log n) + V` where V represents the algorithm overhead. For small values of n, it can be as performant (or even more performant) to utilize simpler sorting algorithms. For large n, as you've pointed out, V becomes insignificant and the complexity is O(n log n)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:54:50.823", "Id": "54068", "Score": "0", "body": "Correct. I should have mentioned perhaps that I choose the algorithm that always has the best running time in the worst case situation since he hinted he wanted a more efficient way of doing sorting. However, I see the worst case for quick sort is rarely the case so you could go with quick sort, too. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:56:58.023", "Id": "54069", "Score": "0", "body": "I agree with you scottb, I actually wanted to edit my comment and add just that info, but for some reason I had to wait 5 min. :(. Thanks for doing it yourself." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:31:41.240", "Id": "33762", "ParentId": "33761", "Score": "0" } }, { "body": "<p>Here are some links to sorting techniques:\n<a href=\"http://en.wikipedia.org/wiki/Bubble_sort\" rel=\"nofollow\">bubble sort</a> ,\n<a href=\"http://en.wikipedia.org/wiki/Insertion_sort\" rel=\"nofollow\">insertion sort</a>, <a href=\"http://en.wikipedia.org/wiki/Merge_sort\" rel=\"nofollow\">merge sort</a>What you're doing in your code isn't efficient. In the worst case scenario where the array is totally unsorted it'll take quite sometime to sort it the way you're doing it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T14:32:18.573", "Id": "60826", "Score": "1", "body": "You forgot my personal favorite; *bogo sort*." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:39:32.643", "Id": "33763", "ParentId": "33761", "Score": "1" } }, { "body": "<p>Your algorithm does not look like a viable array sorting algorithm. Perhaps there are some data sets that it would be able to yield a correct result on, but I do not think it would yield correct results for arbitrary data sets. Maybe it's alright ... without working through it all I can say is that it's an unusual solution.</p>\n\n<p>Following is the pseudo-code for a conceptually very simple sorting algorithm called the \"Delayed Replacement Sort\" (or, perhaps more commonly, the \"Selection Sort\"):</p>\n\n<pre><code>Begin DELAYEDSORT\n For ITEM=1 to maximum number of items in list-1\n LOWEST=ITEM\n For N=ITEM+1 to maximum number of items in list\n Is entry at position N lower than entry at position LOWEST?\n If so, LOWEST=N\n Next N\n Is ITEM different from LOWEST\n If so, swap entry at LOWEST with entry in ITEM\n Next ITEM\nEnd DELAYEDSORT\n</code></pre>\n\n<p>You should be able to easily adapt this pseudo-code into a Java method. Note that this algorithm has two loops:</p>\n\n<ul>\n<li>the outer loop is finished when the whole array has been sorted</li>\n<li>the inner loop finds the \"lowest\" element in the portion of the array that is still unsorted.</li>\n</ul>\n\n<p>After the inner loop, a check is made to see if a swap needs to be made. It is this step that gives the algorithm its name; swapping is only done if it needs to be done to order the element indicated by the index of the outer loop.</p>\n\n<p>Good luck.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:42:30.590", "Id": "33764", "ParentId": "33761", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T23:23:37.537", "Id": "33761", "Score": "1", "Tags": [ "java", "optimization", "sorting" ], "Title": "Sorting integer array" }
33761
<p>I am trying to write something that will copy the current <code>&lt;input&gt;</code>s value and enter it into any <code>&lt;input&gt;</code> that start with the same name.</p> <p><code>&lt;input&gt;</code> names will follow this pattern: <code>price-0</code>, <code>price-1</code>, <code>price-2</code>, <code>upc-0</code>, <code>upc-1</code>, <code>upc-2</code>.</p> <p>So if a user enters a value in <code>&lt;input name="price-0"&gt;</code> and hits copy the value should be transferred over to all input whos name start with <code>price</code></p> <p>This is the code I've written:</p> <pre><code>$(document).on('click', '.--copy', function () { var input_name = $(this).closest('div').find('input').attr('name').split('-')[0]; $('input[name^=' + input_name + ']').val($(this).closest('div').find('input').val()); }); </code></pre> <p>A fiddle to make everyones life easier: <a href="http://jsfiddle.net/6jGLD/" rel="nofollow">http://jsfiddle.net/6jGLD/</a></p> <p>I feel like there are too many selectors being called upon and the code is somewhat difficult to read.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T00:32:51.593", "Id": "54072", "Score": "1", "body": "It would probably be easier to give each related input an identical class. Other than that, I would do `$input = $(this).closest('div').find('input')` at the beginning of your function so you don't have to traverse the dom to find the input twice." } ]
[ { "body": "<p>One minor improvement I can think of is to create a variable to hold the input element since the element is used twice like</p>\n\n<pre><code>$(document).on('click', '.--copy', function () {\n var $input = $(this).closest('div').find('input'), input_name = $input.attr('name').split('-')[0];\n $('input[name^=' + input_name + ']').val($input.val());\n});\n</code></pre>\n\n<p>Demo: <a href=\"http://jsfiddle.net/arunpjohny/Z4FUd/\" rel=\"nofollow\">Fiddle</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T00:33:03.250", "Id": "33766", "ParentId": "33765", "Score": "2" } }, { "body": "<p>You can just grab the value of the first input put it in a variable and put that variable as the value of the second input for example</p>\n\n<pre><code>var value = $('input.firstInput').val();\n $('input.secondInput').val(value);\n</code></pre>\n\n<p>here is a jsfiddle\n<a href=\"http://jsfiddle.net/suyRd/\" rel=\"nofollow\">http://jsfiddle.net/suyRd/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T05:38:27.207", "Id": "54073", "Score": "0", "body": "The HTML should not be changed in the fiddle" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T01:15:03.670", "Id": "33767", "ParentId": "33765", "Score": "0" } } ]
{ "AcceptedAnswerId": "33766", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T00:29:11.703", "Id": "33765", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Is there a simpler way of copying and pasting one inputs value into other input with the same name" }
33765
<p>This tag is for questions related to the loading, formatting, saving, compression, and display of data representing pictures. For visual presentations that are programmatically generated, use the related tag <a href="/questions/tagged/graphics" class="post-tag" title="show questions tagged &#39;graphics&#39;" rel="tag">graphics</a> instead.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T00:47:44.623", "Id": "33768", "Score": "0", "Tags": null, "Title": null }
33768
This tag is for questions related to the loading, formatting, saving, compression, and display of data representing pictures.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T00:47:44.623", "Id": "33769", "Score": "0", "Tags": null, "Title": null }
33769
<p>For <em>professional</em> game development assistance, consult <a href="https://gamedev.stackexchange.com/">Game Development SE</a>.</p> <hr> <p>Some tags on Code Review for specific types of games include:</p> <ul> <li><a href="/questions/tagged/adventure-game" class="post-tag" title="show questions tagged &#39;adventure-game&#39;" rel="tag">adventure-game</a></li> <li><a href="/questions/tagged/chess" class="post-tag" title="show questions tagged &#39;chess&#39;" rel="tag">chess</a></li> <li><a href="/questions/tagged/connect-four" class="post-tag" title="show questions tagged &#39;connect-four&#39;" rel="tag">connect-four</a></li> <li><a href="/questions/tagged/game-of-life" class="post-tag" title="show questions tagged &#39;game-of-life&#39;" rel="tag">game-of-life</a></li> <li><a href="/questions/tagged/hangman" class="post-tag" title="show questions tagged &#39;hangman&#39;" rel="tag">hangman</a></li> <li><a href="/questions/tagged/number-guessing-game" class="post-tag" title="show questions tagged &#39;number-guessing-game&#39;" rel="tag">number-guessing-game</a></li> <li><a href="/questions/tagged/playing-cards" class="post-tag" title="show questions tagged &#39;playing-cards&#39;" rel="tag">playing-cards</a></li> <li><a href="/questions/tagged/simon-says" class="post-tag" title="show questions tagged &#39;simon-says&#39;" rel="tag">simon-says</a></li> <li><a href="/questions/tagged/quiz" class="post-tag" title="show questions tagged &#39;quiz&#39;" rel="tag">quiz</a></li> <li><a href="/questions/tagged/sudoku" class="post-tag" title="show questions tagged &#39;sudoku&#39;" rel="tag">sudoku</a></li> <li><a href="/questions/tagged/tic-tac-toe" class="post-tag" title="show questions tagged &#39;tic-tac-toe&#39;" rel="tag">tic-tac-toe</a></li> </ul> <p>Code Review also has occasional <a href="/questions/tagged/community-challenge" class="post-tag" title="show questions tagged &#39;community-challenge&#39;" rel="tag">community-challenge</a> events, some of which involve creating small games for a Code Review question.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T00:57:30.330", "Id": "33770", "Score": "0", "Tags": null, "Title": null }
33770
For questions requesting reviews of game development code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T00:57:30.330", "Id": "33771", "Score": "0", "Tags": null, "Title": null }
33771
<p>In the application I'm building, the user is able to define 'types' where each 'type' has a set of 'attributes'.</p> <p>The user is able to create instances of products by defining a value for each attribute the product's type has.</p> <p>A pic of the schema: <img src="https://i.stack.imgur.com/pdQ4N.jpg" alt="A pic of the schema"></p> <p>I'm creating the query where the user specifies the attributes values and the product type and with that I should return all the product id's that meets the query.</p> <p>The problem I see in my query is that I'm performing a whole <code>select * from attributes_products ...</code> for each attribute that the product's type has.</p> <p>Is there a way to optimize this? If I create an index in the column attributes_products.product_id would this query be actually optimal?</p> <p>Example of a query where I'm looking for a product whose type has 3 attributes:</p> <pre><code>select p.id from Products as p where exists( select * from attributes_products where product_id = p.id AND attribute_id = 27 AND value = 'some_value' ) AND exists( select * from attributes_products where product_id = p.id AND attribute_id = 28 AND value = 'other_value' ) AND exists( select * from attributes_products where product_id = p.id AND attribute_id = 29 AND value = 'oother_value' ) </code></pre> <p>Many thanks.</p> <h1><strong>Conclusions</strong></h1> <p>So, Gareth Rees (selected answer) proposed another solution which involves multiple Joins. Here is the explanation of its query (done by PGAdmin): <img src="https://i.stack.imgur.com/LADhD.png" alt="Selected answer query explanation"></p> <p>This is the explanation of the original query: <img src="https://i.stack.imgur.com/dEcTA.png" alt="Original query"></p> <p>I believe that the selected answer is slightly faster, but consumes a lot more memory (because of the triple join). I believe that my original query is slightly slower (very slightly, since there's an index on the attributes_products table) but a lot more efficient in memory.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T17:30:16.877", "Id": "54132", "Score": "0", "body": "what Database Engine are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T17:54:07.190", "Id": "54137", "Score": "0", "body": "@Malachi, I'm using PostgreSQL as database manager/engine" } ]
[ { "body": "<p>SQL allows you to join the same table multiple times, so what you need here is:</p>\n\n<pre><code>SELECT p.id FROM products AS p\nJOIN attributes_products AS ap1\n ON ap1.product_id = p.id AND ap1.attribute_id = 27 AND ap1.value = '...'\nJOIN attributes_products AS ap2\n ON ap2.product_id = p.id AND ap2.attribute_id = 28 AND ap2.value = '...'\nJOIN attributes_products AS ap3\n ON ap3.product_id = p.id AND ap3.attribute_id = 29 AND ap3.value = '...'\n</code></pre>\n\n<p>Here's the toy MySQL database that I'm using to answer this question:</p>\n\n<pre><code>CREATE TABLE products (\n id INTEGER PRIMARY KEY AUTO_INCREMENT\n);\nCREATE TABLE attributes_products (\n product_id INTEGER NOT NULL,\n attribute_id INTEGER NOT NULL,\n value CHAR(40)\n);\nCREATE INDEX ap_product ON attributes_products (product_id);\nCREATE INDEX ap_attribute ON attributes_products (attribute_id);\n\nINSERT INTO products VALUES (1);\nINSERT INTO products VALUES (2);\nINSERT INTO attributes_products VALUES (1, 27, 'a');\nINSERT INTO attributes_products VALUES (1, 28, 'b');\nINSERT INTO attributes_products VALUES (1, 29, 'c');\n</code></pre>\n\n<p>With my query above, MySQL reports the following query plan:</p>\n\n<pre><code>+----+-------------+-------+--------+-------------------------+--------------+---------+---------------------+------+--------------------------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+----+-------------+-------+--------+-------------------------+--------------+---------+---------------------+------+--------------------------+\n| 1 | SIMPLE | ap1 | ref | ap_product,ap_attribute | ap_attribute | 4 | const | 1 | Using where |\n| 1 | SIMPLE | ap2 | ref | ap_product,ap_attribute | ap_attribute | 4 | const | 1 | Using where |\n| 1 | SIMPLE | ap3 | ref | ap_product,ap_attribute | ap_attribute | 4 | const | 1 | Using where |\n| 1 | SIMPLE | p | eq_ref | PRIMARY | PRIMARY | 4 | temp.ap3.product_id | 1 | Using where; Using index |\n+----+-------------+-------+--------+-------------------------+--------------+---------+---------------------+------+--------------------------+\n</code></pre>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/explain-output.html\" rel=\"nofollow\">See the MySQL documentation</a> for an explanation of the <code>EXPLAIN</code> output.</p>\n\n<p>This looks better than the plan for the OP's query:</p>\n\n<pre><code>+----+--------------------+---------------------+-------+-------------------------+--------------+---------+-------+------+--------------------------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+----+--------------------+---------------------+-------+-------------------------+--------------+---------+-------+------+--------------------------+\n| 1 | PRIMARY | p | index | NULL | PRIMARY | 4 | NULL | 2 | Using where; Using index |\n| 4 | DEPENDENT SUBQUERY | attributes_products | ref | ap_product,ap_attribute | ap_attribute | 4 | const | 1 | Using where |\n| 3 | DEPENDENT SUBQUERY | attributes_products | ref | ap_product,ap_attribute | ap_attribute | 4 | const | 1 | Using where |\n| 2 | DEPENDENT SUBQUERY | attributes_products | ref | ap_product,ap_attribute | ap_attribute | 4 | const | 1 | Using where |\n+----+--------------------+---------------------+-------+-------------------------+--------------+---------+-------+------+--------------------------+\n</code></pre>\n\n<p>But results will vary from one database to another: a good query planner might be able to make something efficient out of the OP's query.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T17:01:37.927", "Id": "54124", "Score": "0", "body": "wouldn't this still bog down a little bit? I mean not as much as the original but it would still bog down wouldn't it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T17:25:52.080", "Id": "54130", "Score": "0", "body": "It all depends on the query planner, but with indexes on `attributes_products.product_id` and `attributes_products.attribute_id` MySQL looks like it has a decent plan. Try it on your preferred database and see for yourself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T17:29:50.483", "Id": "54131", "Score": "0", "body": "I just assumed this was SQL Server, I didn't even look for tags...oops" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T18:32:14.893", "Id": "54147", "Score": "0", "body": "But what if I create an index in the attributes_products table on the product_id. Yes, my query is doing multiple subqueries, but I think that they would take minimum time given the index I'm talking about; in exchange of that, my query doesn't consumes too much memory. I think (but correct me if I'm wrong) that your query would be slightly faster, but it will hold a bunch of memory for the inner join." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T19:45:33.220", "Id": "54162", "Score": "1", "body": "There's no substitute for trying both and seeing which is better!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T13:42:06.730", "Id": "33792", "ParentId": "33772", "Score": "5" } } ]
{ "AcceptedAnswerId": "33792", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T01:17:02.960", "Id": "33772", "Score": "6", "Tags": [ "optimization", "sql", "postgresql" ], "Title": "Help optimizing this query with multiple where exists" }
33772
<p>I usually use the static methods from this designed class in order to perform objects serializing of custom classes.</p> <p>Even though I'm getting good results, I wonder if this is the most appropriate way for it and if there are any improvements for it?</p> <pre><code>public class InputOuput { private static FileOutputStream flujoSalida; private static ObjectOutputStream flujoSalidaObjetos; private static File archivo; private static final FileChooser seleccionador = new FileChooser(); private static FileInputStream flujoEntrada; private static ObjectInputStream flujoEntradaObjetos; public static boolean serialize(Object anObject) { seleccionador.setTitle("Dónde guardar el estado del programa"); try { archivo = seleccionador.showSaveDialog(null); if (archivo == null) return false; flujoSalida = new FileOutputStream(archivo); flujoSalidaObjetos = new ObjectOutputStream(flujoSalida); flujoSalidaObjetos.writeObject(anObject); flujoSalidaObjetos.close(); flujoSalida.close(); } catch (IOException error) { System.out.println(error.toString()); System.out.println(error.getStackTrace()); } return true; } public static Object deserialize() { Object m=null; try { archivo = seleccionador.showOpenDialog(null); if (archivo == null) return null; flujoEntrada = new FileInputStream(archivo); flujoEntradaObjetos = new ObjectInputStream(flujoEntrada); m= (Object) flujoEntradaObjetos.readObject(); flujoEntradaObjetos.close(); flujoEntrada.close(); } catch (IOException | ClassNotFoundException error) { System.out.println(error.toString()); System.out.println(error.getStackTrace()); } return m; } } </code></pre> <p>*<em>I change <code>Object</code> for the custom intended class</em></p> <p>One good point to ask: how could I be not making the <code>InputOutput</code> class to implement <code>Serializable</code>, yet it works properly anyway?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T05:08:20.943", "Id": "54084", "Score": "1", "body": "When you have variable names like \"m\", you should always think of renaming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:27:01.937", "Id": "76757", "Score": "0", "body": "I agree @Kinjal :)" } ]
[ { "body": "<p>All of your variables should be local, except for maybe the <code>FileChooser</code>.</p>\n\n<p>You swallow exceptions. Printing a stack trace is no substitution for proper exception handling. (By the way, logging should be done using <code>java.util.logging</code>. If you <em>must</em> print a stack trace manually, print it to <code>System.err</code> instead of <code>System.out</code>.) Serialization could completely fail, and the function will still return <code>true</code>. The most appropriate behaviour should be to propagate the exception to the caller.</p>\n\n<p>For greater flexibility and clarity with little additional effort, I suggest overloading <code>serialize()</code> and <code>deserialize()</code> with several variants which call each other:</p>\n\n<pre><code>public class InputOutput {\n private static final FileChooser seleccionador = new FileChooser();\n\n /**\n * Serializes an object to a file chosen by the user using a FileChooser.\n * @return true if completed, false if user cancels the FileChooser.\n */\n public static boolean serialize(Object o) throws IOException {\n seleccionador.setTitle(\"Dónde guardar el estado del programa\");\n File f = seleccionador.showSaveDialog(null);\n if (f == null) return false;\n serialize(o, f);\n return true;\n }\n\n public static void serialize(Object o, File f) throws IOException {\n try (FileOutputStream fos = new FileOutputStream(f)) {\n serialize(o, fos);\n }\n }\n\n public static void serialize(Object o, FileOutputStream fos) throws IOException {\n try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {\n oos.writeObject(o);\n }\n }\n\n /**\n * Deserializes an object from a file chosen by the user using a FileChooser.\n * @return the deserialized object, or null if user cancels the FileChooser.\n */\n public static Object deserialize() throws IOException { ... }\n public static Object deserialize(File f) throws IOException { ... }\n public static Object deserialize(FileInputStream fis) throws IOException { ... }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T04:06:29.797", "Id": "33778", "ParentId": "33773", "Score": "2" } } ]
{ "AcceptedAnswerId": "33778", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T17:24:26.263", "Id": "33773", "Score": "2", "Tags": [ "java", "serialization" ], "Title": "Is this the only or best method for classes serializing in Java?" }
33773
<p>I am constructing a selector on every radio button click. Since I am using the table repeatedly on every radio click, I cached it like:</p> <pre><code>var $t1 = $("#tableone"); </code></pre> <p>but inside the radio check event, I need to retrieve the selector to construct a string.</p> <p><strong>Approach 1:</strong></p> <pre><code>$radio.click(function () { var temp = $t1.selector + " ." + $(this).attr("mobnum"); </code></pre> <p><strong>Note:</strong> If I do not <code>$t1.selector</code>, it comes as [object][Object] which I do not want, so I have to use <code>$t1.selector</code>.</p> <p>Since I am using <code>$t1.selector</code> to construct temp every time radio is clicked, is there still a benefit caching the table at the beginning?</p> <p><strong>Approach 2:</strong></p> <pre><code>$radio.click(function () { var temp = $("#tableone") + " ." + $(this).attr("mobnum"); </code></pre> <p>Which one's better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-19T03:20:17.570", "Id": "54076", "Score": "0", "body": "It's unclear to me what you're doing. FYI, `.selector` is deprecated, and may be removed from jQuery in the future." } ]
[ { "body": "<p>I don't think your approach 2 will do what you want. So I the first one would be better.</p>\n\n<p>It looks to me though that you are building another selector. Probably to find the child element. So I would recommend something like this:</p>\n\n<pre><code>var $c = $t1.find(\".\" + $(this).attr(\"mobnum\")).\n</code></pre>\n\n<p>This returns the child element. This way you are already selecting only out of the children of <code>$t1</code>. Which would be more efficient, in theory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-19T03:33:24.793", "Id": "54079", "Score": "0", "body": "So essentially now I can do operations on $c right. Like $($c).hide() or $($c).show() right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-19T03:40:05.587", "Id": "54080", "Score": "0", "body": "That is correct, but you won't need to wrap it in a `$()`. `$c.show()` should be sufficient." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-19T03:21:11.400", "Id": "33775", "ParentId": "33774", "Score": "3" } } ]
{ "AcceptedAnswerId": "33775", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-19T03:15:06.263", "Id": "33774", "Score": "0", "Tags": [ "javascript", "jquery", "comparative-review" ], "Title": "Selector on every radio button click" }
33774
<p>I redid a Reversi game state class that is online. It follows the conventional rules of the board game. The game state connects to a command line interface now. I am unfamiliar with Android so comments related to that would be especially appreciated. Java related comments would be useful too.</p> <pre><code>/** * Date: 11/3/13 * Time: 11:07 AM * based on https://github.com/dweekly/android-reversi */ public class GameState { public static final byte DIM = 8; public static final byte MAXRAYS = 8; public static final char LIGHT = 'W'; public static final char DARK = 'B'; private final static char[][] DEFAULTBOARD = { {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', 'W', 'B', ' ', ' ', ' '}, {' ', ' ', ' ', 'B', 'W', ' ', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '} }; private char _board[][]; private char _currentSide; private boolean _frozen; public GameState() { this(DEFAULTBOARD, DARK); } public GameState(char board[][], char currentSide) { _board = new char[DIM][DIM]; transferBoard(_board, board); _currentSide = currentSide; _frozen = false; } public void freeze(boolean state) { _frozen = state; } public void transfer(GameState copy) { assert(!_frozen); _currentSide = copy._currentSide; transferBoard(_board, copy._board); } public void swapSides() { assert(!_frozen); assert (Location.isaSide(_currentSide)); _currentSide = (_currentSide == LIGHT) ? DARK : LIGHT; } private static void transferBoard(char[][] board1, char[][] board2) { for (byte x = 0; x &lt; DIM; x++) for (byte y = 0; y &lt; DIM; y++) board1[x][y] = board2[x][y]; } public byte moveTo(byte x, byte y, byte[] turners) { assert(!_frozen); return moveTo(x, y, turners, false); } public byte previewMove(byte x, byte y) { return moveTo(x, y, null, true); } private byte moveTo(byte x, byte y, byte[] turners, boolean preview) { assert (Location.isaSide(_currentSide)); assert (Location.isEmpty(_board[x][y])); assert (Location.isInBounds(x, y)); byte turnerCount = makeTurners(_currentSide, _board, x, y, turners); if (preview) { return turnerCount; } assert(!_frozen); _board[x][y] = _currentSide; for (byte i = 0; i &lt; turnerCount; i++) { Location.setLocation(_currentSide, _board, turners[i]); } return turnerCount; } public char at(byte x, byte y) { return _board[x][y]; } public boolean isCurrentSide(char c) { return _currentSide == c; } public boolean isFirstSide() { return _currentSide == GameState.DARK; } private static boolean checkForTurner(char currentSide, char[][] board, byte x, byte y) { return makeTurners(currentSide, board, x, y, null) != 0; } private static byte makeTurners(char currentSide, char[][] board, byte x, byte y, byte[] turners) { byte maxIndex = 0; for (byte dx = -1; dx &lt;= 1; dx++) { for (byte dy = -1; dy &lt;= 1; dy++) { if (dx == 0 &amp;&amp; dy == 0) continue; for (byte steps = 1; steps &lt; DIM; steps++) { int ray_x = x + dx * steps; int ray_y = y + dy * steps; if (Location.isOutOfBounds(ray_x, ray_y) || Location.isEmpty(board[ray_x][ray_y])) break; if (board[ray_x][ray_y] == currentSide) { if (steps &gt; 1) { for (int backStep = steps - 1; backStep &gt; 0; backStep--) { if (turners != null) { turners[maxIndex] = Location.toLocation(x + dx * backStep, y + dy * backStep); } maxIndex++; } } break; } assert(Location.getOtherSide(currentSide) == board[ray_x][ray_y]); } } } return maxIndex; } public byte makePossibleMoves(byte[] locations) { byte locationIndex = 0; for (byte x = 0; x &lt; DIM; x++) { for (byte y = 0; y &lt; DIM; y++) { if (Location.isEmpty(_board[x][y]) &amp;&amp; checkForTurner(_currentSide, _board, x, y)) { if (locations != null) { locations[locationIndex] = Location.toLocation(x, y); } locationIndex++; } } } return locationIndex; } public byte getScore(char side) { assert (Location.isValid(side)); byte result = 0; for (byte x = 0; x &lt; DIM; x++) { for (byte y = 0; y &lt; DIM; y++) { if (_board[x][y] == side) result++; } } return result; } public String toString() { StringBuffer sb = new StringBuffer(); for (byte y = 0; y &lt; DIM; y++) { for (byte x = 0; x &lt; DIM; x++) { if (Location.isEmpty(_board[x][y])) sb.append("."); else sb.append(_board[x][y]); } sb.append("\n"); } sb.append("\n"); return sb.toString(); } } /** * Date: 11/3/13 * Time: 11:33 AM */ public class Location { public static boolean isValid(char c) { return c == ' ' || c == 'B' || c == 'W'; } public static boolean isaSide(char c) { return c == 'B' || c == 'W'; } public static char getOtherSide(char c) { return c == 'B' ? 'W' : 'B'; } public static boolean isEmpty(char c) { return c == ' '; } public static boolean isInBounds(byte b) { return isInBounds(toX(b), toY(b)); } public static boolean isInBounds(int x, int y) { return x &gt;= 0 &amp;&amp; x &lt; GameState.DIM &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; GameState.DIM; } public static boolean isOutOfBounds(int x, int y) { return !isInBounds(x, y); } public static byte toLocation(int x, int y) { assert (isInBounds(x, y)); return (byte) (x + y * GameState.DIM); } public static void setLocation(char side, char[][] board, byte loc) { board[Location.toX(loc)][Location.toY(loc)] = side; } public static byte toX(byte b) { return (byte) (b % GameState.DIM); } public static byte toY(byte b) { return (byte) (b / GameState.DIM); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T23:13:12.690", "Id": "54177", "Score": "0", "body": "This code mixes the idea of a board with the idea of a game's rules. Without a lot of effort, you could refactor this code to apply to visually similar games (e.g., Go, Pente, Nine-Men's-Morris)." } ]
[ { "body": "<p>Your code looks <em>very</em> much like something one would write in C. On the one hand this is good, because you choose fairly efficient solutions. On the other hand, you throw away many powerful features of Java that would make your code simpler and safer. I'll just present a couple of spotlights that should get you going.</p>\n\n<h3>Java is Garbage Collected</h3>\n\n<p>This means you don't have to keep track of object ownership. For example, you can create a new array inside a method and return it without any problems. This is better than passing empty arrays as function arguments which you then populate. E.g. in <code>makeTurners</code>, the <code>turners</code> argument is unnecessary.</p>\n\n<h3>Arrays != Pointers</h3>\n\n<p>While arrays are a language primitive of Java, they are more sophisticated than their C counterpart. For example, they carry their length around with them: <code>someArray.length</code>.</p>\n\n<h3>The <em>Java Collection Framework</em></h3>\n\n<p>Arrays suck, and are not useful in most use cases (this is true in C++ as well, where the Standard Library provides superior alternatives to C arrays). The main problem with arrays is that they are fixed-sized, which forces you to carry the highest index around in variable-length situations. In Java, you can find lots of useful Collection classes in the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/package-summary.html\" rel=\"nofollow\"><code>java.util</code> namespace</a>. In most cases where you'd think “array”, use an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html\" rel=\"nofollow\"><code>ArrayList</code></a> instead. They support <em>parametric polymorphism</em> aka. <em>generics</em>. You can instantiate a new instance like:</p>\n\n<pre><code>List&lt;Integer&gt; myList = new ArrayList&lt;Integer&gt;();\n</code></pre>\n\n<p>where <code>Integer</code> is the type of object inside that collection. Note that primitive types like <code>char</code> or <code>int</code> cannot be used here, because they aren't objects. However, there are wrapper classes like <code>Character</code> and <code>Integer</code>. In many cases, primitives are promoted to the wrapper type, so you don't have to care.</p>\n\n<p>You can add a new element to a collection using the <code>add</code> method:</p>\n\n<pre><code>myList.add(42); // 42 gets promoted to an Integer\n</code></pre>\n\n<p>The <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/List.html\" rel=\"nofollow\"><code>List</code> interface</a> describes certain functionality that all <code>List</code>s implement, e.g. <code>ArrayList</code>s and <code>LinkedList</code>s. For example, this mandates a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/List.html#get%28int%29\" rel=\"nofollow\"><code>get</code> method</a>, so that we can access out elements:</p>\n\n<pre><code>Foo fooFromTheList = myList.get(0);\n</code></pre>\n\n<p>You can get the size of a collection like <code>myList.size()</code>.</p>\n\n<p>There are many more collections like various <code>Set</code>s and <code>Map</code>s.</p>\n\n<h3>Iteration</h3>\n\n<p>The built-in collections and the dumb arrays can be <em>iterated</em> over using a for-each type loop. This is useful whenever you don't really care about the indices. For example:</p>\n\n<pre><code> // with plain arrays\n int[] someInts = { 1, 42, 12 };\n for (int i : someInts) {\n System.out.println(i);\n }\n\n // with an array list\n List&lt;Integer&gt; moreInts = new ArrayList&lt;Integer&gt;();\n moreInts.add(1);\n moreInts.add(42);\n moreInts.add(12);\n\n for (int i : moreInts) {\n System.out.println(i);\n }\n</code></pre>\n\n<h3>Java is Object Oriented</h3>\n\n<p>Currently, you are only using classes to namespace your functions. This is a good start. However, they are also useful as supercharged C structs, that is: to group data together.</p>\n\n<p>For example, you could group the <code>x</code> and <code>y</code> to a single <code>Location</code>:</p>\n\n<pre><code>class Location {\n public in x, y; // here we declare member fields\n\n // this is a *constructor*\n public Location(int x, int y) {\n this.x = x;\n this.y = y;\n }\n}\n</code></pre>\n\n<p>We can now create a new <code>Location</code> like <code>Location overThere = new Location(x, y)</code>. We can access the fields like <code>overThere.x</code>. Other functions that are only about locations all belong in that class.</p>\n\n<p>Another class you should create is a <code>Board</code>, e.g.:</p>\n\n<pre><code>class Board {\n public char[][] board;\n public int size;\n\n public Board(char[][] board) {\n this.size = board.length;\n // ... copy the primitive board over here\n }\n\n // ... utility methods\n}\n</code></pre>\n\n<p>This class would then contain methods that are only about the <code>Board</code>, not about a <code>Location</code> or a <code>GameState</code>. Examples are field access and bounds checking, which belongs here. The <code>Board</code> should also have a <code>toString()</code> method which gets called when you try to print out a <code>Board</code>. The default board also belongs <em>here</em>, not into the game state.</p>\n\n<p>The <code>GameState</code> would then have a member field containing a <code>Board</code> instance.</p>\n\n<h3>Single Responsibility Principle (SRP) and other design guidelines</h3>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">SRP</a> is an object-oriented design principle that tells us that each class should have one single task. Any further functionality does not belong there. When I look at your code, I see various things that should be classes of their own:</p>\n\n<ul>\n<li>Already mentioned: <code>Board</code>, <code>Location</code>.</li>\n<li>Use a class for your <code>Side</code>s instead of chars.</li>\n<li>Use a class for your <code>Field</code>s instead of chars.</li>\n<li><p>Maybe use a class to represent each <code>Move</code>, rather than implicitly encoding this in the <code>GameState</code>. A <code>Move</code> would then have a source <code>GameState</code>, and lead to another one. It has a <code>Location</code> where a player places a disk, and a <code>List&lt;Location&gt;</code> of all discs that will be flipped by this move. What is the advantage of this abstraction?</p>\n\n<ol>\n<li>Because it records the prior state, you can easily implement an <code>undo</code> operation.</li>\n<li>This representation has the effect that each <code>GameState</code> can be viewed as a vertex and each <code>Move</code> as an edge in a <a href=\"https://en.wikipedia.org/wiki/Game_tree\" rel=\"nofollow\">game tree</a>. This makes it much easier to implement an AI that can take enemy moves into account.</li>\n</ol>\n\n<p>Compare also the <a href=\"https://en.wikipedia.org/wiki/Command_pattern\" rel=\"nofollow\"><em>Command Pattern</em></a>.</p></li>\n<li>Possibly a <code>Rules</code> class that encapsulates the exact rules of the game: Remember that <em>Reversi</em> and <em>Othello</em> are quite similar games that only differ in few details. But much of your code (especially for the board etc) could also be reused for a game of <em>Draughts</em>.</li>\n</ul>\n\n<p>Don't be afraid of writing small classes that seem to do little. If chosen wisely, they actually provide an invaluable service: Structuring your code and data.</p>\n\n<h3>Enumerations</h3>\n\n<p>In Java, an <code>enum</code> is a special kind of class. In the simplest case, it just provides a couple of names:</p>\n\n<pre><code>enum Field { EMPTY, BLACK, WHITE }\n</code></pre>\n\n<p>This is better than using some special <code>char</code>s, because this is actually type safe and can guarantee that no illegal values show up where a <code>Field</code> is expected.</p>\n\n<p>Because an <code>enum</code> is a class, we can also provide a constructor and member fields, e.g:</p>\n\n<pre><code>enum Field {\n EMPTY(\".\"),\n BLACK(\"B\"),\n WHITE(\"W\");\n\n public final String symbol;\n\n public Field(String symbol) {\n this.symbol = symbol;\n }\n}\n</code></pre>\n\n<p>Why are Enums awesome?</p>\n\n<ul>\n<li>They are fully comparable.</li>\n<li>We can now have a <code>Field[][]</code> instead of an <code>char[][]</code> for our board – but with full type safety!</li>\n<li>When coerced to a string, it produces its name: <code>System.out.println(Field.EMPTY)</code> is <code>EMPTY</code>.</li>\n<li><p>When printing out the <code>Board</code>, we can directly access the symbol in each instance:</p>\n\n<pre><code>for (Field[] row : board) {\n for (Field f : row) {\n sb.append(f.symbol).append(\" \");\n }\n sb.append(\"\\n\");\n}\n</code></pre>\n\n<p>This is nicer than your <code>Location.isEmpty(board[y][x])</code> test – which by the way is now <code>boardInstance.at(someLocation) == Field.EMPTY</code>.</p></li>\n</ul>\n\n<p>You will probably also want</p>\n\n<pre><code>enum Side {\n BLACK(Field.BLACK), WHITE(Field.WHITE);\n\n public final Field field;\n\n public Side(Field f) {\n field = f;\n }\n\n public Side otherSide() {\n switch (this) {\n case BLACK: return WHITE;\n default: return BLACK;\n }\n }\n}\n</code></pre>\n\n<p>Now we can fetch the other side from any side itself: <code>side.otherSide()</code>. I also added the corresponding field type to each instance, which makes setting new fields on the board easier. The “disadvantage” of type safety is that you can't easily misuse the same <code>char</code> to represent both a <code>Side</code> and a <code>Field</code>.</p>\n\n<h3>A closing note on Memory Efficiency</h3>\n\n<p>You went through great lengths to use <code>byte</code>s and <code>char</code>s instead of <code>int</code>s and classes. The usual method is to create a <strong>good design first</strong>, and then <strong>optimize only if necessary</strong>, and when you have profiled your code to tell you <em>where</em> you can actually optimize. Java allows you to twiddle low-level bits, but it's more effective to use good abstractions.</p>\n\n<hr>\n\n<p>Topics not covered include:</p>\n\n<ul>\n<li>Algorithm correctness. You can't short circuit when looking for “Turners”, because disks across multiple axes may be turned.</li>\n<li>General coding style.</li>\n<li>Encapsulation in OOP, especially use of <code>public</code> and <code>private</code> modifiers; <a href=\"https://en.wikipedia.org/wiki/Uniform_access_principle\" rel=\"nofollow\">Uniform Access Principle</a>.</li>\n<li><code>StringBuffer</code> vs. <code>StringBuilder</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T23:35:26.743", "Id": "54179", "Score": "0", "body": "Don't use public attributes. See: http://whitemagicsoftware.com/encapsulation.pdf" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T23:41:48.890", "Id": "54180", "Score": "0", "body": "@DaveJarvis Thank you for spotting that. I decided to leave a discussion on `public` vs. `private` and accessor methods out of this answer, because quite frankly, there are more important OOP concepts for OP to understand first (classes, instances, static stuff, inheritance, interfaces). I did however mention this issue under “topics not covered”." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T23:50:16.340", "Id": "54181", "Score": "1", "body": "Yup, that's worth discarding my answer for. The only things I think are missing are (a) using interfaces to isolate the implementation details from other classes and (b) that taking turns between black and white should be expressed via the State pattern." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T23:24:30.530", "Id": "33809", "ParentId": "33780", "Score": "4" } } ]
{ "AcceptedAnswerId": "33809", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T06:39:05.480", "Id": "33780", "Score": "3", "Tags": [ "java", "game", "android" ], "Title": "Reversi game state in Android" }
33780
<p>I'm building an iOS app that uses web services extensively. I've built classes that handle the requests. However since there are a lot of web service request. I need to find out how to detect which web service to run, based on the action - registration, login, image upload, etc.</p> <p>This is just a small snippet of a very large method I came up with: </p> <pre><code>- (BOOL) wsExecution:(int) wsID wsParameters: (NSDictionary*) parameters { switch (wsID) { case WEB_SERVICE_ID { ClassWS* ws = [[ClassWS alloc] initWithURL:WEB_SERVICE_ID Url:WEB_SERVICE_URL]; break; } case AAWEB_SERVICE_ID { ClassWS* ws = [[ClassWS alloc] initWithURL:AAWEB_SERVICE_ID Url:AAWEB_SERVICE_URL]; break; } </code></pre> <p>The web service IDs are defined in a file called constants. I then map a URL to an ID in the method above. There are another 30 switch cases in this method. The Web Service IDs are just <code>int</code>s that have no relevance to the actual web service. It was just a way to check which service, based on a switch statement. </p> <p>It makes it hard to read and I think it can be done better. Is there a way to do with and remove the notion of a web service ID completely?</p> <p>To be a little more clear on where I am going with this:</p> <p>Here is another example of the switch case (I have counted 200 cases):</p> <pre><code>switch (wsID) { case RUN_ORDER_WS_ID: { NSDictionary* postData = [NSDictionary dictionaryWithObject:[parameters objectForKey:@"OrderResponse"] forKey:@"OrderResponse"]; NSMutableDictionary* newParams = [NSMutableDictionary dictionaryWithDictionary:parameters]; OrderWS* ws = [[OrderWS alloc] initWithURL:RUN_ORDER_WS_ID Url:RUN_ORDER_WS_ID_WS_URL]; self.placeClassifiedResponseWS = ws; ws.delegate = self; [newParams removeObjectForKey:@"OrderResponse"]; [ws fetch:newParams PostDataValuesAndKeys:postData]; [ws release]; break; } case GET_LIST_OF_USERS_ID: { NSDictionary* postData = [NSDictionary dictionaryWithObject:[parameters objectForKey:@"userList"] forKey:@"userList"]; NSMutableDictionary* newParams = [NSMutableDictionary dictionaryWithDictionary:parameters]; UsersWS* ws = [[UsersWS alloc] initWithURL:GET_LIST_OF_USERS_ID Url:GET_LIST_OF_USERS_URL]; self.userListWS = ws; ws.delegate = self; [newParams removeObjectForKey:@"userList"]; [ws fetch:newParams PostDataValuesAndKeys:postData]; [ws release]; break; } case GET_USER_REVIEW_FROM_ITEMS_WS_ID: { NSString* itemId = [parameters objectForKey:@"itemId"]; NSMutableDictionary* newParams = [NSMutableDictionary dictionaryWithDictionary:parameters]; NSString* newURL = [NSString stringWithFormat:GET_USER_REVIEW_FROM_ITEMS_WS_URL, itemId]; DataStoreWS = [[DataStoreWS alloc] initForComponents: [NSArray arrayWithObjects:REVIEW_COMPONENT, nil] WebserviceID: wsID Url:newURL]; self.reviewOfUserWS = ws; ws.delegate = self; [newParams removeObjectForKey:@"itemId"]; [ws fetch:newParams]; [ws release]; break; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T14:57:21.377", "Id": "54114", "Score": "1", "body": "If you're mapping Url to an invented numeric value 1:1 wouldn't it make sense to rather create a dictionary where the key was the value and the object the URL? Then you could basically replace that switch/case with one simple objectForKey: call?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T17:01:44.760", "Id": "54125", "Score": "1", "body": "What nickfalk said. But also, rethink your naming: `initWithURL:(not a URL!) Url:(wait, here's the URL?)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T19:22:49.820", "Id": "54158", "Score": "0", "body": "Thanks for the feedback gents. Admittedly, I don't know NSDictionary that well - In the morning I will have a look into it and see how it can help me. Off the top of my head I am already asking myself how am I going to do checking without a switch / if statements all over my method. Since there are over 30 web services @Flambino - Completely agree with you there - an oversight on my part. Will correct it. Once I have come up with a solution I will update this question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T21:35:45.153", "Id": "54167", "Score": "0", "body": "@Tander Once you get something running it's probably wiser to create a new question, if you're still looking for feedback. If you update this question too much, comments and answers here lose their context. Also, absolutely get to know NSDictionary. It's so fundamental to Cocoa that it's got its own JSON-like shorthand syntax (see nickfalk's answer) same as, say, `@[...]` for NSArray or `@\"...\"` for NSString." } ]
[ { "body": "<p>Here's a quick and dirty example to illustrate the benefit of the dictionary setup:</p>\n\n<pre><code>- (NSDictionary *)webServiceIDsAndURLs{\n NSDictionary *sillyExampleDictionary = @{ @1 : [NSURL URLWithString:@\"http://www.noreagle.com\"],\n @2 : [NSURL URLWithString:@\"http://www.stackOverflow.com\"],\n @3 : [NSURL URLWithString:@\"http://www.etc.com\"]};\n return sillyExampleDictionary;\n}\n</code></pre>\n\n<p>...</p>\n\n<pre><code>- (BOOL) webServicesExecution:(NSNumber *) webServiceID webServiceParameters: (NSDictionary*) parameters{\n NSURL *URL = [[self webServiceIDsAndURLs] objectForKey:webServiceID];\n ClassWebService *webService = [[ClassWebService alloc] initWithID:webServiceID URL:URL];\n\n // see, no lengty switch, yay!\n\n return YES; // Not sure what you are planning here...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T06:10:17.853", "Id": "54194", "Score": "0", "body": "Thanks for the quick example - much appreciate. The problem is that I won't be executing the same class / method on all web service IDs. Depending on the web service ID - I execute a few different web services - /search / image upload / buyer info - etc. Would NSDictionary allow for this sort of thing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T07:16:27.727", "Id": "54196", "Score": "0", "body": "The more I think about this then more I don't see how to get passed a switch statement. I'm telling the code to do this: \"If web service is (ID or URL, doesn't matter) then do this\" now the last action is anything from running a method in another class to creating and dictionary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T07:39:13.727", "Id": "54197", "Score": "0", "body": "Without detailed knowledge about your project its hard to be very concrete. It sounds like you will need SOME logic outside the dictionary stuff. It do sound however that you would be able to trim down the logic of the switch statement quite a lot if you limit this to actually messaging the methods: Find the URL from the dictionary first then lump together whatever ID's that makes sense to perform the different services..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T07:55:49.683", "Id": "54199", "Score": "0", "body": "I have updated my question with a more complete version of the switch statement. I really like the NSDictionary idea - but it seems I can't get passed the comparison that the switch does.. 200 odd times.. any thoughts? Appreciate the feedback." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T08:13:34.510", "Id": "54200", "Score": "0", "body": "Only knowing what you show me I'd say 1.Put the creation of the postData dictionary outside the switch statement, it is calling the same method after all. Pass the key into the method instead of defining it inside the method scope. Those two things alone will leave you with only the two different User/order instances and the properties." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T08:19:19.490", "Id": "54201", "Score": "0", "body": "Also: If you change the method names like Flambino suggested as soon as possible (it takes one minute) then it will be a lot easier for us outsiders to read your code. I'd also advice following Cocoa conventions and not abbreviate elements of the method names. (ws = webServices). :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T08:23:44.727", "Id": "54202", "Score": "0", "body": "Thanks for the tips Nick. I plan on rewriting the whole code and all its cases from scratch. There I will follow the correct naming conventions. :). So maybe instance of removing the switch completely, you're saying maybe I can just reduce the amount of code within it? (Still very new to iOS dev, so forgive me if I make errors) thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T08:26:28.387", "Id": "54203", "Score": "0", "body": "Yes if you manage to remove the majority of code within each case then you would be able to lump several cases together making you code a lot easier to read. To err is human. To forgive is divine. I forgive you of course. ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T08:34:55.100", "Id": "54204", "Score": "0", "body": "Ah, awesome - so create a method for all the redundant code and just reduce lines instead of removing switch .. got it. Marked your answer as correct as it actually helped me a lot!" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T20:08:17.470", "Id": "33805", "ParentId": "33793", "Score": "3" } } ]
{ "AcceptedAnswerId": "33805", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T13:45:02.830", "Id": "33793", "Score": "0", "Tags": [ "objective-c", "ios" ], "Title": "Handling web services in an iOS app" }
33793
<p>I have been studying data structures, and I'm new to this. Here is my code for the push and pop operations.</p> <ol> <li><p>I considered using a node=top, so that I can avoid O(n) operations for the push (i.e. finding the last node every time).</p></li> <li><p>I can't seem to find a better implementation for the pop operation. </p></li> </ol> <p>Let me know if my code is good or bad. You can be harsh. I'll take it positively and learn from it.</p> <pre><code>typedef struct stack_ { int data; struct stack_ *next; }stack; stack *push(stack *head, stack **top, int val){ //if stack is empty if(head == NULL){ head = (stack *)malloc(sizeof(stack *)); head -&gt; data = val; head -&gt; next = NULL; *top = head; //make current node the top of stack return head; } stack *newnode; newnode = (stack *)malloc(sizeof(stack *)); (*top)-&gt;next = newnode; //append new node to what top points to newnode -&gt; data = val; newnode -&gt; next = NULL; *top = newnode; //make current node the top of stack return head; } stack *pop(stack *head, stack **top){ if(head == NULL){ printf("Stack is empty\n"); return NULL; } stack *cur, *prev; cur = head; while(cur -&gt; next){ //Traverse to the end prev = cur; cur = cur -&gt; next; } prev -&gt; next = NULL; *top = prev; //make this node the top of stack free(cur); return head; } </code></pre> <p>Here's the <strong>main</strong> function:</p> <pre><code>int main () { stack *head, *top; head = top = NULL; while(1){ int choice; printf("1.Push\n2.Pop\n3.Exit\n"); scanf("%d", &amp;choice); if(choice == 3) break; else if(choice == 2){ head = pop(head, &amp;top); showstack(head); } else if(choice == 1){ int val; printf("Enter the value to be pushed\n"); scanf("%d", &amp;val); head = push(head, &amp;top, val); showstack(head); } else printf("Enter the correct choice\n"); } if(head) free(head); if(top) free(top); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T17:06:16.663", "Id": "54128", "Score": "1", "body": "The `free()` should go before the `return`, otherwise the former will not be called." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T17:42:27.383", "Id": "54135", "Score": "0", "body": "`pop()` should either be `void` or handle an empty stack differently. It shouldn't be returning `NULL` because `NULL` is not of type `stack`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T18:46:16.453", "Id": "54149", "Score": "0", "body": "Yeah right, my bad, I should free cur before i return." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T18:47:08.147", "Id": "54150", "Score": "0", "body": "in main I have\nhead = pop(head, top);\nso that way if I return NULL, head will be NULL thus marking that the list is empty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T18:59:51.403", "Id": "54153", "Score": "0", "body": "Okay. For better context, you could include this code as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T19:18:59.687", "Id": "54155", "Score": "0", "body": "Oh yeah, you're returning pointers, so `NULL` can be returned. `main()` also looks okay to me, but someone more familiar with C specifically may have a better idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T19:19:21.777", "Id": "54156", "Score": "0", "body": "i've another question-\n\nis freeing head and top in main a good practice?\nbecause if the list is empty, I'd be freeing a NULL value" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T19:21:18.620", "Id": "54157", "Score": "0", "body": "Assuming it's the same as in C++, I don't think it's good if you're not calling `malloc` on them. Yes, you also don't want to free a `NULL` value. If the freeing is necessary (with a call to `malloc`), then perhaps you could first do a check for `NULL`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T19:30:15.610", "Id": "54160", "Score": "0", "body": "Exactly, if I'm breaking out of the while loop right in the 1st iteration, I'd end up freeing head and top, which at that moment will be NULL and will not have malloc called on them.\n\na check for NULL will sure help in that case.\nThank you :)" } ]
[ { "body": "<p>After looking at this, I'm not sure you should be freeing <code>cur</code> since you are freeing it before it is returned. You should always see <code>NULL</code>, then.</p>\n\n<p>As for this static implementation, I'm not sure you're even doing this correctly. From the code, it looks like you're doing a queue. Why are you looping through the list? You should just be grabbing the first item, removing the pointer to <code>next</code>, then returning it.</p>\n\n<pre><code>Current List: A-&gt;B\nPush(C) : C-&gt;A-&gt;B\nPOP : remove C List: A-&gt;B return C\n// (c should no longer have a reference to A or any part of the list)\n</code></pre>\n\n<p>Stacks are supposed to be O(1). You should not be iterating through any list at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T18:48:52.890", "Id": "54151", "Score": "0", "body": "As per my implementation, I am adding nodes at the end of the list, so it'l be\n'current List: A -> B\npush(c): A -> B -> C'\nthus c is the top of the list, that's the reason I'm traversing the list till the end." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T18:56:39.283", "Id": "54152", "Score": "1", "body": "On a second note, adding nodes to the head is a way better implementation. Thank you for pointing that out." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T18:29:17.540", "Id": "33801", "ParentId": "33794", "Score": "1" } }, { "body": "<p>As dbarnes stated, a stack should be <code>O(1)</code> in terms of implementation. With this in mind you could consider increasing the memory foot print, and maintaining a pointer to the previous node at each node, or just a pointer to <code>top-1</code>.</p>\n\n<p>In terms of maintainability it might be worth considering changing your push implementation to use an <code>if/else</code> block and have a single exit point. </p>\n\n<p>Also, I would recommend always using <code>{}</code> for code blocks, such as <code>ifs/loops</code> etc. This will help prevent future accidents of code being in the wrong code blocks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T21:50:32.763", "Id": "54171", "Score": "0", "body": "I would also like to add, that if the user doesn't explicitly pop all the elements from the stack, they will never be free'd." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T09:07:04.263", "Id": "54208", "Score": "0", "body": "Ah, thanks for pointing that out. So I guess a better implementation would be to use a function instead, which would traverse till the end and free the allocated space.\n\n `void del_stack(stack *head){ \n stack *prev = NULL; \n while(head -> next){ \n prev = head; \n head = head -> next; \n free(prev); \n } \n free(head); \n }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T09:39:56.430", "Id": "54210", "Score": "0", "body": "I'm sorry, I'm new to this, but I really don't know how to indent / format code in comments. That was supposed to be a code :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T11:11:31.537", "Id": "54224", "Score": "0", "body": "Yes that would be the safest bet, @ChrisWue has provided a good base for this. He takes it a step further by using a stack & stacknode, which is a cleaner solution and removes a lot of extra baggage." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T20:27:15.273", "Id": "33806", "ParentId": "33794", "Score": "1" } }, { "body": "<p>Your implementation suffers from the fact that the user of the stack is required to carry around several pieces of information around (<code>head</code> and <code>top</code>) which can make it easy to get wrong. Also your <code>stack</code> struct does not actually represent a stack in itself, just a node in the stack and one of them just happens to be the head.</p>\n\n<p>For almost any data structure your need to keep meta data about it because it will usually make operations on the structure more efficient. Also you should have a single object which holds the information so you can pass it around easily. Last but not least you should think about the API of the data structure and what the user really cares about. In your case the user does not care about nodes or that it's a linked list. The user cares about that he/she can push values onto it and pop them of later.</p>\n\n<p>Therefore I suggest the following design:</p>\n\n<pre><code>// holds an entry in the stack and point to the next element if there is any\ntypedef struct stacknode_\n{\n int value;\n struct stacknode_* next;\n} stacknode;\n\n// the actual stack, holds the reference to the top and other meta information\n// all operation will only require a reference to this\ntypedef struct stack_\n{\n stacknode *top;\n int size;\n} stack;\n</code></pre>\n\n<p>Next define your operations:</p>\n\n<pre><code>// create a new stack\nstack *new_stack()\n{\n stack *s = malloc(sizeof(stack));\n s-&gt;top = NULL;\n s-&gt;size = 0;\n return s;\n}\n\n// delete a stack and all its nodes\nvoid delete_stack(stack *s)\n{\n stacknode *ptr = s-&gt;top;\n while (ptr != NULL)\n {\n stacknode *next = ptr-&gt;next;\n free(ptr);\n ptr = next;\n }\n free(s);\n}\n\n// pushes a value onto the stack, \n// return 1 if element was pushed on successfully, 0 otherwise\nint push(stack *s, int value)\n{\n if (s == NULL) return 0;\n stacknode *n = malloc(sizeof(stacknode));\n if (n == NULL) return 0;\n n-&gt;value = value;\n n-&gt;next = s-&gt;top;\n s-&gt;top = n;\n s-&gt;size += 1;\n return 1;\n}\n\n// removes top element from stack, \n// return 1 if an element was removed and 0 otherwise\n// return value is passed through value reference\nint pop(stack *s, int *value)\n{\n if (s == NULL || s-&gt;top == NULL) return 0;\n *value = s-&gt;top-&gt;value;\n stacknode *doomed = s-&gt;top;\n s-&gt;top = s-&gt;top-&gt;next;\n s-&gt;size -= 1;\n free(doomed);\n return 1;\n}\n</code></pre>\n\n<p>This way the user doesn't have to care how you implement the stack, just that they need a <code>stack</code> object to pass around and use.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T09:00:34.497", "Id": "54206", "Score": "0", "body": "Okay, thanks. Just what I needed.\nAlthough I've been meddling with the code and as pointed by dbarnes, if I'm inserting new nodes to the head of the list, then both the push and pop will be O(1) because the head will be the top of the list.\n\nBut I find your design very efficient and real with context of stacks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T22:52:46.960", "Id": "54501", "Score": "0", "body": "Nice answer. Remember to increment/decrement `size` though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T23:00:27.357", "Id": "54502", "Score": "0", "body": "@WilliamMorris, good point, fixed" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T08:02:35.760", "Id": "33826", "ParentId": "33794", "Score": "2" } }, { "body": "<p>Some minor comments to add to what others have said.</p>\n\n<ul>\n<li>Adding an underscore to the end of <code>struct stack</code> is just noise. It achieves\nnothing, so leave it out.</li>\n<li>Omit the spaces around <code>-&gt;</code> and add them after keywords (<code>if</code>, <code>while</code> etc)</li>\n<li><p>you are allocating only enough memory to hold a pointer to a stack node\n(<code>stack*</code>). Instead you should be allocating a node:</p>\n\n<pre><code>head = malloc(sizeof(stack));\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>head = malloc(sizeof *head);\n</code></pre>\n\n<p>Note also that there is no cast (we are writing C, not C++)</p></li>\n</ul>\n\n<hr>\n\n<p>The version suggested by @ChrisWue is elegant, but it does need\ntwo structures. You could achieve the same thing but with only a\nsingle struct (your existing <code>stack</code>) like this:</p>\n\n<pre><code>stack* push(stack *head, int data, int *result)\n{\n stack *s = malloc(sizeof *s);\n if (s) {\n s-&gt;data = data;\n s-&gt;next = head;\n *result = 1;\n }\n else *result = 0;\n return s;\n}\n\nstack* pop(stack *head, int *data, int *result)\n{\n if (!head) {\n *result = 0;\n return head;\n }\n *result = 1;\n stack *next = head-&gt;next;\n *data = head-&gt;data;\n free(head);\n return next;\n}\n</code></pre>\n\n<p>But note that you must then be careful always to assign the return value to\n<code>head</code> in the caller:</p>\n\n<pre><code> int data;\n int ok;\n stack *head = NULL;\n ...\n head = push(head, data, &amp;ok);\n if (ok) {\n ...\n }\n head = pop(head, &amp;data, &amp;ok);\n if (ok) {\n ...\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:14:00.890", "Id": "54741", "Score": "0", "body": "I must say, Beautiful code. Short and simple." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T18:15:48.443", "Id": "54742", "Score": "0", "body": "And thank you, I wish if i could +1 you, but my reps are too low to do that :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T23:13:42.600", "Id": "33959", "ParentId": "33794", "Score": "3" } } ]
{ "AcceptedAnswerId": "33826", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T15:11:47.073", "Id": "33794", "Score": "6", "Tags": [ "c", "beginner", "linked-list", "stack" ], "Title": "Reviewing my implementation of a stack using linked list" }
33794
<p>Let a,b,c be a boolean value. I need to print all values of expression a &amp;&amp; b &amp;&amp; c. I'm writing the class</p> <pre><code>public class BooleanTriple{ private boolean a,b,c; public BooleanTriple(boolean a, boolean b, boolean c){ this.a =a; this.b=b; this.c=c;} /** *Increments the value of triple with lexicographical ordering */ public void incr(){ if (!a) a=true; else if(!b){ a= false; b= true; else if (!c){ a= false; b= false; c=true; } } public boolean logProduct(){ return a &amp;&amp; b &amp;&amp; c;} } </code></pre> <p>And Main class:</p> <pre><code>public class Main{ BooleanTriple bTriple = new BooleanTriple(false,false,false); public static void main(String[] args){ for (int i=0; i&lt;8; i++){ System.out.println(bTriple.logProduct()); bTriple.incr(); } } } </code></pre> <p>But i think, that it's bad implementation. Can you correct me?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T18:37:20.767", "Id": "54148", "Score": "0", "body": "can't understand what are you trying to achieve or furthermore what is the main application of your class and methods?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T16:53:04.143", "Id": "59533", "Score": "0", "body": "Please correct the braces. I don't see a closing braces for the first `else if` block in the `BooleanTriple` class. Also please be more precise in what actually you are trying to do. I honestly don't understand your description and your question." } ]
[ { "body": "<p>if I quite understand your problem, to do a proper <code>incr()</code> method I would do so :</p>\n\n<pre><code>public class BooleanTriple {\n private boolean a,b,c;\n private int i;\n public BooleanTriple(boolean a, boolean b, boolean c){\n this.a =a; this.b=b; this.c=c;\n this.i = (a ? 1 : 0)*4+(b ? 1 : 0)*2+(c ? 1 : 0)*1; // not sure if this compile, but the idea is here\n }\n\n public void incr(){\n i = (i + 1) % 8;\n a = (i &amp; 0x4) != 0;\n b = (i &amp; 0x2) != 0;\n c = (i &amp; 0x1) != 0;\n }\n public boolean logProduct(){ return a &amp;&amp; b &amp;&amp; c;}\n}\n</code></pre>\n\n<p>With <code>i</code> going from <code>0</code> (<code>000 binary</code>) to <code>7</code> (<code>111 binary</code>) you have all the possible values for <code>a</code>, <code>b</code> and <code>c</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T21:44:16.213", "Id": "54168", "Score": "4", "body": "Or get rid of the fields `a`, `b`, and `c` entirely, and use `logProduct() { return i == 7; }`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T18:18:45.823", "Id": "33800", "ParentId": "33797", "Score": "1" } }, { "body": "<p>Try this:</p>\n\n<pre><code>public class TribleBool {\n public static void main(String[] args) {\n boolean a, b, c;\n for (int i = 0; i &lt;= 7; i++) {\n int x = i;\n a = (x / 4) &gt; 0;\n x = x % 4;\n b = (x / 2) &gt; 0;\n x = x % 2;\n c = x &gt; 0;\n\n System.out.println(logProduct(a, b, c));\n }\n }\n\n public static boolean logProduct(boolean a, boolean b, boolean c) {\n return a &amp;&amp; b &amp;&amp; c;\n }\n}\n</code></pre>\n\n<p>0 = 0 + 0 + 0</p>\n\n<p>1 = 0 + 0 + 1</p>\n\n<p>2 = 0 + 2 + 0</p>\n\n<p>3 = 0 + 2 + 1</p>\n\n<p>4 = 4 + 0 + 0</p>\n\n<p>5 = 4 + 0 + 1</p>\n\n<p>6 = 4 + 2 + 0</p>\n\n<p>7 = 4 + 2 + 1</p>\n\n<p>Translate ever column into 0 or 1 and you will find required binary combinations</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T08:36:02.603", "Id": "33832", "ParentId": "33797", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T16:02:15.130", "Id": "33797", "Score": "0", "Tags": [ "java" ], "Title": "Review implementation of boolean triple" }
33797
<p>I need to search some data encoded by a Huffman tree, but not by simply walking the tree: I need test combinations of the data for a property and continue searching based on whether the test is positive or not. To this end, I've also returned the intermediate steps of the Huffman algorithm> </p> <p>Here is the code I use to generate the extended tree:</p> <pre><code>import heapq def encode(symbfreq): tree = [[wt, [sym, ""]] for sym, wt in symbfreq] heapq.heapify(tree) while len(tree)&gt;1: lo, hi = sorted([heapq.heappop(tree), heapq.heappop(tree)], key=len) for pair in lo[1:]: pair[1] = '0' + pair[1] for pair in hi[1:]: pair[1] = '1' + pair[1] heapq.heappush(tree, [lo[0] + hi[0]] + lo[1:] + hi[1:]) return sorted(heapq.heappop(tree)[1:], key=lambda p: (len(p[-1]), p)) def next_power_of_two(n): return int(2**( ceil(log(n,2)))) def full_encode(tree): huffman_tree = encode(tree) complete_tree = huffman_tree get_intermediate_node = lambda val, arr : ''.join( [ char for char,binary in itertools.ifilter( lambda node : node[1].startswith(val),arr)] ) for val in range( next_power_of_two( len(huffman_tree) ) ): bvalue = bin(val)[2:] node = [ get_intermediate_node( bvalue , huffman_tree) , bvalue ] if node not in complete_tree: complete_tree.append( node) complete_tree =[y for y in complete_tree if y[0]!=''] complete_tree = sorted( complete_tree , key=lambda p: (len(p[-1]), p) ) return complete_tree </code></pre> <p>So for example this input: </p> <pre><code>tree = [('0',0.25),('0',0.25),('0',0.25),('0',0.125),('1',0.125)] </code></pre> <p>produces this output:</p> <pre><code>tree = [['00', '0'], ['0', '00'], ['0', '01'], ['0', '10'], ['0', '110'], ['1', '111']] </code></pre> <p>Once I've done that, I need to search the tree. Since I've got access to all the intermediate stages, I start by checking whether the data in the first leaf contains a '1' (this leaf is encoded by '0'): if this is true then I check the next leaf which has a '0' in the second position of it's code. If false, I check the leaf whose begins with '10'. I keep on doing this until I've found the leaf (and the encoding) which has only a '1' in the data. The code is below:</p> <pre><code>#searching an extended huffman list 0=&gt;left branch 1=&gt;right branch def search_huff_list(complete_tree, max_depth): defective = 0 loops = 0 stage = 0 code = ['0'] while defective == 0: loops += 1 current = complete_tree[stage] print(stage) if current[0] == '1': defective = complete_tree[stage] return defective,loops if len(current[1]) == max_depth: if current[0]=='1': defective = complete_tree[stage] return defective, loops else: defective = complete_tree[stage+1] return defective, loops if not '1' in current[0]: code[-1] = '1' code.append('0') partial_code = ''.join(code) print(partial_code) stage = complete_tree.index(next(x for x in complete_tree if x[1].startswith(partial_code) ) ) else: code.append('0') partial_code = ''.join(code) stage = complete_tree.index(next(x for x in complete_tree if x[1].startswith(partial_code) ) ) return 0 </code></pre> <p>For the input above, this algorithm finds the '1' (it's easier to debug, if the labels are 'a','b','c','d','e'). I'm building up a partial code and searching the original tree (the extended list) for the first code that begins with that series of bits.</p> <p>The main problem I have is that this is that this algorithm is complicated enough already: yet I've got to get it to find a 1 in a random tree next. There's already enough corner-case if-else catching going on (for example if I get right down to the end, and the test on the left branch comes back negative, then I know the '1' is in the right branch and I don't need to do another test). </p> <p>What could I do to make the code more readable/easier to debug? I guess what I'm actually doing isn't that efficient, but I'm struggling to think of another way to do it. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T11:31:34.947", "Id": "54423", "Score": "0", "body": "I don't understand what you are trying to achieve here. Can you explain the problem you are trying to solve?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T21:53:57.653", "Id": "54499", "Score": "0", "body": "@GarethRees Hi Gareth, I've modified the data structure so that the groups are encoded in the Huffman tree. The new code can be found here: http://stackoverflow.com/questions/19817863/sorting-huffman-leaves" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T21:55:33.427", "Id": "54500", "Score": "0", "body": "@GarethRees I'm trying to solve a variant of the 12-coin problem, but where you believe some coins are more likely to be counterfeit than others - I'm encoding that info in a Huffman tree, and then looking for a sorting/searching algorithm to find the counterfeit. https://en.wikipedia.org/wiki/Counterfeit_coin_problem" } ]
[ { "body": "<p>I've change my data structure, so that the Huffman encoding procedure defines the combinations I need to test: </p>\n\n<pre><code>class Node(object):\n left = None\n right = None\n weight = None\n data = None\n code = ''\n length = len(code)\n\n def __init__(self, d, w, c):\n self.data = d\n self.weight = w\n self.code = c\n\n def set_children(self, ln, rn):\n self.left = ln\n self.right = rn\n\n def __repr__(self):\n return \"[%s,%s,(%s),(%s)]\" %(self.data,self.code,self.left,self.right)\n\n def __cmp__(self, a):\n return cmp(self.code, a.code)\n\n def __getitem__(self):\n return self.code\n\ndef encode(symbfreq):\n tree = [Node(sym,wt,'') for sym, wt in symbfreq]\n heapify(tree)\n while len(tree)&gt;1:\n lo, hi = sorted([heappop(tree), heappop(tree)])\n lo.code = '0'+lo.code\n hi.code = '1'+hi.code\n n = Node(lo.data+hi.data,lo.weight+hi.weight,lo.code+hi.code)\n n.set_children(lo, hi)\n heappush(tree, n)\n return tree[0]\n</code></pre>\n\n<p>Then I search the groups using a function like this:</p>\n\n<pre><code>def search(tree):\ncurrent = tree.right\nloops = 0\n#defective = 0\nwhile current is not None:\n #print(current)\n loops+=1\n previous = current\n if current.data == 1:\n current = current.left\n else:\n current = current.right\nreturn loops,previous\n</code></pre>\n\n<p>There are still some changes I need to make: the data field needs to be a set (not the sum that's there currently), and I need to change the encoding strategy so that the left branch of each node always has a '0' appended to its code regardless of permutations of the labels of the input distribution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T10:15:37.540", "Id": "33975", "ParentId": "33802", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T18:44:55.270", "Id": "33802", "Score": "1", "Tags": [ "python", "algorithm" ], "Title": "Combinatorial searching of Huffman trees" }
33802
<p>Since the original post, I have explored further regarding this pattern. In an effort to fix one self-percieved flaw <em>(the lack of ability of prototype methods to access private object members)</em>, I have revised this Class pattern. As no one has responded regarding the pattern, I am offering a bounty. </p> <p>In general, only people with a high level of expertise in JavaScript will probably be able to review this to my requirements. To be clear, here are my requirements:</p> <ul> <li>I am not looking for a review that utilizes convention as its primary argument.</li> <li>Code style should only be a factor, <strong><em>if and only if</em></strong> it can keep the pattern intact: <ul> <li>All scopes must maintain their accessibility to the other scopes.</li> </ul></li> <li>Clear and Concise review regarding potential security issues.</li> <li>Verifiable performance statistics (if this is one of your review's arguments).</li> <li>Supplemental code and reasoning (for instance, where one would use Object.freeze() or places to consider validation).</li> <li>Other patterns to consider, if they can meet the scoping guidelines.</li> </ul> <p>Please, keep in mind that this is an abstract pattern. The pattern works, though the code utilizes pseudocode. <strong><em>Code Edit</em></strong> Class private member privateAccess was changed to this.privateAccess to allow for proper inheritance. There will be another edit to account for exploits of this.</p> <pre><code>[var | Namespace.]ClassName = (function(Class) { /* Any static(class-wide) privates go here */ var privateMethod = function() { return 'I\'m doing something privately'; }; /* The class prototype */ Class.prototype = {}; // or new BaseClass(); Class.prototype.propertyName = function(value) { var returnValue; // Unlock private Access this.privateAccess = true; // Forward the property access returnValue = this.privateAccessFunction('propertyName', value); // Lock it back up again! delete this.privateAccess; return returnValue; }; // Lock the function, so it can't be modified. Object.freeze(Class.prototype.propertyName); // Optional: Lock the prototype /* The class constructor */ Class.instance = function(config) { // Fail if called without using new! if (!this instanceof Class) return undefined; // So derivative classes don't share privates if (config) { var myPrivateMembers = { propertyName: 'value' }; Object.defineProperty( this, 'privateAccessFunction', { //This is the actual Getter/Setter // P.S. I like chainable properties value: function(name, value) { // Protects our function from call(obj) if (!this.privateAccess || !this instanceof Class) return undefined; if (name !== undefined &amp;&amp; typeof name === 'string') { if (value !== undefined) { myPrivateMembers[name] = value; return this; } return myPrivateMembers[name]; } return undefined; }, writable: false, configurable: false, enumerable: false } ); } }; // So that we get the Class back return Class; }([Namespace.]ClassName = [Namespace.]ClassName || function(config){ if (this instanceof [Namespace.]ClassName) return [Namespace.]ClassName.instance.call(this, config); })); </code></pre> <p>After much research, I've determined that I really like this pattern for the following reasons:</p> <p><strong>Debugging (in Chrome)</strong></p> <ol> <li>ClassNames are clear without having to open the object (even for private Classes).</li> <li>They remain this way even after minifying with several libraries.</li> </ol> <p><strong>Object Advantages</strong></p> <ol> <li>Object has access to Object Privates &amp; Static/Class Privates</li> <li>Object controls which private data to expose to Prototype Methods.</li> <li>Private data may be locked/unlocked on a per method basis.</li> </ol> <p><strong>Prototype Advantages</strong></p> <ol> <li>Prototype Methods have safe access to its own private members.</li> <li>Prototype Methods are chainable.</li> <li>Prototype Methods are only defined once. (if modifying the prototype in a constructor, it gets modified every time the constructor runs)</li> <li>Prototype Methods have access to static private members.</li> </ol> <p><strong>Known Disadvantages</strong></p> <ol> <li>Classes are a little heavier.</li> <li>PrivateAccess is not thread-safe(the privateAccess variable is static). This should be fine for synchronous code, however.</li> <li>Derivative classes must conform to a similar pattern (privateAccess and accessPrivateMember())</li> </ol> <p><strong>Final Note</strong></p> <p>In all of my years, this class pattern is the closest I've ever gotten to classical OOP, without losing any benefit that ECMAScript/JavaScript has. Additionally, it doesn't seem to require additional extension functions. Further, it doesn't inhibit the use of any other type of inheritance that JS provides. While this wasn't the goal, at the time, it is certainly a consideration for me.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T21:48:59.310", "Id": "54170", "Score": "0", "body": "Where is `value` and `value2` set ? Also, this code does not work you are returning ClassName while you are setting it causing the obvious `ReferenceError: ClassName is not defined` Please post working code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T20:28:54.760", "Id": "57326", "Score": "0", "body": "For the purposes of this question, exactly which characteristics do you consider to be part of this \"pattern\"? The use of `privateAccess` to guard against usage by outsiders? Freezing the property accessor? Anything else?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T20:31:26.383", "Id": "57327", "Score": "0", "body": "It is mentioned at the top. The Scope access properly mimicking private member access by Object **and** Prototype properties. Additionally, unmentioned, it correctly utilizes the new operator, and this should remain intact. If another way can be found to allow Object methods and Prototype methods access to the same Object level private members, that is acceptable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T20:34:58.793", "Id": "57328", "Score": "0", "body": "It must be noted that the chainability of said property was a flourish and not a required characteristic. I would also have to maintain the ability of Object and Prototype members to access Class level private members." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T15:51:07.187", "Id": "57795", "Score": "0", "body": "@FuzzicalLogic What's preventing arbitrary client code from setting `privateAccess` to `true` and fetching the private property? If you're relying on client code being polite, what's the advantage over just documenting a property as being private?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T18:45:32.073", "Id": "57827", "Score": "0", "body": "That is exactly why my answer sets it as static private again. I'm not sure that is the best answer, however, which is a major reason why this question was asked." } ]
[ { "body": "<p>It would be great if your code would actually instantiate a Class / object and maybe execute a function or get a value.</p>\n\n<p>You require <code>new</code> according to line 29, you should probably not return undefined, but either throw an exception or create the object yourself.</p>\n\n<p>All in all, your code seems overkill for little benefit and has drawbacks like JSON.stringify() not being able to serialize your class.</p>\n\n<p>I would encourage you to read <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/\" rel=\"nofollow\">Learning JS Patterns</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-15T21:10:57.150", "Id": "57456", "Score": "0", "body": "http://meta.codereview.stackexchange.com/questions/997/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T02:20:21.763", "Id": "57476", "Score": "0", "body": "Curly brace is removed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-15T17:28:31.897", "Id": "35441", "ParentId": "33807", "Score": "2" } }, { "body": "<p><strong>Regarding Code</strong></p>\n\n<p>Some changes can actually substantially improve the performance and usability of the code while keeping the requested features intact.</p>\n\n<ol>\n<li><p>Get rid of the ClassName = ClassName || function(){}. This isn't actually necessary and limits the pattern. Instead, to keep your desired features, just stick the constructor.</p></li>\n<li><p>Removing the <code>this instanceof ClassName</code> check from the passed function should be a serious consideration. This is already performed in the static instance method. This will dramatically improve performance and allow for additional capability. The only reason to keep that particular <code>instanceof</code> check is if you would like to Class to have specifically different behavior when a <code>new</code> object is not requested.</p></li>\n<li><p>I suggest renaming <code>instance()</code> to <code>create()</code>. This is a more descriptive and semantic name. Additionally, if modified to allow for static creation (without <code>new</code>), it will fit both purposes.</p></li>\n<li><p>If you are providing private access to a Class's prototype, the capability should be custom built for each class and not inherited. I would move the <code>privateAccess</code> variable back to the static level.</p></li>\n<li><p>If you want a more generalized pattern, you might weigh the option of passing <code>arguments</code> (though an es5-shim might be required) or individually passing the argument names. The 1st option is more general and accessible. The 2nd performs faster.</p></li>\n<li><p>To generalize even better with more added benefit, add <code>Class.prototype.class = Class</code>; change the <code>ClassName.instance.call</code> to <code>this.class.create.apply(this, [argument method here])</code>.</p></li>\n<li><p>Get rid of the Object.defineProperty. Its not needed to limit the access to the private members. The <code>privateAccess</code> does that. Even if the method is somehow changed, it will no longer have access to the private members it is exposing. </p></li>\n</ol>\n\n<p><strong>Result after Suggestions</strong></p>\n\n<pre><code>[var ClassName = |Namespace.ClassName = |property: ]\n(function(Class) {\n var privateAccess = false;\n\n /* Any static(class-wide) privates go here */ \n var privateMethod = function() {\n return 'I\\'m doing something privately';\n };\n\n\n /* The class prototype */\n Class.prototype = {}; // or new BaseClass();\n Class.prototype.propertyName = function(value) {\n var returnValue;\n privateAccess = true;\n returnValue = this.requestPrivate('propertyName', value);\n privateAccess = false;\n return returnValue;\n };\n\n /* The class constructor */\n Class.create = function(config) {\n var myPrivateMembers = {\n propertyName: 'value'\n };\n\n function requestPrivate(name, value) {\n if (privateAccess &amp;&amp; name !== undefined &amp;&amp; typeof name === 'string') {\n if (value !== undefined) {\n myPrivateMembers[name] = value;\n return this;\n }\n return myPrivateMembers[name];\n }\n return undefined;\n }\n\n if (this instanceof Class) {\n // Do your object setup here\n }\n else {\n return new Class(arguments);\n }\n };\n\n return Class;\n}(function(){return this.class.create.apply(this, arguments);}));\n</code></pre>\n\n<p>After these modifications, the pattern may now be used with a <code>var</code>, <code>Namespace/Module</code> or even as part of an object expression with no further changes except implementation choices. Instantiation occurs as before:</p>\n\n<pre><code>new ClassName(args);\n</code></pre>\n\n<p>with an additional option</p>\n\n<pre><code>ClassName.create(args);\n</code></pre>\n\n<p><strong>Regarding Performance</strong></p>\n\n<p>I have built a series of performance tests comparing this \"Modular Class Pattern\" with both the Prototypal and typical Constructor class structures. I considered comparing with the \"Closure Classes\" from OO.js but they are so similar that to do so would merely be a curiosity. The performance tests are quite extensive. You may look at the <a href=\"http://jsperf.com/class-pattern-comparison/3\" rel=\"nofollow\">jsPerf here</a>.</p>\n\n<p>The statistics are quite interesting, especially across browsers. The most significant point of interest here is that you can hoist any method and in most cases get member access that rivals Prototype methods and Constructor methods. Static methods can show substantially more performance. Because of this pattern, it must be noted that the only thing that differentiates a static method from a hoisted object method is whether or not the method uses <code>this</code>.</p>\n\n<p>Object creation is also interesting because it is significantly higher performing than Constructor, but only 1/2 as good (read the test notes) as defining via pure-prototype. Overall, you'll be able to see that the pattern generally performs well across implementation choices. One thing of note: things get slower when calling prototype methods internally from the constructor <strong><em>or</em></strong> constructor members from the prototype. <em>(Both access hoisted methods with similar statistics)</em> Performance drops even more when accessing private object members from outside of the constructor. </p>\n\n<p>In other words, while the other features you require may provide substantial benefits, the private access to prototype methods should be used judiciously, if at all. <em>(Interestingly, the requestPrivate function may also be used with hoisted object methods, as well)</em></p>\n\n<p><strong>Usability</strong></p>\n\n<p>It is extremely surprising how flexible this pattern is and how many ways even simple member access can be achieved. The tests regarding both inheritance and nested (public and private) classes should also be taken note of, though they are not currently public.</p>\n\n<p>All in all this seems like a pretty useful utilitarian pattern that allows min/max-ing according to the specific needs of the class more than a limitation of the pattern itself. As the additional tests become public, it may emphasize this even more.</p>\n\n<p><strong>Security</strong></p>\n\n<p>I am sorry to say, I have no further insights on the security of the private member access.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T21:52:38.420", "Id": "35497", "ParentId": "33807", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T20:53:31.653", "Id": "33807", "Score": "4", "Tags": [ "javascript", "design-patterns", "classes" ], "Title": "Issues with this pattern to restrict access to private members?" }
33807
<p>If I have a <code>Person</code> class that outlines the properties of a person and one of <code>People</code> that just contains a <code>List&lt;Person&gt;</code> like so:</p> <pre><code>public class Person { public Person(){} public int personID {get;set;} public string name {get;set;} public string address {get;set;} } public class People { public People(){} public List&lt;Person&gt; peoples {get;set;} public List&lt;Person&gt; getPeople() { List&lt;Person&gt; p = new List&lt;Person&gt;(); //create database connection //open datareader Person onePerson = new Person(); //write data to eahc property type and add data to list p.Add(onePerson); return p; } } </code></pre> <p>To call the database method that gets the people from the database I could do this:</p> <pre><code>static void main(string[] args) { People p = new People(); p.getPeople(); } </code></pre> <p>Is this how I would do this in terms of OOP?</p> <p>I'm just beginning to use these techniques in my coding as usually I would remove the <code>getPeople()</code> method from the <code>People</code> class and do this in <code>main()</code>:</p> <pre><code>static void main(string[] args) { List&lt;Person&gt; people = getPeople(); } private static List&lt;Person&gt; getPeople() { List&lt;Person&gt; p = new List&lt;Person&gt;(); //create database connection //open datareader //load data into list Person onePerson = new Person(); p.Add(onePerson); return p; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T00:52:06.323", "Id": "54183", "Score": "1", "body": "I'm not seeing the point of those empty public constructors..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T01:47:48.470", "Id": "54185", "Score": "1", "body": "`peoples` is a rather confusing name for a `List<Person>`, especially in a class called `People`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T18:59:32.653", "Id": "54331", "Score": "1", "body": "Since it's a code review site: your code is tagged as C# and looks like Java. Method names should start with upper case, same goes for properties." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T19:13:33.297", "Id": "54334", "Score": "0", "body": "@Migol YESSS!!! I'm not the only one!! (been biting my tongue on this one)" } ]
[ { "body": "<p>Very few things in life are free. C# default constructors are one of those, the compiler generates one automatically for you if your class doesn't explicitly have one! So unless you have another constructor (with parameters) and you also <em>need</em> a parameterless one, putting it in is just clutter.</p>\n\n<p>Encapsulating database operations in a dedicated object (like you're doing with your <code>People</code> class), vs doing it all in a <code>static</code> method, is a step forward in the right direction.. but I don't see what the <code>peoples</code> property is trying to encapsulate.</p>\n\n<p>Think of classes as <strong>abstractions</strong> - you have a <code>Person</code> abstraction which represents a single record in your database. Then you have a <code>People</code> abstraction which represents an object that can manipulate <code>Person</code> records. That's all nice and tidy and high-level - you don't want to mix this niceness with <strong>boilerplate-level SQL connections</strong> and queries. Doing that is writing code <em>at the wrong level of abstraction</em>.</p>\n\n<p>So the next step forward would be to create <em>another class</em> that's responsible for dealing with these things - a type that would deal with setting up a connection, running a query and then disposing the connection and every other <code>IDiposable</code> along the way.</p>\n\n<p>Once you've done that, you will (hopefully) realize you've just reinvented the wheel - and that your wheel is more than likely square. <strong>At this stage it's all good</strong>, the worst thing you could do is <em>start with</em> an Entity Data Model that does it all for you: you want to <em>understand</em> what's going on, if it feels <em>automagic</em> then you've skipped something.</p>\n\n<p>So first (well, after you've written your square wheel!) take a look at <strong>Linq to SQL</strong> and see what a <code>DataContext</code> can do for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T03:10:54.583", "Id": "54187", "Score": "0", "body": "So I should have the getPeople() defined in the People class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T03:15:59.433", "Id": "54189", "Score": "0", "body": "I see your `People` class as some sort of `Person` *repository* whose job is to perform data operations on `Person`, so yes - and then you'll want to add some `AddPerson`, `RemovePerson` and `UpdatePerson` methods, too - they all belong in there :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T03:21:53.910", "Id": "54190", "Score": "0", "body": "But the `People.peoples` property is wrong though; if the job of `People` is to perform data operations, keeping a copy of the records is breaking this *single responsibility* - and I'm not even mentioning the public setter!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T03:07:11.120", "Id": "33816", "ParentId": "33810", "Score": "5" } }, { "body": "<p>Personally, I think the better approach would be this:</p>\n\n<pre><code>public class Person\n{\n public Person(){}\n public int personID {get;set;}\n public string name {get;set;}\n public string address {get;set;}\n\n public static List&lt;Person&gt; GetPeople() { }\n}\n</code></pre>\n\n<p>Now to get a list of <code>Person</code> objects, you just do this:</p>\n\n<pre><code>var people = Person.GetPeople();\n</code></pre>\n\n<p>And just get rid of the <code>People</code> class. It isn't really doing anything. In fact, you're just building a new data structure when the <code>List&lt;T&gt;</code> is perfect already.</p>\n\n<hr>\n\n<p>Alright, in light of the comments on this post, let me dig a little deeper for you on this one.</p>\n\n<p>I believe the approach I'd take goes much further than the aforementioned simplified solution. So, let's get started. The first thing I'd do is include <a href=\"http://code.google.com/p/dapper-dot-net/\" rel=\"nofollow\">Dapper</a>. This is available via NuGet.</p>\n\n<p>The next thing I'd do is build a static method to wrap the work that needs to be done with Dapper to ensure proper use of resources. That might look like this:</p>\n\n<pre><code>using Dapper;\n\npublic static class DatabaseAccess\n{\n private static string _connString = ConfigurationManager.ConnectionStrings[\"Default\"];\n\n public static IEnumerable&lt;T&gt; Query&lt;T&gt;(string cmd,\n string filter = null,\n object parameters = null)\n {\n using (SqlConnection c = new SqlConnection(_connString))\n {\n return c.Query&lt;T&gt;(string.Format(\"{0} {1}\", cmd, filter),\n parameters);\n }\n }\n\n public static T Single&lt;T&gt;(string cmd,\n string filter = null,\n object parameters = null)\n {\n return Query&lt;T&gt;(cmd, filter, parameters).Single();\n }\n}\n</code></pre>\n\n<p>Alright, now that we've got a way to get to the database, let's fix up that POCO a little:</p>\n\n<pre><code>public class Person\n{\n private const string _selectCmd = \"SELECT personID, name, address FROM Person\";\n\n public int personID {get;set;}\n public string name {get;set;}\n public string address {get;set;}\n\n public static List&lt;Person&gt; GetPeople()\n {\n return DatabaseAccess.Query&lt;Person&gt;(_selectCmd).ToList();\n }\n\n public static Person GetPerson(int id)\n {\n return DatabaseAccess.Single&lt;Person&gt;(_selectCmd,\n \"WHERE personID = @ID\",\n new { ID = id });\n }\n}\n</code></pre>\n\n<p>and so now to use this, you just do this still:</p>\n\n<pre><code>var list = Person.GetPeople();\n</code></pre>\n\n<p>or to get one:</p>\n\n<pre><code>var p = Person.GetPerson(1);\n</code></pre>\n\n<p>Now, I could take this even further by using attributes, reflection, and dynamic SQL generation; but I just feel that's probably outside the scope of this post.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T13:32:55.403", "Id": "54247", "Score": "0", "body": "...and put all the data access code in `Person` as well? Along with an eventual `SaveChanges()` or `Delete()` method? I don't think that's right..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T13:36:22.397", "Id": "54248", "Score": "0", "body": "@retailcoder, absolutely. Who else knows how to `SELECT`, `UPDATE`, `DELETE`, or `INSERT` a `Person`? Now, I could recommend a more dynamic solution that leverages attributing, reflection, dynamic SQL creation, and Dapper; but that's outside the scope of this question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T13:50:14.190", "Id": "54251", "Score": "0", "body": "I don't agree, a DTO/POCO shouldn't be *doing* anything. The *context* knows about the database, and in this case the closest thing would be `People` - you're coupling POCO's with the database and turning an eventual upgrade to EF into a nightmare! (ok, a delete-all-that-code party!) What am I missing here? I mean, you're among the top 0.26% StackOverflow users, there's gotta be something I missed!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:01:17.453", "Id": "54256", "Score": "1", "body": "@retailcoder, first I'm not big on EF. It's bloated and dictates too much. Second, I'm not big on context objects either because they are generally misused (e.g. don't leverage `using` statements) and are heavy. I prefer Dapper over all solutions, and even in this solution, I'd use Dapper internally to actually `SELECT` the data. Now, odds are I'd end up building an extension method on `IDbConnection` to house the actual ADO work and so the method would just about be a one-liner. But the OP is just getting started here; and complicating that with a bloated OO design won't help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:07:16.697", "Id": "54258", "Score": "0", "body": "https://code.google.com/p/dapper-dot-net/ never used that. Looks nice, especially if you're after performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:18:42.337", "Id": "54260", "Score": "1", "body": "@retailcoder, have a look at my edit. I'm going to keep working on it a bit - but I think you'll get the idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T15:11:27.310", "Id": "54281", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11359/discussion-between-retailcoder-and-neoistheone)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T16:46:52.793", "Id": "54307", "Score": "1", "body": "+1 for the effort :) ...and I'm going to look into this Dapper.NET thing, too!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T13:21:50.923", "Id": "33856", "ParentId": "33810", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T00:08:36.013", "Id": "33810", "Score": "4", "Tags": [ "c#", "object-oriented", "classes", "database", "beginner" ], "Title": "Implementation of OOP for retrieving list of objects from database" }
33810
<p>I'm a newbie trying to teach myself Python. Could somebody tell me if there is a better way to write this? I am also curious as to whether or not there is anything I should not do. This code does work, but some indentation may have been lost when I pasted it.</p> <pre><code>import random def game(): yes = ['y', 'Y', 'Yes', 'yes'] number = random.randint(1, 20) numAttempts = 0 print('') name = input('What is your name? ') print('') print('Nice to meet you', name, '! I am going to guess a random number! You will have 3 tries to guess it. ' 'Good luck!') while numAttempts &lt; 3: print('') guess = int(input('Guess the number I have chosen between 1 and 20. ')) numAttempts += 1 if guess == number: print('') print('You guessed correctly! The number was', number, "!", 'Great Job', name, '!') break elif guess &gt; number: print('') print('The number is lower than', guess, "!") elif guess &lt; number: print('') print('The number is Higher than', guess, "!") else: print('') print('Sorry, the number I chose was', number, 'but you have used all 3 tries', name, '!') print('') gameover = input("Would you like to play again? Yes or No? ") while gameover in yes: game() else: print('') print('You should have chose yes. You computer will now explode!') game() </code></pre>
[]
[ { "body": "<p>A few observations:</p>\n\n<ul>\n<li>In place of the while loop with you managing the <code>numAttempts</code> index, why not use a <code>for</code> loop with the <code>in</code> keyword? i.e. <code>for numAttempts in range(3):</code></li>\n<li>Note that with the above, you can still use your <code>else</code> block (<code>for</code> supports the <code>else</code> clause! :) )</li>\n<li>Multiple games keep asking for your name. Unless your code has Alzheimer's, consider avoiding that :) </li>\n<li>Related to the above : Structurally, you've chosen to <strong>recurse</strong> to play another game. Why not keep your game atomic and keep the whole <em>offer another game</em> choice/logic external to your function? </li>\n<li>Your second <code>elif</code> does not make sense. Why not just <code>else</code> (<code>guess</code> can <strong>only</strong> be <code>&lt; number</code> now!)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T15:21:43.403", "Id": "34003", "ParentId": "33811", "Score": "2" } }, { "body": "<p>Aren't you stuck in infinite loop? Because I think this part is designed really badly:</p>\n\n<pre><code>gameover = input(\"Would you like to play again? Yes or No? \")\nwhile gameover in yes:\n game()\n</code></pre>\n\n<p>if you answer yes at least one time, gameover will always be yes, so you never leave the game.</p>\n\n<p>The easiest way to do such programs is (treat this rather as pseudocode):</p>\n\n<pre><code>def game():\n # initialization here, prints, ask for name etc\n gameover = True \n while gameover:\n # Here gamelogic\n inp = input(\"Play again?\")\n if not inp in yes:\n gameover = False\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T18:52:12.567", "Id": "34014", "ParentId": "33811", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T00:35:58.737", "Id": "33811", "Score": "2", "Tags": [ "python", "beginner", "game", "python-3.x", "random" ], "Title": "How to make this random number game better?" }
33811